c - 指针数组在c中存储字符串

标签 c arrays

我打算写一个程序来存储字符串并打印最后两个字符串 (我应该使用指针数组)。

这是我的代码

#include<stdio.h>
#include <string.h>
main()
{
    char*arr[10];
    char student_name[20];
    int i,j;

    for(i=0;i<10;i++) {
        printf("Enter the name of student %d : ",(i+1));
        scanf("%s",student_name);
        arr[i]=student_name;
    }

    for(j=7;j<10;j++) {
        printf("the name of student %d : %s\n",(j+1),arr[j]);
    }
}

它只存储最后一个字符串并打印它

这是试运行

Enter the name 1 : qqq
Enter the name 2 : www
Enter the name 3 : eee
Enter the name 4 : rrr
Enter the name 5 : ttt
Enter the name 6 : yyy
Enter the name 7 : uuu
Enter the name 8 : ii
Enter the name 9 : ioo
Enter the name 10 : ppp
the name 9 : ppp
the name 10 : ppp

我的错误是什么?

如果我更换

arr[i]=student_name;

strcpy(arr[i], student_name);

样本运行将是

Enter the name 1 : ddf
Segmentation fault (core dumped)

最佳答案

您所做的只是将 student_name 的指针分配给所有数组元素,这些元素将在您的 while 循环中的每次迭代中被替换。相反,您应该使用 strdup 将字符串保存在数组中。为防止溢出错误,您应该在 19 处截断学生姓名,因为数组的长度为 20,这将具有 nul 终止符。这可以使用特殊格式 %19s 来完成。

您永远不会为必须使用 malloc 或使用 strdup 函数为您完成的字符串分配内存。

for(i=0;i<10;i++){
  printf("Enter the name of student %d : ",(i+1));
  scanf("%19s",student_name);
  arr[i] = strdup(student_name);
}

此外,您还应该在退出前释放内存。您可以在打印字符串后执行此操作。

for(i=0;i<10;i++){
  free(arr[i]);
}

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

相关文章:

c - 输入未知大小的整数数组

arrays - 如何在Kotlin中使ByteArray保持不变

java - 逐字符读取文本文件

将 char* 中的 char 与循环进行比较

c - SHA256 使用 Openssl 导致段错误

c - 在我增加计数器后,我的数组元素的值发生了变化

arrays - 如何在 Angular Typescript 中将数组作为表单数据发布

arrays - 不匹配的类型 float64 和 int

c++ - 使用 Win32/MFC 将文件位置传递给外部进程

c - 如何使用 C 程序读取命令行输入