0
static void fill_array(int arr[], int count, int num)
{
    int i;
    for(i=0; i<count; i++)
    {
        arr[i] = num;
    }    
}

typedef struct
{
    int a[10];
} x;

int main(void) {
    x *x1;
    fill_array(x1->a, 10, 0);
}

While trying this I am getting Runtime error. Can anybody help on this issue? Thanks in advance.

3 Answers 3

1

You didn't allocate any memory for x: the behaviour of your program is undefined.

For this example, you could get away with

x x1;
fill_array(x1.a, 10, 0);

i.e. use automatic storage duration for x. This is because x1.a effectively decays to a pointer when passed to the function fill_array.

Sign up to request clarification or add additional context in comments.

Comments

1

You have not allocated memory for x1.

int main(void) {
    x *x1 = malloc(sizeof(x));

    if(0 !=x1)
    {
        fill_array(x1->a, 10, 0);
        free(x1);
    }
}

3 Comments

Thank you for checking the return value of malloc. Have an upvote.
you are using x and x1 inconsistently
Thanks BLUEPIXY and artm. It was a typo and i corrected it.
-1

Your runtime error should be probably a segmentation fault

I can look your first pointeur x *x1;

Wich is not allocated and you are trying to access to the content of a non-allocated pointeur so ... segfault.

There is 2 solution. declare your structure with local memory x x1; or allocate it

1 Comment

The runtime error can be anything. The pointer itself is allocated, but is not initialised.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.