Reputation: 508
I am attempting to change the value of an original string by changing a pointer.
Say I have:
char **stringO = (char**) malloc (sizeof(char*));
*stringO = (char*) malloc (17);
char stringOne[17] = "a" ;
char stringTwo[17] = "b";
char stringThree[17] = "c";
char newStr[17] = "d";
strcpy(*stringO, stringOne);
strcpy(*stringO, stringTwo);
strcpy(*stringO, stringThree);
//change stringOne to newStr using stringO??
How can I change stringOne
so its the same as newStr
using the pointer stringO
?
edit: I guess the question was rather unclear. i want it to modify the latest string that *strcpy
was copied from. So if strcpy(*stringO, stringThree);
was last called, it will modify stringThree
, strcpy(*stringO, stringTwo);
then string Two
etc.
Upvotes: 0
Views: 152
Reputation: 3751
I want it to modify the latest string that
strcpy
was copied from. So ifstrcpy( ( *stringO ), stringThree );
was last called, it will modifystringThree
,strcpy( (*stringO ), stringTwo );
thenstringTwo
etc.
It is not possible to do this with your approach since you are making a copy of the string by using strcpy
-- not pointing to blocks of memory. To achieve your goal I would do the following:
char *stringO = NULL;
char stringOne[ 17 ] = "a";
char stringTwo[ 17 ] = "b";
char stringThree[ 17 ] = "c";
char newStr[ 17 ] = "d";
stringO = stringOne; // Points to the block of memory where stringOne is stored.
stringO = stringTwo; // Points to the block of memory where stringTwo is stored.
stringO = stringThree; // Points to the block of memory where stringThree is stored.
strcpy( stringO, newStr ); // Mutates stringOne to be the same string as newStr.
... note that I am mutating (updating) where stringO
points to, not copying a string into it. This will allow you to mutate the values in the blocks of memory that stringO points as (which is consequently where the latest stringXXX
is stored) -- as requested.
Upvotes: 2
Reputation: 70402
Here's one way:
char **stringO = (char**) malloc (sizeof(char*));
char stringOne[17] = "a" ;
char stringTwo[17] = "b";
char stringThree[17] = "c";
char newStr[17] = "d";
*stringO = stringOne;
strcpy(*stringO, newStr);
If I have to use stringO
the way you have allocated memory for it, then:
strcpy(*stringO, newStr);
strcpy(stringOne, *stringO);
Upvotes: 1