Reputation: 3
I think the best way to explain the question is by giving an example:
Why does this output "031" instead of "111"? Also, how would I get it to change the value "a" while only changing the DoSomething function?
#include <stdio.h>
void DoSomething(char* a);
int main(){
char a[11] = "031";
DoSomething(a);
printf("%s\n", a);
}
void DoSomething(char* a){
a = "111";
return;
}
Thank you, This probably is very simple but I can't seem to get it!
Upvotes: 0
Views: 39
Reputation: 308
The output is "031" instead of "111" because you have used a local variable a(in DoSomething function) which points to the a(array) in main function. But when you assign the base address of "111" to a(of DoSomething function) then you are making the a(of DoSomething) pointer to point to "111".The a in the main function has no change after making the pointer a( of DoSomething function) to point "111" since the a( of DoSomething function) is now pointing to "111". You are doing nothing but making the pointer to point another string. That's why the array a(of main function) has no impact.
if you want the output as "111" then try the below code.
#include <stdio.h>
void DoSomething(char** a);
int main(){
char *a = "031";
DoSomething(&a);
printf("%s\n", a);
}
void DoSomething(char**a){
*a = "111";
return;
}
Here I have used double pointer which will contain the address of a(of main function) and now dereferencing it 1 time and assigning the base address of "111" will make the pointer a(of main function) to point "111". I hope it answers your question.
Upvotes: 0
Reputation: 3774
void DoSomething(char* a){
a = "111";
return;
}
Here, a
is a local variable. Whatever you assign to this will be invalid once the function returns. If you imagine that since you are passing the address of a
, 111
should be laid down at that location, you would be wrong. In your DoSometing
function, a
is assigned the address of wherever the literal 111
resides and then the function returns making a
and the address pointed to by a
invalid.
One solution is to use the strcpy
function:
void DoSomething (char* a){
strcpy (a, "111");
return;
}
Here, the strcpy
function will copy 111
from wherever it resides to the address that was passed to DoSomething
. The address pointed to by a
is still valid as it was allocated in main
.
Upvotes: 2