1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

multidimensional arrays in C (xcode 3.2.3)

Discussion in 'Mac Programming' started by bacteriatype4, Jun 6, 2011.

  1. macrumors newbie

    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 =]
  2. macrumors 65816


    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[COLOR=RED]*[/COLOR])*10);
    	for(i=0;i<10;i++){a[i] = (int*) malloc(sizeof(int)*10);}
  3. macrumors newbie


    thank you very much!
  4. macrumors G5


    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.
  5. macrumors 68040


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


Share This Page