#include<stdio.h>
#include<conio.h>
void print(char *arr);
void main()
{
clrscr();
char temp='r';
print(&temp);
getch();
}
void print(char *arr)
{
int arrsz=sizeof(arr);
printf("size is %d",sizeof(arr));
printf("char is %c",arr);
}
Run Code Online (Sandbox Code Playgroud)
为什么我得到这个输出?
size is 1
char is e
Run Code Online (Sandbox Code Playgroud)
当然应该说char is r?
sho*_*nex 13
您打印的地址不是值使用
printf("char is %c",*arr);
Run Code Online (Sandbox Code Playgroud)
尝试通过调试器来运行它以了解发生了什么,请问一个真实的问题,比如你认为应该发生什么,以及你所观察到的.通过这样做,你可能会回答你自己的大部分问题.
顺便说一下,一旦打印出来,arr就是一个局部变量,而sizeof无法知道原始数组的大小,所以应该打印大小为4.下面的代码显示了这种行为,以及数组和指针之间的区别当谈到sizeof.如果你试试
编辑:感谢Daniel的评论,将代码更改为我实际测试过的内容,而不仅仅是猜测
#include <stdio.h>
void print(char *);
int main(int argc, char ** argv)
{
char temp = 'r';
char temp2[] = {'a','b'};
char temp3[] = {'r'};
print(&temp);
print(temp2);
print(temp3);
printf("sizeof temp is %d\n",sizeof(&temp));
printf("sizeof temp2 is %d\n", sizeof(temp2));
printf("sizeof temp3 is %d\n",sizeof(temp3));
return 0;
}
void print(char * arr)
{
printf("size of arr is %d\n", sizeof(arr));
printf("arr contains %c\n", *arr);
}
Run Code Online (Sandbox Code Playgroud)
你得到 :
size of arr is 4
arr contains r
size of arr is 4
arr contains a
size of arr is 4
arr contains r
sizeof temp is 4
sizeof temp2 is 2
sizeof temp3 is 1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
340 次 |
| 最近记录: |