Dereferencing of structure pointers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kavsudhakar
    New Member
    • Jul 2006
    • 1

    Dereferencing of structure pointers

    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.
  • dna5122
    New Member
    • Jul 2006
    • 12

    #2
    I'm not sure I understand the point of doing that with a structure. A structure has different kinds of data types, an array does not.

    Besides, the example you gave won't do anything. It's also VERY unsafe code that should never, ever, be written into a program.

    Comment

    • Ashish_CPP
      New Member
      • Jul 2006
      • 35

      #3
      Originally posted by kavsudhakar
      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.

      Comment

      Working...