onezeroonefive
onezeroonefive

Reputation: 31

seg fault in dynamic array (C)

Why do I get a segfault error for *a[1]=1; even though I have already allocated space for it on the heap with malloc?

void d(int **a, int count){
    *a = malloc(sizeof(int)*count);
    *a[1]=1; 
}

int main(){
    int count =10;
    int *a;
    d(&a, count);
}

Upvotes: 1

Views: 291

Answers (2)

Lemon Drop
Lemon Drop

Reputation: 2133

*a[1] = 1; is likely not doing what you think it is doing. Since the brackets for indexing have a higher precedence than dereferencing, you can think of it as if it is treating a as an array of pointers to integers and attempting to access the second element of it before dereferencing to get the integer it is pointing at, rather than a pointer to an array of integers. Since this is not the case, it segfaults as there is likely some bad address which is then being dereferenced in that position.

If you however change it to (*a)[1] = 1;, the pointer is first dereferenced and the memory you allocated it indexed into properly.

Upvotes: 5

frslm
frslm

Reputation: 2978

Your assignment operation *a[1]=1 is equivalent to *(a[1])=1, according to operator precedence rules. If you intend to dereference a first, and then access the element at index 1, you should include the parentheses to make your intent clear: (*a)[1]=1

Upvotes: 2

Related Questions