Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc only allocates 4 bits?

Tags:

c++

malloc

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.

like image 241
jeroen Avatar asked Sep 05 '26 12:09

jeroen


1 Answers

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 when used on a pointer.

like image 169
Dan McGrath Avatar answered Sep 08 '26 03:09

Dan McGrath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!