I am trying to set up an array of structs for a few sample parts which then need to output to a file. It seems to work ok but will only print the first 3 parts and then crashes.
#include "stdio.h"
main()
{
struct stock{
char name[20];
int partNum;
int quantity;
};
struct stock someStock[3];
strcpy(someStock[0].name, "License plate");
someStock[0].partNum = 1234;
someStock[0].quantity= 4;
strcpy(someStock[1].name, "Head lamp");
someStock[1].partNum = 1111;
someStock[1].quantity= 2;
strcpy(someStock[2].name, "Rear wiper");
someStock[2].partNum = 2222;
someStock[2].quantity= 6;
strcpy(someStock[3].name, "Tyres");
someStock[3].partNum = 3333;
someStock[3].quantity= 10;
struct stock *ptr = &someStock[0];
int i;
FILE *file_ptr;
file_ptr = fopen("stock.dat", "w");
for(i=0;i<4;i++)
{
fprintf(file_ptr, "%s %d %d\n",(*ptr).name,(*ptr).partNum, (*ptr).quantity);
ptr++;
}
fclose(file_ptr);
return 0;
}
As others said:
Some other tips for you:
Is equivalent to:
As Daniel pointed out this is since the array name evaluates to a pointer to its first element in that context.
And:
Is equivalent to:
->is known as the structure pointer operator, it dereferences a pointer and accesses a member all in one, as oppose to the.which is the structure member operator and so requires the indirection operator*as well when you have a pointer.