-1

I am working on a practice problem that asks me to remove the first character in a string. Ex. char *string = "Rudolph", after calling removeFirst(string), string now equals "udolph".

I noticed, if I do it all in my main, I get the output "udolph". Here is my code:

int main() {
  char *string = "Rudolph";
  printf("%s\n", string);
  //removeFirst(string);
  string++;
  printf("%s\n", string);
  return 0;
}

However, if I were to call another function, my output is Rudolph. Here again is my code:

void removeFirst(char *string) {
  if (string == "" | string == NULL)
    return;
  string++;
}

int main() {
  char *string = "Rudolph";
  printf("%s\n", string);
  removeFirst(string);
  //string++;
  printf("%s\n", string);
  return 0;
}

Given that I'm working with pointers, I thought that the changes I make in removeFirst should also make it to main. Why doesn't it work that way?

DrJessop
  • 462
  • 6
  • 26
  • Some fundamental misunderstandings in the `removeFirst()` function: first, the variable `string` is local to that function, so changing it in the function will have no effect on the one in `main()`. Second, you can't compare strings with `==`, that just compares pointers. Third, even if you fixed those things, `string` in main is assigned to a literal, and string literals are read-only, so you'd likely segfault.\ – Lee Daniel Crocker Dec 12 '17 at 18:54

1 Answers1

1

You are changing to the local variable. C is pass by value. A char* with same value as that of string is there in the called function removeFirst(). You make changes to it and then you expect the changes made on the copy to be reflected in the original variable. That's not going to happen here. That's why you don't get the same result as before case.

string == "" comparing two addresses not the content as you may have expected.

You can make changes like this

removeFirst(&string);

void removeFirst(char **string) {
  if (*string == NULL)
    exit(1);
  (*string)++;
}

Then in main()

printf("%s\n", string); outputs udolph.

In this is case you pass the address of the pointer variable. You are now changing to the original variable by accessing the memory contained in the called function's local variable string. That is what retain the changes in main().

user2736738
  • 30,591
  • 5
  • 42
  • 56