0

i am starting homework about dynamic array, first, I have a 2 dimensional array :

int initializeInfo[3][4] ={{77,68,0,0},{96,87,89,78},{70,90,86,0}};

and use pointer to store it:

int **ptr = (int**)malloc(3*sizeof(int));
int size = 0;
for(int i =0;i<3;i++){
    addInitiazeInfo(ptr,initializeInfo[i],size);
}

here is function addInitiazeInfo:

void addInitiazeInfo(int**& ptr, int arr[],int& size){
    ptr[size] = (int*)malloc(4*sizeof(int));
    if(ptr[size] == NULL){
        return;
    }
    ptr[size] = arr;
    size++;
}

It's run OK! The 2 dimensional array is store by ptr pointer.enter image description here

And I want to add new row, I think realloc is needed, then I try:

int arr[] = {3,4,5,6};
size++;            
ptr = (int**)realloc(ptr,size * sizeof( int ) );
ptr[size-1] = (int*)malloc(4*sizeof(int));
ptr[size-1] = arr;

But I think this is my trouble, the output make me hard to know how it happend: enter image description here

please help me, thanks everyone

4
  • I dont think you realize what ptr[size] = arr; is doing Commented Jun 26, 2013 at 9:00
  • 3
    int **ptr = (int**)malloc(3*sizeof(int)); is wrong (and so is the realloc)) . BTW: C does not have references. Maybe you mean C++ ? Commented Jun 26, 2013 at 9:02
  • 1
    The defined type for ptr is int **ptr;, so it points to a pointer, (or to the first member of an array of pointers) So, you should allocate 3 * sizeof (int*) chars for it. AND: mixing C and C++ really is a bad habit. Commented Jun 26, 2013 at 9:15
  • When your program contains **& it doesn't matter whether you make it work or not, your program is unreadable either way. Commented Jun 26, 2013 at 9:43

1 Answer 1

2

When you do

ptr[size] = arr;

You are essentially assigning the address of arr, to ptr[size]. This means that the memory you just allocated is lost and successfully leaked.

You want to manually copy element by element or use something like memcpy. It is likely this might fix your issue, depending on the rest of your code.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.