Storing an array's subscript into a structure's member
Hello,
I am trying to store an array's subscript value into a structure's member
pointer. I then want to access it so I can read values form the array itself.
There are two very short code samples below and the thing is that it works
with the first one which the array is of single dimension. In the second
sample, I do the same thing that is done for the first sample but instead of
a single dimensional array, I am doing it for a two dimensional array. I
really tried to search this as to why it doesn't work in the second sample,
but unfortunately I can't figure it out.
In summary, I declare and define an array in main() and then pass the
subcript's value (The address of start of array) to a function so I can store
it to a pointer called "p" which is a member of the lb sturcture. Once this
is done, I fetch F1() function which has a pointer to the lb object as its
only parameter. Once in the F1() function, I try to access the arrays data
via the "p" pointer. It works for a single dimension array, but it gives me 3
errors on the sample where I try it with a two dimensional array.
HERE IS THE SINGLE ARRAY SAMPLE (Compiles without errors)
====================================
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct tag_lb
{
long *p;
}lb;
lb* create_obj(long pmr[])
{
lb MyRef3;
lb *ptr_lb = &MyRef3;
ptr_lb = malloc (sizeof *ptr_lb);
ptr_lb->p = pmr;
return ptr_lb;
}
void f1(lb *pObj)
{
long t;
t = pObj->p[0];
t = pObj->p[1];
}
int main()
{
lb *pObj = NULL;
long pmr[2] = {111, 112};
pObj = create_obj(pmr);
f1(pObj);
free(pObj);
return 0;
}
================================
AND NOW HERE IS THE TWO DIMENSIONAL ARRAY SAMPLE (Gives errors)
================================
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct tag_lb
{
long *p;
}lb;
lb* create_obj(long pmr[][5])
{
lb *ptr_lb = NULL;
ptr_lb = malloc (sizeof *ptr_lb);
ptr_lb->p = pmr; << errors point here
return ptr_lb;
}
void f1(lb *pObj)
{
long t;
t = pObj->p[0][0];
t = pObj->p[0][1];
}
int main()
{
lb *pObj = NULL;
long pmr[][5] = { {195, 194, 193, 111, 111 },
{194, 195, 112, 222, 111 } };
pObj = create_obj(pmr);
f1(pObj);
free(pObj);
return 0;
}
=======================================
I know that in f1() function I could access any of the array's informations
using pointer arithmetic like this:
t = * (pObj->p);
t = *((pObj->p)+1);
t = *((pObj->p)+2);
but I would prefer to keep following array format :
subscript[idx][idx];
I think I ran into this once before but this time I am storing the array's
starting address to a pointer and don't know why it works with one
dimensional arrays and not two dimensional ones!
Any help would be greatly appreciated!
Sincerely thanking all in advance.
--
Best regards
Roberto