2

I passed my function void Assign_numbers to void Adding. When I change it to a pointer and compile it, the first array value returns the same value from number.a in void Assign_numbers. The other value in the array starting from ptr[1] gives a entirely different number. Can you please help me so the array is able to output the other assigned numbers. Please don't change the formatting.

#include <stdlib.h>
#include <stdio.h>

#define Max 6

struct Numbers
{
    double a,b,c,d,e,f;
};

void Adding(struct Numbers *ptr)

void Assign_numbers()
{
    struct Numbers number;

    number.a=45.78;
    number.b=81.45;
    number.c=56.69;
    number.d=34.58;
    number.e=23.57;
    number.f=78.35;

    Adding(&number);
}

void Adding(struct Numbers *ptr)
{
    int i =0;

    for(i;i<Max;i++)
    {
        ptr[i];
        printf("%.2f\n",ptr[i]);
    }
}

int main()
{
     Assign_numbers();
     return 0;
}
Suvarna Pattayil
  • 5,136
  • 5
  • 32
  • 59
user5771881
  • 97
  • 1
  • 9

2 Answers2

3

In the Adding function the variable ptr points to a single structure, essentially an arry of a single element. When you do e.g. ptr[1] you try to access the second element in this one-element array, which is out of bounds and will lead to undefined behavior.

There's simply no way you can treat a structure in standard C like an array.


There are hacks though. For example using a union with the structure as one member and an array as another, but that relies on the compiler not adding any padding between the members of the structure. It's neither portable nor recommended.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
3

Type of the pointer (in your case struct Numbers) defines offset of the elements in the array. For example if you have array of some type T use of a[i] would mean take value of T from the address a + i * sizeof(T) or simplier.

Note: To be true a[i] would be converted to *(a + i), and this is the reason why i[a] works just fine. See With arrays, why is it the case that a[5] == 5[a]? question.

Now you have struct Numbers *ptr and use ptr[0] that makes it *(ptr + 0 * sizeof(struct Numbers)), which leads you to your struct in you memory. However the use of ptr[1] would lead you to *(ptr + 1 * sizeof(struct Numbers)), but there is no data on this address in memory and this causes undefined behavior.

What you wanted to do is to iterate through your struct with double*, for example

void Assign_numbers()
{
    struct Numbers number;

    number.a=45.78;
    number.b=81.45;
    number.c=56.69;
    number.d=34.58;
    number.e=23.57;
    number.f=78.35;

    Adding((double*)&number);
}

void Adding(double* ptr)
{
    int i = 0;
    for(i; i < Max; i++)
    {
        ptr[i];
        printf("%.2f\n",ptr[i]);
    }
}

prints

45.78
81.45
56.69
34.58
23.57
78.35

Another way is to use union. See C method for iterating through a struct's members like an array? for example.

Community
  • 1
  • 1
Nikolay K
  • 3,770
  • 3
  • 25
  • 37