Click here to Skip to main content
11,478,642 members (64,075 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: 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....
Posted 29-Aug-12 0:25am
Edited 29-Aug-12 0:28am
CPallini340.5K
v2

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Yes, you may use a double pointer to store the address of another pointer as well for creating a matrix, the compiler won't complain. Smile | :)

The memory you are going to use does actually depend on the malloc statements.

Plaese note:
balasubramaniyan94 wrote:
value = (int **) malloc(sizeof(int)*2);


The above line is wrong, it should be
value = (int **) malloc(sizeof(int *) * 2);

(You are lucky if, as often happens, sizeof(int) == sizeof(int *)).
  Permalink  
Comments
Mihai Vrinceanu at 29-Aug-12 9:00am
   
On 32 bit operating systems, sizeof(int) is 4 and sizeof(int*) is 4.
On 64 bit operating systems, sizeof(int) is 4 and sizeof(int*) is 8.
For storing a 64 bit address, you need 8 bytes: 8 bytes * 8 bits/byte = 64 bits.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 205
1 F-ES Sitecore 170
2 Frankie-C 120
3 OriginalGriff 105
4 DamithSL 95
0 Sergey Alexandrovich Kryukov 7,865
1 OriginalGriff 7,341
2 Sascha Lefèvre 3,059
3 Maciej Los 2,491
4 Richard Deeming 2,335


Advertise | Privacy | Mobile
Web03 | 2.8.150520.1 | Last Updated 29 Aug 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100