在其中一个在线代码竞赛中,他们给出了一个问题,问题的解决方案代码必须写在这个函数中
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并使用字符指针?为什么呢?
如果是,我出错了?
如果不是,我应该如何传递参数和处理字符指针。
为什么代码编译时没有错误和警告?
答案 0 :(得分:4)
您可以将字符指针传递给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)仔细阅读 其文档,请使用它。特别是,请注意如何传递最大字符串(或单词)长度,并始终测试扫描的项目计数结果。
答案 1 :(得分:0)
根据定义,常量不能修改。这就是使它们保持不变的原因。
char *input1="NANpp";
这使得input1
指向常量“NANpp”。因此input1
指向无法修改的内容。但后来iteration
尝试修改input1
指向的内容。那不行。