c - 在指针 C 中保存多个字符(动态内存)

标签 c pointers memory dynamic char

我需要在 C 中创建迷你社交网络。我为每个人制作了一个 struct。我将每个 friend 存储在一个带有 id 的 char 指针中。我以为我可以这样管理它:

ptr_friends = id1,id2,id3,id4...

当我需要它们时,我可以使用 strtok 读取它们。

但我没能那样保存它。应该是这样的:

ptr_friends = ptr_friends + id + ","

但当然它不起作用,这是为什么,我不知道该怎么做。

如何保存和使用这种方式?或者,如果您对保存方法有其他想法,请告诉。

最佳答案

我建议您使用 malloc(size_t) 使 ptr_friends 成为指向多个字符的指针,然后使用 realloc(void *, size_t) 每次你想添加一个 ID 到好友列表。这样你就可以使用 ptr_friends[i] 获取数字。

例如:

int friends_size = 1;

char *ptr_friends = malloc((size_t)1);

ptr_friends[0] = john_id; // john_id is a fictional ID here

当你想添加一个 friend 时:

ptr_friends = realloc(ptr_friends, ++friends_size);
ptr_friends[friends_size-1] = mary_id;

编辑:

如果你想做一个添加 friend 的函数,比如addfriend(char *,int),那么这样做是错误的:

void addfriend(char *ptr_friends, int *friends_size, int id)
{
    ptr_friends = realloc(ptr_friends, (size_t) ++(*friends_size));
    ptr_friends[friends_size-1] = id;
}

ptr_friends 在这里被重新分配,由于指针在重新分配时可以移动,我们将它存储在 ptr_friends 中。但是,它是来自函数内部ptr_friends,这意味着我们提供给函数的指针将不会被修改,因为一个参数功能被预先复制到别处。这意味着你必须给指针一个指针,所以你可以在主代码中修改指针。

关于c - 在指针 C 中保存多个字符(动态内存),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20838608/

相关文章:

条件不行?

c - 如何将字符串转换为二进制?

c - C中的double类型和short类型有什么区别?

c - 指针、后增量运算符和序列点

c++ - 为什么linux上一个动态链接的可执行文件在自己的内存空间里有libc的完整内存空间?

c - 如何将二维数组传递给 C 函数

c - 无法使用 GTK3 更改光标

c++ - _Block_Type_Is_Valid (pHead->nBlockUse) 删除堆栈内存?

java - 使用内连接合并 2 个大型 csv 文件

linux - 我想知道linux内存对齐和布局