gpt4 book ai didi

c - 删除 char*,同时保留字符串

转载 作者:行者123 更新时间:2023-11-30 14:46:06 25 4
gpt4 key购买 nike

我需要帮助弄清楚如何删除或重置 char*,但将 char* 的值保留在 struct 中。

例如,如果我有

char* word;
struct test *person;
word = (char*)malloc(sizeof(char) * 50);
person = malloc(sizeof(struct test));

假设我使用函数将“Jack”一词存储在 word 中,因为我使用 read 函数从 CSV 中读取内容。

所以...

while (read(STDIN, buffer, 1) != 0) {
add(word, *buffer);
}

void add(char* string, char c) {
int size = strlen(string);
string[size] = c;
string[size + 1] = '\0';
}

person->name = word;
memset(word, 0, sizeof(word));

这样做会清空 person->name 和 word 中的字符串。

如何将字符串保留在 person->name 中?

我尝试创建一个单独的字符串,但无法解决问题。

char temp[size];
int i = 0;
while (word[i] != '\0') {
temp[i] = word[i];
i++;
}

这也会清除 person->name 中的字符串以及 temp。

任何帮助将不胜感激。

最佳答案

person->name = word;
memset(word, 0, sizeof(word));

如果你想为person->name复制word,你必须先分配内存:

person->name = malloc(strlen(word) + 1);  // + 1 for the terminating '\0'

然后你可以将word指向的字符串复制到现在由person->name指向的内存中:

strcpy(person->name, word);

然后您可以将单词的长度设置为0:

word[0] = '\0';

并重复使用单词

确保在不再需要时free()使用malloc()分配的所有内存。

<小时/>
void add(char* string, char c) {
int size = strlen(string);
string[size] = c;
string[size + 1] = '\0';
}

此函数不安全,因为它可能会超出为 string 分配的内存范围进行写入。给它另一个参数来表示它的大小:

#include <stdbool.h>  // bool
#include <stddef.h> // size_t
#include <string.h> // strlen()

bool add(char* string, size_t size, char ch)
{
size_t length = strlen(string);

if (length + 2 > size)
return false;

string[length] = ch;
string[length + 1] = '\0';
return true;
}

关于c - 删除 char*,同时保留字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52547945/

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