Terminatorka Terminatorka - 1 month ago 15
C Question

How to fill up elements of dinamical array with structs from user input?

My program dynamically allocates an array for the size of user input. (If user input is '5' then the size of my

prog
array is 5). Every element of this array should contain a struct.(The struct contains a name and the points of 10 different tests). In the end I would like to output these structs like this:

a
1 2 3 4 5 6 7 8 9 10
b
4 5 3 2 3 7 8 9 11 12


My problem is that I don't know how to achieve this. The only thing I was able to achieve is this, with the program mentioned below (the last data I enter changes everything):

a
1 2 3 4 5 .... 10
b
1 2 3 4 5 .....10


I spent hours with this and I feel like I am totally lost.

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

struct programming{

char name[30];
int partpoints[10];
};

int main(){

struct programming *prog;
int j,i,N;

printf("Please enter the total number of students: \n");
scanf("%d", &N);

prog=(struct programming*) malloc (N * sizeof(struct programming));

for(i=0;i<N;i++){
printf("Please enter the name of the student: \n");
scanf("%s",(prog+i)->name);
for(j=0;j<10;j++){
scanf("%d", (prog+j)->partpoints+j); //PROBLEM!!!!
}
}

printf("Name of students and their points: \n");
for(i=0;i<N;i++){
printf("%s\n", (prog+i)->name);
for(j=0;j<10;j++){
printf("%d\t",(prog+j)->partpoints[j]); //PROBLEM!!!!
}

putchar('\n');
}

return 0;
}

Answer

The problem is that in your nested for-loop you use j to index prog in stead of i, and you must pass a pointer to an int in scanf:

for(i=0;i<N;i++){
    printf("Please enter the name of the student: \n");
    scanf("%s",(prog+i)->name);
    for(j=0,j<10,j++){
        printf("Please enter point %d: \n", i+1);
        scanf("%d", &((prog+i)->partpoints+j)); // no more PROBLEM now
}

Note: you may need to add a space in the scanf format string so it will skip whitespace and cr/lf: " %d" (I am not a scanf guru).

Comments