开发者

How to find the number of elements in char** array?

I have an string array in the form of char**

I am struggling to find the length of that array:

typedef struct _stringArray
{
    int (*Length)(char**);
    char** (*Push)(char**, char*);
    char** (*Pop)(char**, char*);
}StringArray;

StringArray* StringArray_Constructor(void)
{
    StringArray* stringArray = 开发者_运维知识库(StringArray *)malloc(sizeof(StringArray));
    stringArray->Push = StringArray_Push;
    stringArray->Pop = StringArray_Pop;
}

char** StringArray_Push(char** array, char* string)
{
    int size = 0; //how to find how many elements in the array object???

    array = realoc(array, (sizeof(char *) * (size + 1));
    array[size] = string;
    return array;
}

Any help would be greatly appreciated! Thanks.


With C, you will have to keep track of this yourself.


There's no way you can infere the lenght of the array, the only way you could do it is doing it dynamically. You have an array of strings (char**), so you have the pointer to the first character of the first element of the array. We all know that, in C, all strings must ed with '\0', so you can "scan" for the strings of the array taking this pointer and saving it, then increment it until you get a '\0'. The next pointer is the first character of the next string and so on.

But this have a huge flaw: memory is not as linear as it appears. What I'm saying is that your first string can be entirely allocated at, e.g., address 0x0010101A, and the next at 0xF0FF0001, so or you hae a huge string @0x0010101A or there is a bunch of data beetween them and you do not know if they are part of the string or not.

And that's why you need to maintain a counter of how many strings you have. :)

PS: and as this number is always greater than zero, you should use unsigned int to type it.


You have a few options:

1) Pass a size parameter around which indicates the current size of your char **array.

2) Declare a structure which combines char **array with int array_size (really the same as #1).

3) If your array will always contain valid pointers (i.e. non-NULL) then create an extra element at the end which is always set to NULL. This acts as an array terminator, you can scan char **array looking for this terminating element:

int size;

for (size = 0; array[size] != NULL; size++);

// 'size' is number of valid entries in 'array'.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜