2014-10-16 86 views
0

我想写一个简单的程序,将用户输入的字符串读入指针数组。阅读很顺利,但是当我想为我的方法添加一个额外的参数以保存实际阅读的字符串数量时,它会停止工作。编译器不是非常有用,所以我决定在这里解决我的问题。C读取用户输入的数据

实际代码:

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

void read(char**, int *); 
void write(char**); 

int main() { 
    int amount = 0; 
    int * amount_p = &amount; 
    char *pt_p[1000]; 
    read(pt_p,amount_p); 
    write(pt_p); 
} 


void read(char ** pt, int * amount) { 

    char stop[] = "STOP"; 
    char* woord; 
    int i = 0; 

    printf("Enter a word: "); 
    scanf("%70s", woord); 
    pt[i] = malloc(sizeof(char)*(strlen(woord)+1)); 
    pt[i] = strcpy(pt[i], woord); 

    i++; 

    while(strcmp(stop,pt[i-1]) != 0) { 
      printf("Enter a word: "); 
      scanf("%70s", woord); 
      pt[i] = malloc((strlen(woord)+1)*sizeof(char)); 
      pt[i] = strcpy(pt[i], woord); 
     i++;  
    } 
    *amount = i; 

} 

void write(char ** pt) { 
    int i = 0; 
    char stop[] = "STOP"; 
    while(strcmp(stop,pt[i]) != 0) {  
     printf("pt[%d]-> %s",i,pt[i]); 
     printf("X \n"); 
     i++; 
    } 

} 
+0

'char * woord;'''char woord [71];' – BLUEPIXY 2014-10-16 19:05:59

+0

谢谢!这似乎确定了它。但是我不完全明白为什么。当我声明char * woord并不意味着我可以输入尽可能多的字符,因为字符串的大小尚未定义。因为稍后我只是接受这个词的长度,以便在pt [i]中保留足够的空间。难道这可能是woord在记忆中的地位是未知的吗? – Actaeonis 2014-10-16 19:16:06

+0

需要存放角色的区域。 – BLUEPIXY 2014-10-16 19:19:17

回答

2

您需要分配一些空间,可以在其中输入字符串

char* woord;刚刚宣布指向无处特别的指针。

代替它声明为

char woord[128]; 

到堆叠您的输入上分配128个字节。

也使用fgets()代替scanf()阅读字符串,这样就可以防止用户输入过大的字符串。

if (fgets(woord, sizeof(wooord), stdin) != NULL) 
{ 
    char* p = strchr(woord, '\n'); 
    if (p != NULL) 
    { 
    *p = '\0'; 
    } 
} 
+0

谢谢!在提醒之前,它确实引起了我的注意,因为fgets对于这项操作是一种更安全的方法。 – Actaeonis 2014-10-16 19:39:37