简体   繁体   English

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

[英]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. 我是C语言的新手,出于我需要的目的,我似乎在指针指针char上找不到太多内容。 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. 我不确定在获取用户输入时指针指标char的正确格式是什么。 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! 谢谢!

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. 如果要存储N个字符串(每个字符串最多20个字符),则不仅需要分配用于指向字符串的指针的空间,还需要分配用于存储字符串本身的空间。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM