C中的动态字符串数组结构

时间:2011-02-13 00:55:17

标签: c

我必须在c中编写一个函数,它将返回一个动态字符串数组。以下是我的要求:

  • 我有10个不同的检查函数,它们将返回true或false以及相关的错误文本。 (错误文本字符串也是动态的)。
  • 我的函数必须收集结果(true或false)+错误字符串,它将被称为n检查函数。所以我的函数必须收集n个结果,最后将动态字符串数组返回给其他函数。

3 个答案:

答案 0 :(得分:1)

您可以使用malloc()分配任意长度的数组(在Java中类似于“new”),并使用realloc()使其增长或缩小。

你必须记住用free()释放内存,因为在C中没有garbarage收集器。

检查:http://www.gnu.org/software/libc/manual/html_node/Memory-Allocation.html#Memory-Allocation

编辑:

#include <stdlib.h>
#include <string.h>
int main(){
    char * string;
    // Lets say we have a initial string of 8 chars
    string = malloc(sizeof(char) * 9); // Nine because we need 8 chars plus one \0 to terminate the string
    strcpy(string, "12345678");

    // Now we need to expand the string to 10 chars (plus one for \0)
    string = realloc(string, sizeof(char) * 11);
    // you can check if string is different of NULL...

    // Now we append some chars
    strcat(string, "90");

    // ...

    // at some point you need to free the memory if you don't want a memory leak
    free(string);

    // ...
    return 0;
}

编辑2: 这是用于分配和扩展指向字符(字符串数组)的指针数组的示例

#include <stdlib.h>
int main(){
    // Array of strings
    char ** messages;
    char * pointer_to_string_0 = "Hello";
    char * pointer_to_string_1 = "World";
    unsigned size = 0;

    // Initial size one
    messages = malloc(sizeof(char *)); // Note I allocate space for 1 pointer to char
    size = 1;

    // ...
    messages[0] = pointer_to_string_0;


    // We expand to contain 2 strings (2 pointers really)
    size++;
    messages = realloc(messages, sizeof(char *) * size);
    messages[1] = pointer_to_string_1;

    // ...
    free(messages);

    // ...
    return 0;
}

答案 1 :(得分:0)

考虑创建适合您问题的适当类型。例如,您可以创建一个包含指针和sn整数长度的结构来表示动态数组。

答案 2 :(得分:0)

  1. 你有一些限制 examine()的原型设计 功能和你的功能 来写 ? (我们称之为 validate()

  2. 你说你有10个examine()函数,这是否意味着你在validate()返回的数组中最多有10条消息/结果?

  3. 我是一名具有C背景的Java程序员,所以也许我可以为你强调一些事情:

    • C中没有Array.length的等价物:你必须提供一个边整数值来存储数组的有效大小

    • C数组不能“增长”:当数组增长或缩小时,你必须使用指针并分配/重新分配数组开始指针所指向的内存

    • 您应该已经知道C中没有类或方法的概念,但您可以使用structtypedef和函数指针来添加某种面向对象/通用性行为你的C程序......

    • 根据您的需求和义务,数组可能是一个好的方式:或许您应该尝试找出一种在C中构建/查找等效的Java List接口的方法,以便您可以添加,删除/销毁或排序检查结果元素,而无需在每次操作结果集时重复内存分配/重新分配/释放代码(并且您应该使用结构/检查函数发送头文件来描述您所执行的操作无论如何,现在更准确地表达你的需求,以便我们引导你走向好的方向)

    不要犹豫,提供更多信息或询问有关上述子弹点的具体信息;)

相关问题