- #1
mathmannn
- 15
- 0
Homework Statement
I do not have much experience with C, just a single course a few years ago, and I didn't do so well in it either.
I'm just trying to get familiar with structs in C. Basically what I want to do is just store the length and width of a rectangle using a function and a struct.
I can get it to work without using a function with this code:
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int length;
int width;
} Piece;
int main(void){
int p_count=0;
printf("How many pieces? ");
scanf("%d",&p_count);
Piece piece[p_count];
for(int i=0; i<p_count; i++){
printf("\n\nEnter the length for piece %d: ",i+1);
scanf("%d",&piece[i].length);
printf("Enter the width for piece %d: ",i+1);
scanf("%d",&piece[i].width);
}
for(int i=0; i<p_count; i++){
printf("\n\n---------------------------\n");
printf("Length for piece %d is: %d\n",i+1,piece[i].length);
printf("Width for piece %d is: %d\n",i+1,piece[i].width);
printf("---------------------------\n");
}
return 0;
}
However, when I try to move just the part where I get the input into a function called "readPieces" I get an error when trying to store the values into length and width.
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct{
int length;
int width;
} Piece;
void readPieces(Piece piece, int p_count);
int main(void){
int p_count=0;
printf("How many pieces? ");
scanf("%d",&p_count);
Piece piece[p_count];
readPieces(piece[p_count],p_count);
for(int i=0; i<p_count; i++){
printf("\n\n---------------------------\n");
printf("Length for piece %d is: %d\n",i+1,piece[i].length);
printf("Width for piece %d is: %d\n",i+1,piece[i].width);
printf("---------------------------\n");
}
return 0;
}
void readPieces(piece[p_count], int p_count){
for(int i=0; i<p_count; i++){
printf("\n\nEnter the length for piece %d: ",i+1);
scanf("%d",&piece[i].len);
printf("Enter the width for piece %d: ",i+1);
scanf("%d",piece[i].wid);
}
}
Homework Equations
The Attempt at a Solution
I'm sure that my mistake is something about how I call the function, or how I'm trying to store the values. But I do not have enough experience to debug this myself.
If anyone can help out with understand the proper way to call a function using a struct and store user input it would be greatly appreciated.