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



我是C的新手,我似乎找不到太多指针指针字符来满足我的需要

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: %lfn",*(nAmer + tempX), *(nUmer + tempX)); //andor this
}

我不确定在获取用户输入时指针指针字符的正确格式是什么。正如你所看到的,我正试图得到一份名单上的人的名字和他们的号码。我知道数组、矩阵之类的东西很容易,但它必须只是一个指针。谢谢

如果您想存储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:  %in", 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: %lfn", 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);
}

最新更新