Function changes the value of the given argument

Advertisements

I’m passing the Test variable that I declared in my main function to tf function. If I make a change to the argument in tf, the actual Test variable changes.

Is there any way to prevent this without creating another variable in the tf function?

The Code

#include <stdio.h>

void tf(char *argument){
    argument[0] = 'Z';
}

int main() {
    char Test[5] = "Hello";
    printf("'Test' before calling tf function : %s\n",Test);
    tf(Test);
    printf("'Test' after calling tf function  : %s\n",Test);    
    return 0;
}

The Output

'Test' before calling tf function : Hello
'Test' after calling tf function  : Zello

I googled the problem but I didn’t found anything useful.

>Solution :

For starters:
On my computer your code displays garbage.

This is wrong, it reserves 5 chars and the length of "Hello" is 5, so there is no room for the terminating NUL character:

char Test[5] = "Hello";

Don’t specifiy the length but let the compiler do it’s job:

char Test[] = "Hello";

That being said, it’s normal that the first character is modified into ‘z’, argument points to your original string. What do you expect?

There is no way to prevent this without creating another variable in the tf function, you need to make a copy of the string and operate on the copy.

But the question here is: what are you actually trying to achieve?

Leave a ReplyCancel reply