Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

using malloc to create array of pointers

Status
Not open for further replies.

Maulkin

Programmer
Apr 8, 2002
19
AU
Is theis the correct code to create an array of pointers using malloc

b = malloc(256 * sizeof(char*));

if so how do I set the memory address pointed to by each pointer.
e.g
Code:
b[i] = &extract[i];
 
Ok, but few changes.

char **b;
b = (char **) malloc(256 * sizeof(char *));
put b[0] = (char *) malloc(noOfCharacters * sizeof(char));
or as u said
b = &extract;

If you want to allocate two dimensional arrays then do like the following.

int main()
{
int (*p)[3];
int i, j;
p = (int (*)[3]) malloc(sizeof(int) * 3 * 2);
for(i = 0; i < 2; i++)
{
for(j = 0; j < 3; j++)
{
p[j] = i * 3 + j;
}
}
return 0;
}
 
Here's a trick where you have a single dim array (e.g. bitmap bits); you like to keep it stored this way for easy writing back to disk.

//Before you can write bmp bits to it...
BYTE* lpBits;
lpBits = (BYTE *)calloc(biWidth * biHeight, sizeof(BYTE));

//Writing data from bmp file to lpBits
...here...

//It would be easy though to index the bmp in 2D, no?
//We create an array of byte pointers for each line...
BYTE** lppBits;
lppBits = (BYTE**)calloc(biHeight, sizeof(BYTE*));

//Now we set the pointers to the beginning of each row...
int R=0, iOffset=0;
while(R < biHeight){
lppBits[R] = &lpBits[iOffset];
iOffset += biWidth;
R++;
}

//Now you're able get each bmp color index like this...
BYTE tiColor;
int R, C;

R=0;
while(R < biHeight){
C=0;
while(C < biWidth){
tiColor= lppBits[R][C];
C++;
}
R++;
}




 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top