why sizeof(a pointer) returns incorrect value? [duplicate]

拈花ヽ惹草 提交于 2019-12-25 14:30:43

问题


Possible Duplicate:
Sizeof string literal

On my windows7 mingw environment, I tried this:

char str[] = "hello";

The value of sizeof(str) is 6, not 4 or 8.

How can this happen?


回答1:


sizeof(str) returns the number of bytes in the string which includes the terminating null character. I.e., "hello\0" makes for 6 bytes in your array.

If instead you had had

char* str = "hello";

then sizeof(str) would have returned the number of bytes in the pointer str (4 for 32-bit systems).

You may find this SO question Why does sizeof return different values for same string in C? of interest.




回答2:


The "sizeof()" operator returns the number of bytes. In the case of your string, it happens to be 6 (5 characters plus the null byte). For a 6 element integer array, it's 24 (at least on my 32-bit Linux system). And for a pointer, it will be 4 (again, for a 32-bit system).

#include <stdio.h>

int
main (int argc, char *argv[])
{
  char str[] = "Hello";
  char *s = "Hello";
  int a[] = {1, 2, 3, 4, 5, 6};
  printf ("sizeof (str)=%d, sizeof(s)=%d, sizseof(a)=%d\n",
    sizeof (str), sizeof(s), sizeof(a));
  return 0;
}

RESULT:

sizeof (str)=6, sizeof(s)=4, sizeof(a)=24



回答3:


It's because str is an array of chars. sizeof(array) will tell you the number of bytes that the array occupies, and since str is an array of chars, each element is only 1 byte, including the null terminating character, for 6 bytes.

You can get the number of elements in an array using: sizeof(array)/sizeof(array[0]), and so this could be more explicitly written: sizeof(str)/sizeof(str[0]), but if str is an array of char then this is equivalent to just sizeof(str).

Note that this isn't generally applicable to C strings, for the length of a string, use strlen. For instance:

char *str = "hello";
sizeof(str);  // returns 4, since str is declared as char*, not char[]


来源:https://stackoverflow.com/questions/11919369/why-sizeofa-pointer-returns-incorrect-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!