繁体   English   中英

更改字符的内存地址*

[英]Changing memory address of a char*

我有以下代码:

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

*str在第五个位置//0x001135FC后- //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)
}

您似乎对C的一些非常重要的东西感到困惑。指针只是内存中的地址。 它住在大街上的一个地址。 假设我喜欢409 K街。 然后有人去喷涂409的“ D”,410的“ E”,411的“ A”和412的“ D”。然后有人去202 M Street的喷涂“ B”和202 E的喷涂。 203,“ E”在204,“ F”在205。您可以说“嘿,现在413 K街现在与202 M街相同吗?”是否有意义? 不,不是! 取而代之的是,您必须找到一个带有一堆尚未粉刷过的房屋的街区,并在其中八个房屋上写下“ DEADBEEF”。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM