2016-04-30 154 views
0

我想每个5个本书的名字在数组中保存并打印出来。但是我在这里做错了什么? 输出打印出最后一个输入5次。从命令行获取输入?

#include <stdio.h> 

int main(int argc, const char * argv[]) 
{ 
    char * books[5]; 
    char currentBook[1024]; 
    for(int i = 0; i < 5; i++) 
    { 
     printf("Enter book:\n"); 
     gets(currentBook); 
     books[i] = currentBook; 
    } 

    for(int i = 0; i <5; i ++) 
    { 
     printf("Book #%d: %s\n", i, books[i]); 
    } 
} 
+1

切勿使用'gets'。这本质上是不安全的。 –

+3

您存储currentBook'的'地址在每个数组元素,其中包含最新的条目。我建议'书籍[I] =的strdup(currentBook);'然后事后你必须'free'每个指针数组中,因为'strdup'从'malloc'获取存储器。 –

回答

2

鉴于你的声明

char * books[5]; 
char currentBook[1024]; 

,这个代码...

books[i] = currentBook; 

...分配books[i]是一个指针开始数组currentBook。您可以多次执行各种各样的i,从而生成指向相同阵列的指针数组。当你稍后打印每一个点的字符串时,它当然是相同的字符串。

您可以通过使用strdup()复制输入缓冲区而不是分配books的每个元素指向相同的东西来解决问题。

0

的问题是,你的指针将指向相同的字符串currentbook。 使用的strdup(),而不是复制的字符串:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main(int argc, const char * argv[]) 
{ 
    char *books[5]; 
    char currentBook[1024]; 
    for (int i = 0; i < 5; i++) 
    { 
     printf("Enter book:\n"); 
     fgets(currentBook, sizeof(currentBook), stdin); 
     books[i] = strdup(currentBook); 
    } 

    for (int i = 0; i < 5; i++) 
    { 
     printf("Book #%d: %s\n", i, books[i]); 
     free(books[i]); 
    } 
} 
0

我想每个5个本书的名字存储阵列

然后,你需要定义一个合适的阵列英寸

假设要存储5名,每一个都具有42个字符的最大长度,则需要定义各自为42 + 1个字符的阵列5个元素的阵列。

即定义char个二维数组这样

char books [5][42 + 1]; /* Define one more char then you need to store the 
          `0`-terminator char ending each C "string". */ 

而且使用这样的

for(int i = 0; i < 5; i++) 
{ 
    printf("Enter book:\n"); 
    fgets(books[i], 42 + 1, stdin); 
} 

为什么要使用gets()你可能想在这里阅读:Why is the gets function so dangerous that it should not be used?


更多的0封端的串这里的概念:https://en.wikipedia.org/wiki/Null-terminated_string