1

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);
}
4
  • Is the name of the first parameter of secondary() supposed to be attachmentsArray? That seems to be the name used in the function body. Commented May 2, 2020 at 17:14
  • What do you mean by size==10? Please post a Minimal, Reproducible Example. Commented May 2, 2020 at 17:16
  • @JohnBollinger Sorry, typo. Commented May 2, 2020 at 17:19
  • @MikeCAT fixed it, sorry Commented May 2, 2020 at 17:20

3 Answers 3

3

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] = '.'
Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

Amazing! Where can I read about the relative precedence of operators?
@willywill997 Here!
0

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++;

Comments

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.