0

我有以下代码:

str = "ABCD";  //0x001135F8  
newStr = "EFGH"; //0x008F5740

*str在第 5 位重新分配之后 -//0x001135FC
我希望它指向:0x008F5740

void str_cat(char** str, char* newStr)
{
 int i;
 realloc(*str, strlen(*str) + strlen(newStr) + 1); //*str is now 9 length long
 // I want to change the memory reference value of the 5th char in *str to point to newStr.
 // Is this possible?
 // &((*str) + strlen(*str)) = (char*)&newStr; //This is my problem (I think)
}
4

2 回答 2

1

你似乎混淆了关于 C 的一些非常重要的东西。指针只是内存中的一个地址。它是街上的地址。假设我喜欢 409 K Street。然后有人去在 409 喷漆“D”,在 410 喷漆“E”,在 411 喷漆“A”,在 412 喷漆“D”。然后有人去 202 M Street 喷漆“B”,在 410 喷漆“E” 203,“E”在 204,“F”在 205。你可以直接说“嘿,现在 413 K 街现在和 202 M 街一样”有什么意义吗?不,它没有!取而代之的是,您必须找到一个街区,那里有一堆尚未粉刷的房屋,并在其中八个上写上“ DEADBEEF”。

以此类推,在 C 中,您将分配一个新字符串,长度为两个字符串的长度加 1,作为零终止符,然后将第一个字符串复制到前四个位置,将下一个字符串复制到其余位置。

于 2012-09-16T09:34:35.383 回答
0
void str_cat( char* dest, char* src )
{
   dest = realloc( dest, strlen( dest ) + strlen( src ) + 1 );

   strcpy( dest + strlen(dest), src );
}

应该可以工作 - 虽然我手头没有编译器来测试

甚至更快,几乎没有指针:http ://www.koders.com/c/fid359660C181A42919DCB9E92C1406B7D16F27BB8D.aspx

于 2012-09-16T09:28:14.207 回答