为什么字符指针不能用于传入gets()和scanf()函数?

时间:2015-11-12 18:43:23

标签: c arrays string pointers

在其中一个在线代码竞赛中,他们给出了一个问题,问题的解决方案代码必须写在这个函数中

char* iteration(char* input1) { // write code here}

当我在Windows中的Code :: Blocks IDE中编写解决方案时,我已经编写了如下主要功能

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不能使用charcater指针。

我知道通过将Input作为字符数组然后使用strcpy()将其复制到字符串中,效果很好。但我不知道他们尝试的输入的最大长度是多少,我也希望只用uisng字符指针来保存完整的代码

是否可以使用scanf并使用字符指针?为什么呢?

如果是,我出错了?

如果不是,我应该如何传递参数和处理字符指针。

为什么代码编译时没有错误和警告?

2 个答案:

答案 0 :(得分:4)

可以将字符指针传递给fgets(但您可能应该使用getline(3))。但是,文字字符串通常是只读数组(在code segmentexecutable中),无法覆盖。

将指针传递给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)仔细阅读 其文档,请使用它。特别是,请注意如何传递最大字符串(或单词)长度,并始终测试扫描的项目计数结果。

答案 1 :(得分:0)

根据定义,常量不能修改。这就是使它们保持不变的原因。

char *input1="NANpp";

这使得input1指向常量“NANpp”。因此input1指向无法修改的内容。但后来iteration尝试修改input1指向的内容。那不行。