简体   繁体   中英

length of a 2-D char array in a function

This is a small code snippet. In the function g(), is there any way to know the number of strings in a[] ie, in this case is 4.

In main I can get this with the help of sizeof() function, but since I am passing address to the function g() and my pc is of 64 bit that is sizeof(a) inside g() is 8 which the size of pointer, but I have to know the number of strings.

void g(char *a[])
{
    printf("%d\n",sizeof(a)/sizeof(a[0]));
}
int main()
{
    char *a[]={"1","2","3","4"};
    printf("%d\n",sizeof(a)/sizeof(a[0]));
    g(a);
}

There are many very similar questions on SO already, that explain what arrays are, how they are passed to functions, and what the implications are. This one, for example should provide you with enough information to work this one out... still:

You can't do that, not reliably anyway. Once an array is passed to a function, it decays into a pointer (the size of which is 8 on a 64bit platform, 4 on 32 bit). Your function argument char *a[] is what's known as an incomplete type. It specifies an array of pointer, but that array is of an unspecified length. What you could do is complete the type:

void g(char *a[4])
{}

In which case, your code will work, but that's a tad dangerous, because the function might be called with an array of a different length.

What is more common is to require a second argument to be passed (generally of size_t ) which specifies the length of the array that is passed:

void g(char *a[], size_t arr_len)
{}

This function is to be called like so:

g(an_array, sizeof an_array/ sizeof *an_array);

Where an_array is, of course, an array, and sizeof an_array is its size in bytes, divided by the size of the type of the values within the array. sizeof *an_array is an alternative way of writing sizeof an_array[0] . It also relies on the fact that arrays decay into pointers most of the time, and since the C standard specifies array[0] as being the same as *(array + 0) , they are interchangeable...

Just a nit-pick: you might want to change this:

char *a[]={"1","2","3","4"};

To what you're actually declaring and initializing here:

const char *a[]={"1","2","3","4"};

The char * in a are constant, they cannot be altered as they reside in read-only memory, it'd be better to either allocate the memory yourself, or write

char a[][] = {"1", "2", "3", "4"};

Which copies the string into RW memory

在C中,您需要将数组的大小传递给函数或使用sentinel值。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM