C 修改函数参数中的字符串并取消引用

C Modify String in Function Parameter and Dereference

这里对 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(input);

而且这个声明看起来很麻烦,而不是你想要的:

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);
}

试试这个:

void do_something(char* str)
{
    char new = ++str[0];
    printf("%c %s\n", new, str);
}