tags:

views:

133

answers:

4

I'm trying to make some c programs, ut i'm stuck at the malloc command. This is my code:

        #include <stdlib.h>
        #include <iostream>
        #include "Oef1.h"
        using namespace std;

 some methode clled by main{
         int ** q=NULL;
         int m=read(q);
}


 int read(int ** q){
          int m=3;
          int n=5; //n and m are beeing asked, but for debugging hard-coded
          cout << sizeof(int*) << endl;     // returns 4
          cout <<sizeof(q) << endl;        //returns 4
          cout <<m*sizeof(int*) << endl;   //returns 12
          q=(int**)realloc(q,m*sizeof(int*));
          cout <<sizeof(q) << endl;         //should return 12 but returns 4
          for(int k =0; k < m; k++){
             q[k] = (int*)malloc(n*sizeof(int));
           }
            return m;
    }

The problem is, that after the malloc command the sizeof(q) is still 4 where it should be 12 (3*4). I know that you could make arrays in c++ with the [] brackets, but I like to do it with malloc for learning purpose. It's probably a stupid mistake, but I don't find it.

+2  A: 

sizeof(q) will return the size of the pointer q, not the content pointed by the pointer.

Guillaume Lebourgeois
+10  A: 

sizeof is returning the size of the data type, which is a pointer. On your system you will find that a pointer is always 4 bytes (not bits). sizeof does not return the size of the array.

Dan McGrath
Down vote was for?
Dan McGrath
Actually, `sizeof` *does* return the size of the array if given an array.
Rotsor
Yes, sorry, that is correct. I meant to say an array pointed to. Naturally performing sizeof on an array such as a constant string will give you the size of the array. Likewise, if you give it an actual structure, it returns the size of the structure.
Dan McGrath
+3  A: 

sizeof(Any_Type) returns the size occuped in memory by one element of this type. In your case, sizeof(q) is sizeof(int **), that is the size of a pointer (generally 4 or 8 depending on if your are on a 32 or 64bits machine).

Moreover, you are confusing bits and bytes. sizeof returns the size in bytes, not bits

Scharron
A: 

sizeof(q) tells you the size of the data type of q, which is int** in your case. sizeof will never tell you the size of a dynamically allocated object/array, if not because it is evaluated at compile-time - it is not even possible for sizeof(x) to return a different value for the same x. The size of a type is a compile-time constant.

It is your task to keep track of the size of the allocation (the value that you passed to malloc()/new etc, or rather use a standard container that will do that for you (std::vector).

visitor