C 读取用户输入的数据
我试图编写一个简单的程序,将用户输入的字符串读入指针数组。读取过程很顺利,但是当我想向方法中添加一个额外的参数以保存实际读取的字符串数量时,它会停止工作。编译器不是很有用,所以我决定在这里解决我的问题 实际代码:C 读取用户输入的数据,c,pointers,C,Pointers,我试图编写一个简单的程序,将用户输入的字符串读入指针数组。读取过程很顺利,但是当我想向方法中添加一个额外的参数以保存实际读取的字符串数量时,它会停止工作。编译器不是很有用,所以我决定在这里解决我的问题 实际代码: #include <stdio.h> #include <stdlib.h> #include <string.h> void read(char**, int *); void write(char**); int main() { i
#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++;
}
}
#包括
#包括
#包括
无效读取(字符**,整数*);
无效写入(字符**);
int main(){
整数金额=0;
整数*金额=&amount;
字符*pt_p[1000];
读取(pt\U p、金额\U p);
写入(pt_p);
}
无效读取(字符**pt,整数*金额){
字符停止[]=“停止”;
查尔*沃尔德;
int i=0;
printf(“输入一个单词:”);
scanf(“%70s”,woord);
pt[i]=malloc(sizeof(char)*(strlen(woord)+1);
pt[i]=strcpy(pt[i],woord);
i++;
while(strcmp(停止,pt[i-1])!=0){
printf(“输入一个单词:”);
scanf(“%70s”,woord);
pt[i]=malloc((strlen(woord)+1)*sizeof(char));
pt[i]=strcpy(pt[i],woord);
i++;
}
*金额=i;
}
无效写入(字符**pt){
int i=0;
字符停止[]=“停止”;
而(strcmp(stop,pt[i])!=0{
printf(“pt[%d]->%s”,i,pt[i]);
printf(“X\n”);
i++;
}
}
您需要分配一些空间来输入字符串
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';
}
}
char*woord代码>-->charwoord[71]代码>谢谢!这似乎解决了问题。然而,我并不完全理解其中的原因。当我声明char*woord时,这并不意味着我可以输入任意多的字符,因为字符串的大小尚未定义。因为后来我只允许单词的长度在pt[I]中保留足够的空间。可能是woord在内存中的位置未知吗?需要存储字符的区域。好的,谢谢您的帮助!谢谢在此之前,我确实注意到fgets是一种更安全的手术方法,谢谢提醒。