so i was doing a program in c, and the purpose of it is to read how much students are going to get their avarege grade and their names, so i have to do an array of strings with their names and so on, but the size of this array is defined by the person that is using the program, so of course the array needs to be allocated as a pointer, but how do i do that? how do i allocate the array as pointer and how do read this same array?
I made some code but i have no idea what is the error on it, because the ide doesn't show it my objective here is to know the student name add it to an array with the size specified by the user here is the program that i did:
#include<stdio.h>
#include <stdlib.h>
int main()
{
float b=0;
int op=0;
int x=0;
int i=0;
double* w;
float q=0;
int h = 0;
int p=0;
int n=0;
int no=0;
printf("enter how much students that u gonna type \n");
scanf_s("%d", &no);
char* g = (char*)malloc(no* sizeof(char));
while (n != no , n ) {
g[n] = malloc(no* sizeof(char));
printf("enter the name of the student of number %d ", n);
scanf_s("%c", & g[n]);
printf("enter how much grades u wanna type for this student\n");
scanf_s("%d", &p);
char* w = (double*)malloc(p * sizeof(double));
while ( i != p, i )
{
w[n] = malloc(p * sizeof(char));
printf("type the %d", i);
printf("º grade\n");
scanf_s("%f", &w[i]);
}
}while(x==no,x )
{
while (op !=p, op )
{
b = w[op] / n;
printf("the student average is %c", g[x]);
printf(" e %f\n", & b);
}
}
return 0;
}
CodePudding user response:
Step by step.
In c a string is an array of characters terminated by \0 (null char). This means its a char * that gets passed around; a pointer to the first character. This need not be dynamically allocated, but in your case it needs to be
Since you want a dynamic sized array of these you need to malloc an array of char * pointers
char *names = malloc(sizeof(char*) * no);
ie we need no
char * pointers
Next we need space for each name (all we have so far are no
initialized pointers)
How much space to we need? Lets choose an arbitrary buffer size say 100 chars
I would do this
.....
char name_buff[100]; // accept up to 99 chars
scanf_s("