[英]Changing the value of the original string using a pointer
我試圖通過更改指針來更改原始字符串的值。
說我有:
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??
如何使用指針stringO
將stringOne
更改為與newStr
相同?
編輯:我想這個問題還不清楚。 我希望它修改從中復制*strcpy
的最新字符串。 因此,如果strcpy(*stringO, stringThree);
最后一次調用,它將修改stringThree
, strcpy(*stringO, stringTwo);
然后string Two
等
我希望它修改從其復制
strcpy
的最新字符串。 所以如果strcpy( ( *stringO ), stringThree );
最后一次調用,它將修改stringThree
,strcpy( (*stringO ), stringTwo );
然后是stringTwo
等
用您的方法無法做到這一點,因為您要使用strcpy
復制字符串-不指向內存塊。 為了實現您的目標,我將執行以下操作:
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.
...請注意,我正在變異(更新) stringO
指向的地方,而不是將字符串復制到其中。 這將允許您根據要求更改stringO指向的內存塊中的值(因此,這是存儲最新stringXXX
位置)。
這是一種方法:
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);
如果我必須使用stringO
分配內存的方式,那么:
strcpy(*stringO, newStr);
strcpy(stringOne, *stringO);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.