gpt4 book ai didi

c - printf 以不同的方式表现......并获取地址和值......字符串的地址和仅在取消引用后的指针

转载 作者:太空宇宙 更新时间:2023-11-04 05:15:59 26 4
gpt4 key购买 nike

printf 正在获取字符串的地址,而不是在解除引用之后获取,而在指针的情况下,它需要解除引用。

#include <stdio.h>
#include<stdio.h>

int main()
{
char str[100];
int i;
int j=0;
int *p;

p=&j;
scanf("%s",str);
for(i=0;str[i];i++)
{
if((str[i]>='A') && (str[i]<='Z'))
{
str[i]=str[i]+('a'-'A');
}
else
{
str[i]=str[i]-('a'-'A');
}
}
printf("%s",str); //it should have been printf("%s",*str); here we are passing address
printf("%d\n",j);
printf("%d",*p); //here we are passing evact value;

return 0;
}

当与 * 一起使用时它会崩溃,如果只使用 str 它工作正常...

最佳答案

printf%s 格式说明符用于打印字符串并需要一个指向第一个元素的char * 参数以 null 结尾的字符数组。 %d 格式说明符用于以十进制格式打印整数并需要 int

因为 str 是一个数组,当在表达式中使用时,它衰减为指向其第一个元素的指针。因此,表达式中的 str 的类型为 char *,这与 %s 所期望的相匹配。

*str%s 无效,因为它的类型为 char 并且值为数组中的第一个字符。对 printf 的给定参数使用错误的格式说明符会调用 undefined behavior .

*p%d 有效,因为 p 的类型是 int *,这意味着 *p 的类型为 int,它符合 %d 的预期。

关于c - printf 以不同的方式表现......并获取地址和值......字符串的地址和仅在取消引用后的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55832010/

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