Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Access Structure elements with pointer (http://www.go4expert.com/forums/access-structure-elements-pointer-t149/)

go4expert 26Aug2004 09:54

Access Structure elements with pointer
 
hi, could someone help me. If i have a struct and a 2-D array in it. how do i access it using a pointer?

Code:

e.g.
struct user {
      int i;
      char array[i][j];
}user;

this is what i tried:

  user *tmp;
 
  tmp->array[i][j];  ??


shabbir 26Aug2004 09:58

Re: Access Structure elements with pointer
 
Code:

typedef struct user {
      int i;
      char array[10][10];
}user;

int main()
{

user *tmp;
 
  tmp->array[0][0]; 
}

1. First there should be a typedef to use it like user <varname>
2. You cannot declare an array in structure whose dimension are variables.
3. Accesing the array elements using variable i and j can be done after declaring them.

But the pointer access stuff is absolutely fine and does not contain any error.
tmp->array[0][0];
But the only thing you should remember is using [i][j] should be done after declaring that.

Thanks
Shabbir Bhimani

Amit Ray 26Aug2004 18:09

Re: Access Structure elements with pointer
 
Just adding on to Shabbir's reply ...

firstly there is no harm if you do not typedef the structure but you have to keep this in mind that wherever you declare variables or pointers of that structure type you have to go like :

struct user *tmp ;

Also you can't declare arrays like you have done in C. You have two options if you are not sure about the size of the array either declare a char pointer to a pointer and go about determining the dimansions at run time like I have explained in http://go4expert.com/forums/showthread.php?t=146 .... or you can do the following :

# define M 100
# define N 90
....
typedef struct user
{
int i;
char array[M][N];
}user;


But in this case you need to change the values of M and N before compiling and executing the code and you can't input the dimensions at runtime.

As for accessing the structure members with pointers, the following simple rule will help, wherever you use the "." in case of a simple structure variable use a "->" at the same places for accessing the members via pointers to the structure.

Cheers,
Amit Ray. :)

elec.shabnam 26Feb2008 17:05

Re: Access Structure elements with pointer
 
2d arrays are better or **


All times are GMT +5.5. The time now is 04:01.