2015-11-02 224 views
1

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

这是我的代码

#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]); 
    } 
} 

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

这是samle运行

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 

什么是我的错?

另外,如果我replase

arr[i]=student_name; 

strcpy(arr[i], student_name); 

的sumple运行将是

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

欢迎来到Stackoverflow。你的问题很清楚,格式也很好。我希望你能得到一个快速的答案。 –

回答

3

你在做什么是刚分配的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]); 
} 
+0

@WhozCraig我的不好!对不起,我把'strcpy'与'strdup'混淆了。 '现在修好了。 – Linus

+0

不用担心。它更好,仍然可以使用验证'scanf'工作并将读取大小限制为9 + 1,但它比它更好。 – WhozCraig

+0

它不起作用 – user5517410

3

事实上,你有指针数组。如果你想在每个指针指向的内存中写入内容,你需要为每个指针分配一些有效的内存 - 你可以写入的地方 - 。你可以这样做:现在

for(int i = 0; i <10; i++) 
    arr[i] = malloc(MAX_LEN); // Initialize each pointer to point to valid memory 

,您可以复制该字符串的用户进入到内存中的每个指针指向:

scanf("%s",student_name); 
strcpy(arr[i],student_name); 

这样,我们要复制输入的内容用户的内容。您的方式 - 您将阵列中的每个指针指向相同的地址 - 数组student_name的第一个元素的地址。因此,阵列中的所有指针都指向相同的内存位置(即内存位置保持不变,即student_name“居住”的位置)。如果在这种情况下您尝试打印每个指针的内容,它们将全部打印相同的值 - 存储在地址student_name的数据。

最后,free每个指针稍后在数组中使用循环。