строка указателя указателя (char **) из пользовательского ввода в C - PullRequest
0 голосов
/ 12 ноября 2018

Я новичок в C, мне кажется, я не могу найти что-то на указателе char для той цели, которая мне нужна. Вот мой упрощенный код:

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
}

Я не уверен, что правильный формат для указателя указателя char при получении пользовательского ввода. Как видите, я пытаюсь получить список имен людей вместе с их номером. Я знаю, массивы, матрицы и тому подобное легко, но это должен быть только указатель указателя. Спасибо!

1 Ответ

0 голосов
/ 12 ноября 2018

Если вы хотите хранить N строк длиной до 20 символов в каждой, вам нужно выделить не только пространство для указателей на строки, но также пространство для хранения самих строк. Вот пример:

#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);
}
...