gpt4 book ai didi

C - 追加字符串直到分配的内存结束

转载 作者:太空宇宙 更新时间:2023-11-04 04:42:26 25 4
gpt4 key购买 nike

让我们考虑以下代码:

int len = 100;
char *buf = (char*)malloc(sizeof(char)*len);
printf("Appended: %s\n",struct_to_string(some_struct,buf,len));

有人分配了一定数量的内存,以便用字符串数据填充它。问题是从 some_struct 中获取的字符串数据可以是任意长度。所以我想要实现的是使 struct_to_string 函数执行以下操作:

  1. 不要分配任何到外部的内存(因此,buf 必须在函数外部分配并传递)
  2. 在 struct_to_string 中我想做类似的事情:

    char* struct_to_string(const struct type* some_struct, char* buf, int len) {

    //it will be more like pseudo code to show the idea :)


    char var1_name[] = "int l1";
    buf += var1_name + " = " + some_struct->l1;
    //when l1 is a int or some non char, I need to cast it

    char var2_name[] = "bool t1";
    buf += var2_name + " = " + some_struct->t1;

    // buf+= (I mean appending function) should check if there is a place in a buf,
    //if there is not it should fill buf with
    //as many characters as possible (without writting to memory) and stop
    //etc.

    return buf;
    }

输出应该是这样的:

Appended: int l1 = 10 bool t1 = 20  //if there was good amount of memory allocated or
ex: Appended: int l1 = 10 bo //if there was not enough memory allocated

总结:

  1. 我需要一个函数(或几个函数)将给定的字符串添加到基本字符串而不覆盖基本字符串;
  2. 当基本字符串内存已满时什么都不做
  3. 我不会使用 C++ 库

我可以问但现在不那么重要的其他事情:

  1. 有没有一种方法(在 C 中)遍历结构变量列表来获取它们的名称,或者至少获取它们的值但没有它们的名称? (例如通过数组遍历结构;d)

我通常不使用 C,但现在我有义务使用,所以我有非常基础的知识。(对不起我的英语)

编辑:

下面的帖子显示了解决该问题的好方法:stackoverflow.com/a/2674354/2630520

最佳答案

我想说您只需要在 string.h header 中定义的标准 strncat 函数。

关于“遍历结构变量列表” 部分,我不太确定您的意思。如果您谈论迭代结构的成员,一个简短的回答是:您不能免费内省(introspection) C 结构。

您需要事先知道您使用的是什么结构类型,以便编译器知道它可以在内存中的什么偏移处找到您的结构的每个成员。否则它只是一个字节数组,与其他字节数组一样。

不要介意问我是否不够清楚,或者您是否需要更多详细信息。祝你好运。

关于C - 追加字符串直到分配的内存结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24957527/

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