printf
is taking address of string and not taking after dereferencing, whereas in case of pointer it is required to dereference.
#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;
}
when used with *
it crashes and if only str
is used it works fine...
The %s
format specifier to printf
is used to print a string and expects a char *
argument which points to the first element of a null-terminated character array. The %d
format specifier is used to print an integer in decimal format and expects an int
.
Since str
is an array, when used in an expression it decays into a pointer to its first element. So str
in an expression has type char *
, which matches what %s
expects.
*str
is not valid for %s
because that has type char
and has a value of the first character in an array. Using the wrong format specifier for a given argument to printf
invokes undefined behavior .
*p
is valid for %d
because p
has type int *
, meaning that *p
has type int
, which matches what %d
expects.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.