I am passing a structure to a function. This structure contains a pointer variable. The structure is itself passed to the function as a pointer variable. I am unable to access the structure's pointer variable member (while inside the function) using subscript style of accessing an array (var[0]). The code compiles but I get a segmentation fault upon executing the .o file. The error lies in the first line of the function code. I am not able to access the pointer variable inside the structure.
I can easily access this pointer variable using the dot operator when functions are not involved. For example, see the working code in the end.
Problematic code:
#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";
}
Working code:
#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);
}
Running 'gdb' says "Program received signal SIGSEGV, Segmentation fault. 0x00005555555551d3 in fun (in=0x7fffffffe200) at strct-fun.c:35 35 (*inp).var[0] = 4.5;"