2013-08-16 90 views
0

我正在尝试通过更改指针来更改原始字符串的值。使用指针更改原始字符串的值

说我有:

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);最后调用,它会修改stringThreestrcpy(*stringO, stringTwo);然后string Two

+1

您不应该投射'malloc'的结果。 – chris

+1

@chris([解释](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858)) – 2013-08-16 05:14:25

+0

@ H2CO3该线程上的其他答案指向包含演员的充分理由 – gta0004

回答

2

我希望它修改最新字符串strcpy娃从...复制。所以,如果strcpy((*stringO), stringThree);最后调用,它会修改stringThreestrcpy((*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被存储在哪里)。

+0

是最新的,那是我的目标。感谢您的解释 – gta0004

1

这里有一种方法:

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); 
+0

不,但使用'='而不是'strcpy'确实修复了它 – gta0004

+0

@ gta0004:我不明白。什么不适合你?见[this](http://ideone.com/vDdnQz)和[this](http://ideone.com/kBtw33)。 – jxh