1

While I was doing a online quiz (http://www.mycquiz.com/), I came to this question:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void myfunc(char** param){
    ++param;
}
int main(){
    char* string = (char*)malloc(64);
    strcpy(string, "hello_World");
    myfunc(&string);
    printf("%s\n", string);
    // ignore memory leak for sake of quiz
    return 0;

My first answer choice was that the string would get modified, whch didn't happen, and I am puzzled why not? Isn't he passing the address of the literal? Also a train of thought came to me that how would these situation vary?

void myfunc(char* param){
        ++param;
}
int main(){
    char* string = (char*)malloc(64);
    strcpy(string, "hello_World");
    myfunc(string);

void myfunc(char* param){
    ++param;
}
int main(){
    char string[12];
    strcpy(string, "hello_World");
    myfunc(string);

None of them seems to actually change the passed string. So if I do need to modify the string how do I pass it by reference?

Thanks.

1 Answer 1

3

In all cases, you are passing a pointer to something to a C function, modifying the pointer, not its contents, and then printing the string in main(). When you pass a pointer, a copy of it is made, so the version you modify in the function does not affect the value in main(). That is why you will not see any change in the string unless you start to modify the contents of the pointer.

If you wish to make changes to the string:

void myfunc(char** param){
        ++(*param);
}

will print ello_World since it will increment the address used by main() to point to the memory containing the string.

void myfunc(char* param){
    ++(*param);
}

will print iello_World since it will modify the first char in the actual piece of memory containing the string.

Sign up to request clarification or add additional context in comments.

4 Comments

So why does passing string or &string gives the same result? Also changing myfunc(char** param) to myfunc(char* param) has same results. Are these side effects?
I think you meant the first one to be void myfunc(char** param).
@RSahu No, I changed the declarations randomly it yielded same resuts.
@Debojyoti, that comment was meant for Mad Physicist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.