tunas425
tunas425

Reputation: 11

C language pointer array in Struct

Code:

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

typedef struct{
    int *arr;
}example;

void Create(example var){
    var.arr = (int *)malloc(sizeof(int)*2);
}

int main(){
    example var1, var2;
    var1.arr = (int *)malloc(sizeof(int)*2);
    var1.arr[0] = 11;
    var1.arr[1] = 22;
    printf("%d %d\n",var1.arr[0],var1.arr[1]);
    Create(var2);
    var2.arr[0] = 111;
    var2.arr[1] = 222;
    printf("%d %d\n",var2.arr[0],var2.arr[1]);
    return 0;
}
OUT:
11 22
Segmentation Fault

My code is as above. I don't get any error when I do it manually as in var1. But if I do it inside a function as in var2, I get an error. How can I fix this. I want to do it inside the function.

EDIT:Thank you for your answers. It worked

Upvotes: 0

Views: 67

Answers (3)

Mridula daga
Mridula daga

Reputation: 21

you have to pass reference of var2: Create(&var2);

Upvotes: 1

paulsm4
paulsm4

Reputation: 121619

The problem is that Create() is making a COPY of your struct. The original struct is unchanged.

If your program was C++, you'd want to pass a "reference".

Here, you want to pass a pointer:

void Create(example * mystruct){
    mystruct->arr = (int *)malloc(sizeof(int)*2);
}

int main(){
    example var1, var2;
    ...
    Create(&var2);

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

The function parameter

void Create(example var){
    var.arr = (int *)malloc(sizeof(int)*2);
}

is its local variable that is initialized by the passed argument and is not alive after exiting the function.

That is this call

Create(var2);

did not change the variable var2 declared in main.

As a result in these statements

var2.arr[0] = 111;
var2.arr[1] = 222;

there is used uninitialized pointer arr that has an indeterminate value that invokes undefined behavior.

You need to pass the variable by reference to the function. For example

void Create(example *var){
    var->arr = (int *)malloc(sizeof(int)*2);
}

and the function is called like

Create( &var2 );

Upvotes: 0

Related Questions