如何知道结构的存在元素?

时间:2011-08-22 10:12:23

标签: c

我有一个简单的结构:

typedef struct {
    int test;
} struct1_t;


typedef struct {
struct1_t** tests;
} struct2_t;


struct2_t *str
for(i=0;i<1000;i++) {
    (str->tests)[i]=(test1_t *) malloc(sizeof(test1_t));
    (str->tests)[i]->test = i;
}

如何知道存在str-&gt;测试)[i]元素不?

 if (str->tests)[i] != NULL 

调用分段失败:)。

5 个答案:

答案 0 :(得分:3)

简单地说,你不能。无法知道C中数组的长度,您必须在数组更改或增长时手动跟踪它。

答案 1 :(得分:1)

C数组实际上只是内存块,所以你真正的 想要在你的结构中添加一个跟踪方式的字段 已经分配了很多空间并确保您初始化 一切都是理智的价值观。使用时也要小心 包含指向结构指针的指针的结构指针, 因为在您的示例中,您无法正确分配内存 一切。

试试这个:

typedef struct {
    int test;
} test_t;

typedef struct {
    test_t* tests; /* We only need a regular pointer here */
    size_t numtests;    /* This is so we know how many tests we allocated */
} mystruct_t;


/* .... Now skip to the actual usage: */

mystruct_t *str;
int i;

str = malloc(sizeof(mystruct_t)); /* Remember to allocate memory for
                                     the container! */
str->numtests = 1000; /* Set our size inside the container and use it! */

/* Now to allocate an array of tests, we only need to allocate
   a single chunk of memory whose size is the number of tests 
   multiplied by the size of each test: */
str->tests = malloc(sizeof(test_t)*str->numtests);

/* Now let's initialize each test: */
for (i=0; i<str->numtests; i++) { /* Notice we use str->numtests again! */
    str->tests[i]->test = 1; /* Notice we don't need all the extra
                                parenthesese. This is due to the operator
                                precedence of [] and -> */
}

现在,当您需要查看测试元素是否存在时,您可以看看是否存在 index在容器的大小范围内:

if (i >= 0 && i < str->numtests) {
  str->tests[i]->test = 2; /* This code only runs if the index would exist. */
}

但这意味着你必须注意始终初始化str-&gt; numtests 一个理智的价值。例如,没有分配的测试:

mystruct_t *str = malloc(sizeof(mystruct_t));
/* Initialize the container to sane starting values! */
str->tests = NULL;
str->numtests = 0;

这就是你知道某件事是否存在的方式 - 你在里面跟踪它 你定义的结构。那是因为C代码非常直接映射到 汇编语言,C结构和数组直接映射到位和字节 在计算机内存中,所以如果你想保持元信息如何 许多元素都在你的数组中,你必须为这些信息腾出空间 并自己存储。

答案 2 :(得分:0)

在C语言中你不能这样做是非常基础的。你的struct2_t需要一个额外的字段,比如你要更新的int no_of_tests。

事实上,为了做你想做的事,你还需要2个mallocs -

struct2_t str;
str.tests = malloc( 1000 * sizeof(int) );
str.no_of_tests = 1000;
for(i=0;i<1000;i++) {
  str.tests[i] = malloc( sizeof(struct1_t) );
  str.tests[1]->test = i;
}

答案 3 :(得分:0)

语言中没有任何内容可以为您执行此操作,您需要自己跟踪。一个常见的解决方案是使任意大小的指针数组中的最后一个指针成为NULL指针,因此您知道在点击NULL时停止循环。

答案 4 :(得分:0)

如果您的编译器支持_msize,您可以找到您分配的大小。例如:

if (i < _msize((str->tests)/sizeof(test1_t))
    then i is valid and points to an element of the allocated array