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

标签 c string 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(输入);

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

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/

相关文章:

C -FILE I/O 分段故障核心已转储?

c - 使用内存屏障强制按顺序执行

c - 用 C 语言进行微 Controller 编程

php - 从 PHP 版本 7.2.0 开始, "Array dereferencing"如何处理 boolean/integer/float/string 类型的标量值?

assembly - 是否可以在汇编中取消引用内部的某些内容?

c - C 中的数组声明

java - 使用 split 或 tokenizer 将字符串放入大括号内的方法

PHP删除特定字符串之前的所有字符

C: strchr() 和 index() 的区别

c++ - 解除引用的指针或迭代器的类型是什么?