How can I create (and use) an array of pointers to an array of strings in C?

advertisements

I need to create an array of pointers that will each point to an array of strings. The base, is a size 2 array of strings (the length of the strings is unknown at start). For example an array of 2 strings (first-name and last-name):

char *name[2];

Now I need to create an array of an unknown size (entered by the user) that will point to the type that I just created. My idea was to create it this way:

char **people=name;

And then ask the user how many names he would like to enter and allocate enough space to hold all the names.

people=(char**)malloc(sizeof(char*)*num); //num is the number received by the user.

This is where things got too complicated to me and I can't figure out how to I call each individual name to put a string in it. I built a loop that will receive all the names but I have no idea how to store them properly.

for(i=0;i<num;i++){
    printf("Please enter the #%d first and last name:\n",i+1);
    //Receives the first name.
    scanf("%s",&bufferFirstName);
    getchar();
    //Receives the last name (can also include spaces).
    gets(bufferLastName);
    people[i][0]=(char*)malloc(strlen(bufferFirstName)+1);
    people[i][1]=(char*)malloc(strlen(bufferLastName)+1);
    //^^Needless to say that it won't even compile :(
}

Can anyone please tell me how to properly use this kind of an array of points? Thanks.


from cdecl:

declare foo as array of pointer to array 2 of pointer to char

char *(*foo[])[2];

So, foo[0] is a pointer to array 2 of char *

That is the array, but for your use, you want:

declare foo as pointer to array 2 of pointer to char;

char *(*foo)[2];

Now you can do:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char *(*foo)[2];

    printf("How many people?\n");
    int n; scanf("%d", &n);

    foo = malloc(sizeof *foo * n);

    for (int i = 0; i < n; i++) {
        char bufFirstName[1024];
        char bufLastName[1024];

        printf("Please insert the #%d first and last name:\n", i+1);

        scanf("%s %s", bufFirstName, bufLastName); 

        char *firstName = malloc(strlen(bufFirstName) + 1);
        char *lastName = malloc(strlen(bufLastName) + 1);

        strcpy(firstName, bufFirstName);
        strcpy(lastName, bufLastName);

        foo[i][0] = firstName;
        foo[i][1] = lastName;
    }

    for (int i = 0; i < n; i++) {
        printf("Name: %s LastName: %s\n", foo[i][0], foo[i][1]);
    }

    return 0;
}

Compile with -std=c99

Note that using scanf, strcpy, strlen like that is unsafe because there can be a buffer overflow.

Also, remember to free your malloc's!