0

我有以下代码

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

typedef struct Example
{
    uint16_t a;
    uint16_t b;
} ExampleStruct;

void derp(struct Example * bar[], uint8_t i)
{
    uint8_t c;
    for(c = 0; c < i; ++c)
    {
        bar[c]->a = 1;
        bar[c]->b = 2;
    }
}

int main()
{
    struct Example * foo;
    uint8_t i = 3;
    foo = malloc(i*sizeof(ExampleStruct));
    derp(&foo, i);
    free(foo);
    return 0;
}

我收到段错误,所有调试器都告诉我代码停止工作是因为

bar[c]->a = 1;

我试图将其重新排列为以下所有内容

(*bar)[c]->a = 1;
(*bar[c])->a = 1;
bar[c].a = 1;
(*bar)[c].a = 1;

并没有成功。我究竟做错了什么?我不明白为什么会失败,也不明白为什么 bar[0]、bar[1] 和 bar[2] 的地址彼此相距如此之远,而每个只占用 2 个字节。

4

2 回答 2

0

没有必要通过&foo。把事情简单化:

// In a function declaration, it's (almost) always a pointer, not an array.
// "struct Example bar[]" means *exactly* the same thing in this context.
void init(struct Example * bar, int n) {
    int i;
    for (i = 0; i < n; ++i) {
        bar[i].a = 1;
        bar[i].b = 2;
    }
}

int main() {
    int n = 3;
    struct Example * foo = malloc(n*sizeof(struct Example));
    init(foo, n); // passes the address of the array - &a[0] - to init
    printf("The second element is {%u, %u}\n", foo[1].a, foo[1].b);
    free(foo);
    return 0;
}

输出:

第二个元素是 {1, 2}

于 2013-10-29T01:32:46.580 回答
0

由于您试图传递对象数组,因此需要进行一些更改:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
typedef struct Example
{
    uint16_t a;
    uint16_t b;
} ExampleStruct;

void derp(struct Example * bar[], uint8_t i)
{
    uint8_t c;
    for(c = 0; c < i; ++c)
    {
        bar[c]->a = 1;
        bar[c]->b = 2;
    }
}

int main()
{
    struct Example * foo[3];
    uint8_t i = 3, c;
    for(i = 0; i < 3; i++)
    foo[i] = malloc(sizeof(ExampleStruct));
    derp(foo, i);
    for(c = 0; c < i; ++c)
    {
        printf("\n%" PRIu16  " %" PRIu16 ,foo[c]->a,foo[c]->b);
    }
   for(i = 0; i < 3; i++)
   free(foo[i]);
    return 0;
}

struct Example * foo;可以保存一个指向类型对象的指针struct Example。Whilestruct Example * bar[]可以保存指向类型对象的指针数组struct Example

在您的原始程序中,这将在c大于时出现段错误,0因为您没有分配任何指向 type 对象的指针struct Example

bar[c]->a = 1;
bar[c]->b = 2;

对于静态对象:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
typedef struct Example
{
    uint16_t a;
    uint16_t b;
} ExampleStruct;

void derp(struct Example  bar[], uint8_t i)
{
    uint8_t c;
    for(c = 0; c < i; ++c)
    {
        bar[c].a = 1;
        bar[c].b = 2;
    }
}

int main()
{
    struct Example  foo[3];
    uint8_t i = 3, c;
    derp(foo, i);
    for(c = 0; c < i; ++c)
    {
        printf("\n%" PRIu16  " %" PRIu16 ,foo[c].a,foo[c].b); //accessing in main
    }
    return 0;
}
于 2013-10-29T00:59:26.137 回答