It shows nothing when you pass the string to the function
int main(void){
char *string[200];
getChar(string);//starts function
printf("This is the string %s",*string);//prints
return 0;
}
Void getChar(char *String[200]){
scanf(" %s",String[200]);//gets string
}
最佳答案
存在多个问题:
- 您应该使用
char
数组而不是char *
数组, - 您应该将数组直接传递给
scanf()
: Void
没有大写:void
getChar
难以读取字符串,应在使用前声明或定义。scanf("%s",
中的初始空格是多余的:%s
已经跳过了初始空格。- 您必须告诉
scanf()
要存储到目标数组中的最大字符数,否则如果输入的字符太多,您将出现未定义的行为。
修改后的版本:
#include <stdio.h>
int getword200(char *buf) {
return scanf("%199s", buf);
}
int main() {
char word[200];
if (getword200(word) == 1)
printf("This is the string: %s\n", word);
return 0;
}
上述函数假定数组的长度至少为 200。传递实际数组长度并修改代码以处理任何长度会更通用:
#include <limits.h>
#include <stdio.h>
int getword(char *buf, size_t size) {
char format[32];
int length;
if (size == 0)
return NULL;
if (size == 1) {
*buf = '\0';
return buf;
}
if (size > INT_MAX)
length = INT_MAX;
else
length = size - 1;
snprintf(format, sizeof format, "%%%ds", length)
return scanf(format, buf);
}
int main() {
char word[200];
if (getword(word, sizeof word) == 1)
printf("This is the string: %s\n", word);
return 0;
}
关于c - 从函数传递 scanf 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66633245/