开发者

C Array address confusion

开发者 https://www.devze.com 2023-01-18 09:15 出处:网络
Suppose I have the following code: main () { char string[20]; printf(\" The String is %s \\n \" , &str);

Suppose I have the following code:

main ()
{
  char string[20];

  printf(" The String is %s \n " , &str);
}

What would printf(" The String is %s \n " ,&str); give?

Suppose str points to location 200,开发者_Python百科 what would &str give??


Not sure what you exactly want, but according to the question title, you might want to know a couple of things about array addresses:

main ()
{
  char string[20];
  char *str = &string;

  printf("The String addr is %p \n" , &string);
  printf("The String addr is %p \n" , &string[0]);
  printf("The String addr is %p \n" , str);
  printf("The String addr is %p \n" , &str[0]);
}

all these are equivalent ways to get the address of the "array". The address of the array is the address of the first element of the array.


You should get a warning saying that

%s expects char* but argument 2 has char (*)[20] type.

The address is not printed, in fact nothing is printed.


Assuming you actually initialized the array with a string (which you didn't, but let's assume you did) then:

It is of type char (*)[20]. It'll give the same output as

printf("The String is %s\n", str)

&str points to the same memory location as str but is of different type; namely pointer-to-array. The type of str is of type pointer-to-char.

0

精彩评论

暂无评论...
验证码 换一张
取 消