Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass array by reference using C

Yes, I've read this question & answers: Passing an array by reference in C?. I have a similar problem and implemented the same idea from that question.

However, I still get an error from the following code:

#include <iostream>

void FillArray(int** myArray)
{
   free( *myArray ) ;
   * myArray = (int*) malloc(sizeof(int) * 2);

   *myArray[0] = 1;
   *myArray[1] = 2;
}

int main()
{
   int* myArray = NULL;
   FillArray(& myArray);    
   return 0;
}

I got the following run-time error right after the FillArray function ends:

Unhandled exception at 0x773115de in Program.exe 0xC00000005: Access violation writing location 0xcccccccccc.

I'm using Visual Studio, opened Visual C++ Empty Project. And the file named main.cpp. Does that mean it's compiled with C++ compiler instead of C compiler? If so, how can I open a file which will be compiled only C compiler? I tried renaming main.cpp with main.c, but still have the same problem. (I'm asking this question, because I read some about "pass by reference" and saw that it's different in C and C++.)

Sorry for this very fundamental question.

I will be appreciated for any help,

Sait.

like image 737
Sait Avatar asked Sep 08 '26 12:09

Sait


1 Answers

Precedence is not working as you expect it to be. Try these:

(*myArray)[0] = 1;
(*myArray)[1] = 2;

(Note: iostream is not C. It's C++.)

like image 171
Tugrul Ates Avatar answered Sep 11 '26 02:09

Tugrul Ates



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!