pointers - Errors in C gradebook -


i attempting code gradebook in c. however, inexperience in handling pointers, getting strange values when printing values console. code listed below:

# include <stdio.h> # include <stdlib.h> # include <string.h>  int main(int agrc,char * argv[]) { // create null pointers char * students = 0; char * grades = 0; int * namelen = 0;  // variable track class size int classsize   = 0;   printf("please enter class size: "); scanf("%d",&classsize); printf("class size = %d\n",classsize);  // allocate memory null pointers students = malloc(classsize * sizeof(char)+classsize); grades   = malloc(classsize * sizeof(int)); namelen   = malloc(classsize * sizeof(int));  int = 0; char * tmp; int pos = 0;  for(;i<classsize;i++) {     printf("please enter student %d's name: ",i+1);      // read name dummy variable     scanf("%s",tmp);      // store length of name     *(namelen + i) = strlen(tmp);      // read in name of student     strcpy(students+pos,tmp);      printf("please enter %s's grade: ",students + pos);      // read in grade of student     scanf("%d",grades+i);      pos += *(namelen+i)+1; }  printf("\n"); printf("the data entered follows:\n"); printf("----------------------------------------\n");  = 0; pos = 0;  for(;i<classsize;i++) {     printf("student %d: %s. grade: %d\n",i+1,students+pos,*(grades+i));     pos += *(namelen+i)+1; } } 

the problem is, names , grades of students not being displayed sometimes. know has pointers. can't seem spot error. please me? thanks.

students = malloc(classsize * sizeof(char)+classsize); // allocates 1 char each student name.  

this should replaced expected size each name.

students = malloc(classsize * sizeof(char) * 20); // assuming size of each max of 20 bytes including null termination.  char * tmp; 

this should

char tmp[20]; // assumed max size of each name 20 bytes including null. 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -