Pass array by reference using C

拥有回忆 提交于 2019-12-10 18:04:09

问题


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.


回答1:


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++.)




回答2:


Your problem is one of operator precedence.

The [] operator binds more tightly than the * operator, so

*myArray[1] 

is the same as

*(myArray[1]).  

This is wrong, as the top level pointer only has enough memory allocated for one pointer. You want:

(*myArray)[1] = 2;

On a side note, there is no good reason to mix C and C++ like you have. Obviously you have C++ code here, so prefer new and delete over malloc and free because the latter two do not take into account constructors and destructors for complex objects.




回答3:


Good:

int main()
{
   int* myArray = NULL;
   FillArray(& myArray);   
   ...

Good:

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

Catastrophically bad:

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

Better:

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

ALSO:

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


来源:https://stackoverflow.com/questions/10438625/pass-array-by-reference-using-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!