【发布时间】:2017-05-10 00:06:14
【问题描述】:
我需要动态获取字符串,但由于我需要获取多个字符串,因此我需要使用函数。到目前为止我写了这个 (我把 //**** 放在我认为可能是错误的地方)
char* getstring(char *str);
int main() {
char *str;
strcpy(str,getstring(str));//*****
printf("\nString: %s", str);
return 0;
}
char* getstring(char str[]){//*****
//this part is copy paste from my teacher lol
char c;
int i = 0, j = 1;
str = (char*) malloc (sizeof(char));
printf("Input String:\n ");
while (c != '\n') {//as long as c is not "enter" copy to str
c = getc(stdin);
str = (char*)realloc(str, j * sizeof(char));
str[i] = c;
i++;
j++;
}
str[i] = '\0';//null at the end
printf("\nString: %s", str);
return str;//******
}
函数中的printf 正在工作,但在main 函数中没有返回。
我尝试返回void,摆脱*s 或添加,创建另一个str2 并在那里找到strcpy,或者根本不使用strcpy。似乎没有任何工作。我错过了什么吗?或者这根本不可能
//非常感谢您的回答
【问题讨论】:
-
请你的老师停止使用 malloc
-
对于
'\0'终结符,内存太少了 1。将j++;移到realloc行上方。 -
如果您的系统上可用,请考虑使用getline(3)。
-