我有以下代码
#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个字节。< / p>
答案 0 :(得分: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
类型对象的单个指针。虽然struct Example * bar[]
可以包含指向struct Example
类型对象的指针数组。
在原始程序中,当c
大于0
时,这将导致错误,因为您没有为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;
}
答案 1 :(得分: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}