我正在将结构传递给函数。该结构包含一个指针变量。结构本身作为指针变量传递给函数。我无法使用下标样式访问数组(var [0])来访问结构的指针变量成员(在函数内部)。代码可以编译,但是执行.o文件时出现分段错误。错误位于功能代码的第一行。我无法访问结构内部的指针变量。
当不涉及函数时,我可以使用点运算符轻松访问此指针变量。例如,请参阅最后的工作代码。
问题代码:
#include<stdio.h>
struct prog
{
double* var;
char* name;
int arr[];
};
typedef struct prog p;
void fun(p *inp);
int main()
{
p in;
p *inptr = ∈
in.arr[1] = 32;
fun(inptr);
printf("Value var is: %f\n", in.var[0]);
printf("Value arr[0] is: %d\n", in.arr[0]);
printf("Value arr[1] is: %d\n", in.arr[1]);
printf("Name of prog is: %s\n", in.name);
return 0;
}
//Function
void fun(p *inp)
{
(*inp).var[0] = 4.5;
//inp->var[0] = 4.5;
inp->arr[0] = 11;
inp->arr[1] = 55;
inp->name = "User";
}
工作代码:
#include<stdio.h>
struct prog
{
double* var;
char* name;
int arr[];
};
void main()
{
struct prog p;
p.var[0] = 3.7;
p.name = "User";
p.arr[0] = 100;
p.arr[1] = 30;
printf("Value var is: %f\n", p.var[0]);
printf("size of prog is: %d bytes \n", sizeof(p));
printf("Value at arr[0] is: %d\n", p.arr[0]);
printf("Value at arr[1] is: %d\n", p.arr[1]);
printf("Name of prog is: %s\n", p.name);
}
正在运行的“ gdb”显示“程序收到信号SIGSEGV,分段错误。 在strct-fun.c:35中获得0x00005555555551d3乐趣(in = 0x7fffffffe200) 35(* inp).var [0] = 4.5;“
答案 0 :(得分:0)
in.arr[1] = 32;
您不能使用静态内存来做到这一点,如果您想要一个灵活的数组成员,则需要malloc
:
p *in = malloc(sizeof *in + sizeof(int) * number_of_arr_elements);
请注意,灵活数组仅适用于最后一个成员。
您还需要其他成员var
和name
的空间:
p->var = malloc(sizeof(double) * number_of_var_elements);
p->name = malloc(max_length_of_name + 1); /* +1 for the trailing \0 */