在一场在线代码竞赛中,他们给出了一个问题,问题的解决方案代码必须写在这个函数中
char* iteration(char* input1) { // write code here}
当我在 Windows 中的 Code::Blocks IDE 中编写解决方案时,我编写了 main 函数,如下所示
int main(){
char *input1,*ans;
printf("Enter The Expression:");
//scanf("%s",input1);
//scanf("%s",&input1);
//gets(input1);
/*All the commented statements compiled without errors and warning but generated exe file stoped immediately after this statements */
printf("\nInput 1 is: %s",input1);
ans=iteration(input1);
printf("\nAns is: %s",ans);
getch();
return 0;}
所以我想在字符指针中获取输入并希望传入函数。但我不能,因为 scanf 和 gets 不适用于字符指针。
我知道,将输入作为字符数组,然后使用 strcpy() 将其复制到字符串中效果很好。但我不知道他们尝试的输入的最大长度是多少,我也想更喜欢仅使用字符指针的完整代码
是否可以将 scanf 和 gets 与字符指针一起使用?为什么?
如果是的话我哪里出错了?
如果不是,我应该如何传递参数并处理字符指针。
为什么代码编译后没有错误和警告?
最佳答案
您可以将字符指针传递给fgets
(但您也许应该使用 getline(3) )。但是,文字字符串通常是一个只读数组(位于 code segment 的 executable 中),无法被覆盖。
这是一种将指针传递给 fgets
的愚蠢方法:
#define MYSIZE 128
char *str = malloc(MYSIZE);
if (!str) { perror("malloc"); exit(EXIT_FAILURE); };
memset (str, 0, MYSIZE);
if (fgets(str, MYSIZE-1, stdin)) {
printf("got line: %s\n", str);
}
但你确实应该使用 getline
来代替。它将为您执行malloc
。当然你稍后需要free(str)
如果您更喜欢使用 scanf(3) 仔细阅读其文档,然后使用它。特别是,请注意如何传递最大字符串(或单词)长度,并且您始终应该测试扫描的项目计数结果。
关于c - 为什么字符指针不能用来传入gets()和scanf()函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33678926/