这里对 C 有点陌生,但这是我正在做的事情。
void do_something(char* str){
char *new = str[0]+1;
printf("%s%s\n", *str, new);
}
int main(){
char input[2];
printf("Enter a two character string: \n");
scanf("%s", input);
do_something(&input);
}
这是我对do_something()
do_something("aa")
.
.
.
aaba
基本上在 do_something()
中,我想打印取消引用的输入参数 str
,然后是参数的修改版本,其中第一个字符使用 ascii 递增一个.
我不确定我是否将正确的输入传递到我的 main()
函数中。
如有任何帮助,我们将不胜感激。
最佳答案
I'm not sure if I'm passing in the correct input into the function inside of my main() function.
不,那是不正确的。
do_something(&input);
//不正确,因为输入已经是字符串
您应该将参数传递为
do_something(输入);
另外这个声明看起来真的很麻烦,而不是你想要的:
char input[2]; // this can only hold 1 char (and the other for NUL character)
你真的应该有更大的缓冲区,并且也要为 NUL 字符分配空间,比如
char input[100] = ""; // can hold upto 99 chars, leaving 1 space for NUL
Basically in do_something() I want to print the dereferenced input parameter str, and then a modified version of the parameter where the first character is incremented by one using ascii.
您可以直接修改函数 do_something
中的字符串(无需在其中创建另一个指针 - atm 这是完全错误的)
void do_something(char* str){
// char *new = str[0]+1; // <-- remove this
str[0] += 1; // <-- can change the string passed from `main` directly here
printf("%s\n", str);
}
关于C 修改函数参数中的字符串并取消引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41799385/