gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:14:49 24 4
gpt4 key购买 nike

我是 C 语言的新手,我似乎找不到太多关于 pointer pointer 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
}

我不确定获取用户输入时指针指针字符的正确格式是什么。如您所见,我正在尝试获取人员姓名及其号码的列表。我知道数组、矩阵和类似的东西很容易,但它必须只是一个指针指针。谢谢!

最佳答案

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

关于c - C 中用户输入的指针指针字符串 (char **),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53255035/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com