C中用户输入的指针指针字符串(char **)

时间:2018-11-12 01:44:39

标签: c string pointers pointer-to-pointer

我是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 :(得分:0)

如果要存储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);
}