gpt4 book ai didi

c - 2维指针存储字符串

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

我在用 c 编写代码时遇到了一些麻烦。我是这门语言的新手,我对 java 的了解要好得多,而 c 中的字符串让我最头疼。

当我实现这段代码时...

int num, n, i, j;
printf("How many students will you enter (min. 5)\n");
scanf("%d",&num);

char *fn = (char*)malloc(num * sizeof(char *));
char *ln = (char*)malloc(num * sizeof(char *));

for (n=0; n<num; n++)
{
*(fn+n) = (char *)malloc(20 * sizeof(char));
*(ln+n) = (char *)malloc(20 * sizeof(char));
}

printf("Enter students (firstName lastName score)\n");
for(i=0; i<num; i++)
{
scanf("%s %s", &fn[i], &ln[i]);
}
for (i=0; i<num; i++)
{
printf("%s %s\n", &fn[i], &ln[i]);
}
printf("You did it!");

它打印每个名字和姓氏的第一个字母,然后是我输入的最后一个人的全名。例如,

Jane Doe
Greg Smith

作为用户输入的输出

JGreg DSmith
Greg Smith

非常感谢您的帮助!

最佳答案

试试这个...

char **fn = (char*)malloc(num * sizeof(char *));
char **ln = (char*)malloc(num * sizeof(char *));

申报时

char *fn = (char*)malloc(num * sizeof(char *));
char *ln = (char*)malloc(num * sizeof(char *));

字符 *fn;声明一个指向字符的指针,它可以容纳一个字符串,但不能容纳一个数组字符串。

检查一下。

关于c - 2维指针存储字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43482504/

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