View Full Version : multidimensional arrays in C (xcode 3.2.3)

Jun 6, 2011, 06:01 PM
I've been working on a project using my, now, old PC using visual C++.
everything works fine there.

Now i'm attempting to run it on my new imac. however an strange error occurs.

after allocating a simple 2d array

a = (int**) malloc(sizeof(int)*10);
for(i=0;i<10;i++){a[i] = (int*) malloc(sizeof(int)*10);}

when the following loop is processed


EXC_BAD_ACCESS occurs. I made some research and i found something like there are holes in the memory or i should use a convention to a 1-dimensional array to deal with it. Another suggestions were around C++ object programing.

it should work on simple C, but i don't know what is happening and i have plans to stay with macos =]

Jun 6, 2011, 06:06 PM
Your code is not 64-bit clean because of a coding error. It worked on 32-bit Window because a pointer is the same size an integer under that system. It's not true under 64-bit Mac OS X.

Your missing an asterisk, highlighted below in red.

a = (int**) malloc(sizeof(int*)*10);
for(i=0;i<10;i++){a[i] = (int*) malloc(sizeof(int)*10);}

Jun 6, 2011, 06:16 PM

thank you very much!

Jun 7, 2011, 02:58 AM
General observation: When you write code, and it crashes, your very first assumption should be that there is a bug in your code, and you should stay with this assumption until it is proven wrong - and believe me, that is very, very unlikely to happen. Obviously the code would have crashed on _any_ compiler with 32 bit int and 64 bit pointers.

Jun 7, 2011, 08:30 AM
Obviously the code would have crashed on _any_ compiler with 32 bit int and 64 bit pointers.

Just to be a dick, anywhere the sizeof(void *) > sizeof(int).