gpt4 book ai didi

c - 请解释这个奇怪的输出

转载 作者:行者123 更新时间:2023-12-01 15:51:39 25 4
gpt4 key购买 nike

#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);
}

为什么我会得到这个输出?

size is 1
char is e

它肯定应该说 char is r 吗?

最佳答案

您打印地址而不是使用的值

printf("char is %c",*arr);

尝试通过调试器运行它以了解发生了什么,并提出一个真实的问题,例如您认为应该发生什么,以及您观察到的是什么。通过这样做,您可能会自己回答大部分问题。

顺便说一句,在打印时,arr 是一个局部变量,而 sizeof 无法知道原始数组的大小,因此它应该打印大小为 4。下面的代码显示了这种行为,以及两者之间的区别array 和 pointers 当涉及到 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);
}

你得到:

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

关于c - 请解释这个奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1048952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com