我试图通过更改指针来更改原始字符串的值。
假设我有:

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

如何更改stringOne,使其与使用指针newStr时的stringO相同?
编辑:我想这个问题不太清楚。我希望它修改从中复制的最新字符串。因此,如果上次调用*strcpy,它将修改strcpy(*stringO, stringThree);stringThree然后strcpy(*stringO, stringTwo);等。

最佳答案

我希望它修改从中复制的最新字符串。因此,如果上次调用strcpy,它将修改strcpy( ( *stringO ), stringThree );stringThree然后strcpy( (*stringO ), stringTwo );等。
使用这种方法是不可能的,因为您正在使用stringTwo--而不是指向内存块来复制字符串。为了实现您的目标,我将执行以下操作:

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.

... 注意,我在strcpy指向的地方进行变异(更新),而不是将字符串复制到其中。这将允许您根据请求改变stringO指向的内存块中的值(这是存储最新stringO的地方)。

10-08 13:05