[英]printf is behaving in different ways…and taking address as well as value…address of string and for a pointer only after dereferencing
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 *
參數,該參數指向以空字符結尾的字符數組的第一個元素。 %d
格式說明符用於以十進制格式顯示整數,並且期望為int
。
由於str
是一個數組,因此在表達式中使用時,它將衰減為指向其第一個元素的指針。 因此,表達式中的str
類型為char *
,與%s
期望的類型匹配。
*str
對於%s
無效,因為它的類型為char
並且具有數組中第一個字符的值。 對printf
的給定參數使用錯誤的格式說明符會調用未定義的行為 。
*p
對%d
有效,因為p
類型為int *
,這意味着*p
類型為int
,與%d
期望的匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.