Reputation: 2481
in this program i am accessing a global char array through a function pointer,changing string values with address by address in char pointer makes difference in global char array , but when changing the string as whole string it does't make any difference in the global array
#include <stdio.h>
#include <string.h>
void function(char *string);
char str[20] = "Hello"; // global char array
int main()
{
function(str);
return 0;
}
void function(char *string)
{
int i;
printf("%s\n",string);
printf("%s\n", str);
for(i = 0;i < strlen(string);i++)
string[i] = 'a';
printf("%s\n",string);
printf("%s\n", str);
string = "jhony";
printf("%s\n",string);
printf("%s\n",str); // here is the doubt
}
output
Hello
Hello
aaaaa
aaaaa
jhony
aaaaa //how this supposed to print aaaaa even after we changed string into jhony
Upvotes: 1
Views: 1105
Reputation: 934
This is because string is a local variable. When you set string = jhony
you aren't changing str. You are simply changing what string is pointing too. After this there are two string constants defined, "aaaaa" and "jhony", the aaaaa string is not overwritten. Str is also still "aaaaa" since it was not overwritten by the assignment of johnny to string.
Upvotes: 1
Reputation: 815
string and str are both different pointers pointing to the same thing. Using the array notation is the same as dereferencing so you were actually manipulating the underlying data and because they were pointing to the same thing the change was noted in both places.
When you set the pointer equal to the literal, there wasn't any dereferencing or array notation. This changed what the pointer pointed to but the underlying data was not touched. And so the change was not noted by the other pointer.
Setting a pointer equal to something changes its value in the sense that the value of a pointer is an address. That address is a reference to whatever the pointer points to but now the pointer points to a new address. In your case, the string literal.
Upvotes: 1
Reputation: 32576
string = "jhony";
does not copy "jhony"
to the memory pointed by string
. Instead, it assigns address of "jhony"
to string
.
So after that, string
points at "jhony"
while str
stays unchanged.
As @BrianCain commented, to copy "jhonny"
to the memory addressed by string
you may use
strcpy(string, "jhonny");
Upvotes: 2
Reputation: 33
string = "jhony";
this statement has changed the string's value which means the variable string not points to global array any more, it now points to the new const string "johny" which stored in the function's stack
Upvotes: 0