Advertisement
Advertisement


Finding length of char array


Question

I have some code as follows:

int i=0;
char a[7]={0x00,0xdc,0x01,0x04};
int len=0;
len = sizeof(a);
printf("The Length is : %d", len);

Here I want to find the length of the array a in c? How can this be done?

2017/08/17
1
25
8/17/2017 10:39:53 AM


sizeof returns the size of the type of the variable in bytes. So in your case it's returning the size of your char[7] which is 7 * sizeof(char). Since sizeof(char) = 1, the result is 7.

Expanding this to another example:

int intArr[5];
printf("sizeof(intArr)=%u", sizeof(intArr));

would yield 5 * sizeof(int), so you'd get the result "20" (At least on a regular 32bit platform. On others sizeof(int) might differ)

To return to your problem:

It seems like, that what you want to know is the length of the string which is contained inside your array and not the total array size.

By definition C-Strings have to be terminated with a trailing '\0' (0-Byte). So to get the appropriate length of the string contained within your array, you have to first terminate the string, so that you can tell when it's finished. Otherwise there would be now way to know.

All standard functions build upon this definition, so if you call strlen to retrieve the str ing len gth, it will iterate through the given array until it finds the first 0-byte, which in your case would be the very first element.

Another thing you might need to know that only because you don't fill the remaining elements of your char[7] with a value, they actually do contain random undefined values.

Hope that helped.

2011/05/27

If you are expecting 4 as output then try this:

char a[]={0x00,0xdc,0x01,0x04};

2011/05/27

You can try this:

   char tab[7]={'a','b','t','u','a','y','t'};
   printf("%d\n",sizeof(tab)/sizeof(tab[0]));
2013/05/12

You can do len = sizeof(a)/sizeof(*a) for any kind of array. But, you have initialized it as a[7] = {...} meaning its length is 7...

2011/05/27

If anyone is looking for a quick fix for this, here's how you do it.

while (array[i] != '\0') i++;

The variable i will hold the used length of the array, not the entire initialized array. I know it's a late post, but it may help someone.

2020/05/20

Source: https://stackoverflow.com/questions/6150258
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]