user3614293
user3614293

Reputation: 425

C adding to double pointer array

I need to use char **userIDArray to store a list of user ID's (32 chars max), which will be added to the list one by one. The number of ID's to be stored is unknown.

My initial idea was to create another char **start - a pointer to the beginning of the array. Then I would allocate space in *userIDArray. The code should be something like:

if (arraySize == 0)
{
     userIDArray = malloc(sizeof(*userIDArray));
     *userIDArray = malloc(32 * sizeof(char));
     strcpy(*userIDArray, userID);
     start = userIDArray;
}
else
{
     int i = 0;
     while(i < arraySize && strcmp(*userIDArray, userID) != 0)
     {
          i++;
          userIDArray++;
     }
     if(strcmp(*userIDArray, userID) == 0)
     {
        printf("already in the array");
     }
     else
     {
         arraySize++;
         start = realloc(start, arraySize * sizeof(*userIDArray));
         *userIDArray = malloc(32 * sizeof(char));
         strcpy(*userIDArray, userID);
     }
     userIDArray = start;
}

This gives me all kinds of errors. Is there any simpler way to add to multidimensional arrays?

Upvotes: 0

Views: 1385

Answers (1)

user1483946
user1483946

Reputation: 151

The number of ID's to be stored is unknown.

In this case, an array is a poor choice for storage. If you create an array of strings, a char**, then you'll need to allocate enough space for the maximum number of strings up front or continuously reallocate userIDArray.

A better design would be to store the data in a structure such as a linked list, which is easy to add or remove from.

Upvotes: 3

Related Questions