Search code examples
cstringpointerspointer-to-pointer

pointer pointer string (char **) from user input in C


I am new to C, I can't seem to find much on pointer pointer char for the purpose that I need it. Here's my code simplified:

int total, tempX = 0;
printf("Input total people:\n");fflush(stdout);
scanf("%d",&total);

char **nAmer = (char**) malloc(total* sizeof(char));

double *nUmer = (double*) malloc(total* sizeof(double));;

printf("input their name and number:\n");fflush(stdout);

for (tempX = 0;tempX < total; tempX++){
    scanf("%20s %lf", *nAmer + tempX, nUmer + tempX); //I know it's (either) this
}
printf("Let me read that back:\n");
for (tempX = 0; tempX < total; tempX++){
    printf("Name: %s Number: %lf\n",*(nAmer + tempX), *(nUmer + tempX)); //andor this
}

I'm not sure what the proper format for pointer pointer char when getting user input. As you can see, I'm trying to get a list of people's name along with their number. I know Arrays, Matrices, and stuff like that is easy, but it has to be a pointer pointer only. Thanks!


Solution

  • If you want to store N strings of up to 20 characters each, you need to allocate not just the space for the pointers-to-the-strings, but the also the space to hold the strings themselves. Here's an example:

    #include <stdlib.h>
    #include <stdio.h>
    
    int main(int argc, char ** argv)
    {
       int total, tempX = 0;
    
       printf("Input total people:\n");fflush(stdout);
       scanf("%d",&total);
       printf("You entered:  %i\n", total);
    
       // note:  changed to total*sizeof(char*) since we need to allocate (total) char*'s, not just (total) chars.
       char **nAmer = (char**) malloc(total * sizeof(char*));
       for (tempX=0; tempX<total; tempX++)
       {
          nAmer[tempX] = malloc(21);  // for each string, allocate space for 20 chars plus 1 for a NUL-terminator byte
       }
    
       double *nUmer = (double*) malloc(total* sizeof(double));;
    
       printf("input their name and number:\n");fflush(stdout);
    
       for (tempX = 0; tempX<total; tempX++){
           scanf("%20s %lf", nAmer[tempX], &nUmer[tempX]);
       }
    
       printf("Let me read that back:\n");
       for (tempX = 0; tempX<total; tempX++){
           printf("Name: %s Number: %lf\n", nAmer[tempX], nUmer[tempX]);
       }
    
       // Finally free all the things we allocated
       // This isn't so important in this toy program, since we're about
       // to exit anyway, but in a real program you'd need to do this to
       // avoid memory leaks
       for (tempX=0; tempX<total; tempX++)
       {
          free(nAmer[tempX]);
       }
    
       free(nAmer);
       free(nUmer);
    }