povoação said:
I'd recommend using the prototype form:
int main(void)
{
int a;
struct peoples *people;
This is very creative naming, to give the pointer to the
beginning of an array a relatively singular name, and the
structure type that the array contains a relatively plural name.
Most programmers would probably do it differently, e.g.
struct person *people;
people=(struct peoples *)malloc(SIZE*sizeof(struct peoples));
I don't recommend casting the return value of malloc():
* The cast is not required in ANSI C.
* Casting its return value can mask a failure to #include
<stdlib.h>, which leads to undefined behavior.
* If you cast to the wrong type by accident, odd failures can
result.
In unusual circumstances it may make sense to cast the return value of
malloc(). P. J. Plauger, for example, has good reasons to want his
code to compile as both C and C++, and C++ requires the cast, as he
explained in article <
[email protected]>.
However, Plauger's case is rare indeed. Most programmers should write
their code as either C or C++, not in the intersection of the two.
When calling malloc(), I recommend using the sizeof operator on
the object you are allocating, not on the type. For instance,
*don't* write this:
int *x = malloc (128 * sizeof (int)); /* Don't do this! */
Instead, write it this way:
int *x = malloc (128 * sizeof *x);
There's a few reasons to do it this way:
* If you ever change the type that `x' points to, it's not
necessary to change the malloc() call as well.
This is more of a problem in a large program, but it's still
convenient in a small one.
* Taking the size of an object makes writing the statement
less error-prone. You can verify that the sizeof syntax is
correct without having to look at the declaration.
for(a=0;a<SIZE;a++)
{
people->code=a;
scanf("%s",people->name);
You need to specify a maximum length, or this can lead to a
buffer overflow.
scanf("%f",people->value);
You forgot to take the address: &people->value.
people++;
}
for(a=0;a<SIZE;a++)
{
printf("%d",people->code);
printf("%s",people->name);
printf("%f",people->value);
people++;
}
This isn't going to work, because in your first loop you already
advanced "people" past the records you're trying to print. I'd
suggest dropping the "people++" from both loops and using array
index notation instead for each member reference,
e.g. people[a].code.