c - 2维指针存储字符串

标签 c pointers multidimensional-array 2d

我在用 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/

相关文章:

numpy - 多个 3D 阵列转为一个 2D 阵列

c - 未初始化的指针导致核心转储

javascript - Vue.js 从数组中弹出一个嵌套对象

c - 如何在 c 中为 linux 操作系统创建两个进程?

带有标准输入的 C++ 字符数组

c++ - 使用指针 vector 循环其他 vector

c++ - 除非从方法本身内部调用方法不会更改值

php - 将 php 数组转换为 csv 字符串

c - 有没有更好的方法来进行 C 风格的错误处理?

c - 从函数返回后是否可以访问函数参数?