Reputation: 47
I have this following piece of code.
I am getting segfaulted when I iterate on *attachmentsArray
after the first iteration, even though size==3
.
What am I doing wrong here?
void secondary(char** array, long size)
{
*array = (char*)malloc(size*sizeof(char));
for(int i = 0; i < size; i++)
{
*array[i] = '.';
}
}
void main()
{
char* attachmentsArray;
long size = 3;
secondary(&attachmentsArry, size);
}
Upvotes: 1
Views: 37
Reputation: 1
Segmentation fault is due to *array[i]="." because what malloc only returns a pointer to the starting address of the memory allocated you cant iterator directly by indexing..
other answers are also correct but you can also do it with incrementing the pointer to point corresponding address blocks like *array = "."; *array++;
Upvotes: 0
Reputation: 180058
The indexing operator ([]
) has higher precedence than the dereferencing operator (unary *
). Indeed, the highest operator-precedence tier consists of all the postfix operators. Therefore,
*array[i] = '.'
is equivalent to
*(array[i]) = '.'
. This is valid in that the expression array[i]
has type char *
, and in that sense is a valid operand for unary *
, but for i
other than zero, array[i]
does not designate a valid pointer, and it is not surprising that trying to dereference it causes a segfault.
Instead, you want
(*array)[i] = '.'
Upvotes: 3
Reputation: 51815
Your problem is with the relative precedence of the *
and []
operators. Your line:
*array[i] = '.';
is de-referencing (or trying to) the 'ith' element in an array of pointers.
What you need, to access the 'ith' element of the array pointed-to by array
is this:
(*array)[i] = '.';
Feel free to ask for further clarification and/or explanation.
Upvotes: 2