gpt4 book ai didi

c - 如何在 C 中编辑 char* 字符串的值?

转载 作者:行者123 更新时间:2023-11-30 17:06:22 24 4
gpt4 key购买 nike

我刚刚开始学习 C,我很不确定如何“正确”访问和编辑字符指针的值。

例如:

#include <stdio.h>
#include <stdlib.h>
int main()
{
char* text = malloc(20);
char* othertext = "Teststring";

do
{
*text++ = *othertext++;
} while (*othertext != '\0');

printf("%s\n", text + 3);
free(text);
return 0;
}

首先,为什么do-while函数不起作用? “othertext”的内容不会复制到“text”指针。而且,当执行free(text)时,程序崩溃了!

我们知道如果我们添加第二个指针,这段代码就会起作用:

#include <stdio.h>
#include <stdlib.h>

int main()
{
char* text = malloc(20);
char* othertext = "Teststring";

char *ptr1 = text;
char *ptr2 = othertext;

do
{
*ptr1++ = *ptr2++;
} while (*ptr2 != '\0');

printf("%s\n", text + 3);
free(text);
return 0;
}

但是两个指针的地址基本相同!它们在调试器中具有相同的值,那么第二个指针有何不同呢?

最后一点:我们不允许使用 string.h。我们确实知道数组和指针之间存在细微的区别。但我们需要具体了解 char* 是如何工作的!

最佳答案

您应该将 malloc() 返回的指针传递给 free()(相同的地址)。您正在传递递增的指针,即 text 指针现在没有 malloc() 返回的指针的地址,而是 最后一个元素的地址code>text,使用另一个指针复制数据,或者更好的索引

size_t i;
for (i = 0 ; othertext[i] != '\0' ; ++i)
text[i] = othertext[i];
text[i] = '\0';

你说

But both pointers have basically the same address!

这不是真的,试试这个

printf("%p -- %p\n", (void *) text, (void *) ptr1);

关于c - 如何在 C 中编辑 char* 字符串的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34770258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com