Dear forum users,
I want to use a certain area of the memory to store some data as 2d arrays. The memory area should be always the same, it should be accessed for reading.
I'm having some headaches with this. Here is the code, on the comment what i get.
int num_col=10;
int num_row=10;
char *ptr2_data;
char **ptr2_row;
ptr2_data=(char *)calloc(num_col*num_row,sizeof(char));//allocate all the memory
printf("\nstart at:%p\n",ptr2_cam_data3);//gives an addres add1
for (i=0;i<num_col;i++)//create an array of pointers
{
ptr2_row[i]=ptr2_cam_data3+(i*num_col*sizeof(char));
printf("%p\n",ptr2_row[i]);
}//
/*fill the 2Darray*/
printf("\n!!! fill the 2Darray !!!\n");
for(int i=0;i<num_row;i++)
{
printf("\n&ptr2_row[%i][0]:%p\n",i,&ptr2_row[i][0]);}//print always the address pointed by the pointer held in ptr2_row[i]
for(int j=0;j<num_col;j++)
{
*(*(ptr2_row+i)+j) = (char)j;//giving value
printf("%i ",ptr2_row[i][j]);
}
}
for(int i=0;i<num_row;i++)
{
printf("\n&ptr2_row[%i][0]:%p\n",i,&ptr2_row[i][0]);//same as before.The address of &ptr2_row[0][0] has changed!!
for(int j=0;j<num_col;j++)
{
printf("");
}
Although you think you've created a 2D array, you have in fact created a 1D array large enough to hold all the elements of your 2D array. It's assumed you're going to do the index calculations yourself. So to begin with, the array's type is char*.
You've declared ptr2_data to be the correct type. So far so good.
I have no idea what ptr2_cam_data3 is.
It looks like you want ptr2_row to be an array of indices into the array, ptr2_data. If that's what you want to do, you have to allocate it an array, then fill the nodes with the pointer offsets into ptr2_data. You haven't done that as far as I can tell.
And because ptr2_row isn't set up properly, it makes a nonsense of the rest of your code.
Dear kbw,
thanks a lot for the replay!
Basically the mistake was not allocating also the array of pointers!
Don't know why, I thought with dynamic allocation you could avoid allocating.
Sorry for the ptr2_cam_data3,that's just the name I'm using for ptr2_data in my real code.