Search code examples
cstringdereference

C Modify String in Function Parameter and Dereference


A bit new to C here, but this is what I'm working on.

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

Here's my expected output fordo_something()

do_something("aa")
.
.
.
aaba

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.

I'm not sure if I'm passing in the correct input into the function inside of my main() function.

Any help would be appreciated.


Solution

  • I'm not sure if I'm passing in the correct input into the function inside of my main() function.

    No that's incorrect.

    do_something(&input); // incorrect because input is already string

    You should pass the parameter as

    do_something(input);

    Also this declaration looks really troubling, and not what you want:

    char input[2]; // this can only hold 1 char (and the other for NUL character)
    

    You should really have bigger buffer, and DO allocate for the NUL character as well, something like

    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.

    You can directly modify the string inside function do_something (and no need to create another pointer in it - atm it was completely wrong)

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