Hi,
I have a pointer to structure, and i have to check which member has a desired value.
For that can any one suggest me the best way to access the members while checking for the desired value in that member.
For example ,if i have an array a[]={0,1,2,3};
here say my desired vlue is 2
then i can check
while(--a == 2)
{
break;
}
return(i);
My question is best way to do that when we have a structure instead of array.
Hi,
First thing is that the way you are trying to decrement the address of the array will throw an error of L-value becoz you cannot decrement the address rather you have to collect its address in a pointer and then decrement it.
Now coming to your question :
There are two ways to know the value of the members of a structure through pointer.
1. If your structure has all the members of same data types then you can easily access the members through pointers but structures are meant to hold diff data types so this method will not help u much.
2. If you have diff data types in the structure then you must be aware of the data types of the members before accessing their values. Their values can be accessed in the following way.
struct base x;
unsigned char *ptr, arr[sizeof(x)];
unsigned long *p;
ptr = (char*)&x;
memcpy(arr, ptr, sizeof(x));
p = (unsigned long*)arr;
printf("%lu\n\n", *p);
In the above code I have assumed that the first member of the structure is a unsigned long variable. U can type cast the address of the array as per the data type of the member variable and fetch the value.