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++;
}
}
'char * woord;'''char woord [71];' – BLUEPIXY 2014-10-16 19:05:59
谢谢!这似乎确定了它。但是我不完全明白为什么。当我声明char * woord并不意味着我可以输入尽可能多的字符,因为字符串的大小尚未定义。因为稍后我只是接受这个词的长度,以便在pt [i]中保留足够的空间。难道这可能是woord在记忆中的地位是未知的吗? – Actaeonis 2014-10-16 19:16:06
需要存放角色的区域。 – BLUEPIXY 2014-10-16 19:19:17