Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function changes the value of the given argument

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading