Pointer in c/C++

Hi to everyone,

I have very basic doubt in Pointer.

I have declared a variable like this
int **value;

Book Definition:
value = &anotherpointer;


But I have used the same double pointer for storing data in two dimensional array.

I have given a sample code below:
value = (int **) malloc(sizeof(int)*2);
value[0] = (int *)malloc(sizeof(int) *2);
value[1]= (int *)malloc(sizeof(int)*2);

This above syntax is working fine with my program.

Basically, i have tried to create a dynamic two dimensional array of size (2X2).

The above syntax of creating dynamic array works fine for all user defined and built-in data types.

Please let me know how memory will be allocated if i tried to create a dynamic structure pointer or other data types of size (example 10).

Please let me know whether i have used the pointer correctly or not?

And let me know the reason. Looking forward for your replies....
Your example contains an error. It is not obligatory that sizeof( int ) is equal to sizeof( int * ). For example on 64-bit system sizeof( int ) can be equal to 4 while sizeof( int * ) can be equal to 8. So instead of

value = (int **) malloc(sizeof(int)*2);

it would be better to write

value = (int **) malloc(sizeof(int *)*2);

Here is an example of creating data structure that simulates a two dimensional array char[2][10]

1
2
3
char **s = ( char ** )malloc( 2 * sizeof( char * ) );
char s[0] = ( char * )malloc( 10 * sizeof( char ) ); 
char s[1] = ( char * )malloc( 10 * sizeof( char ) ); 

Last edited on
Topic archived. No new replies allowed.