Reputation: 21
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;
}
Upvotes: 1
Views: 169
Reputation: 54781
As others said:
struct stock someStock[4];
Some other tips for you:
struct stock *ptr = &someStock[0];
Is equivalent to:
struct stock *ptr = someStock;
As Daniel pointed out this is since the array name evaluates to a pointer to its first element in that context.
And:
fprintf(file_ptr, "%s %d %d\n",(*ptr).name,(*ptr).partNum, (*ptr).quantity);
Is equivalent to:
fprintf(file_ptr, "%s %d %d\n", ptr->name, ptr->partNum, ptr->quantity);
->
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.
Upvotes: 1
Reputation: 3107
struct stock someStock[3]; means you have three elements in array so the array index can be from 0 to 2 so strcpy(someStock[3].name, "Tyres"); is crashing your program as 3 is out of range array index
Upvotes: 0
Reputation: 183858
struct stock someStock[3];
declares an array of 3 struct stock
, but you're using four. The number in brackets is the number of elements, not the highest valid index. Declare
struct stock someStock[4];
Upvotes: 4