0

I am having trouble adding "records" at the end of a dynamically allocated string array. Before reallocating more memory for the records to be added, everything works fine, and then I basically replicate what I initially did but now with realloc. And after I am done inputting the added Records I get an error and I don't know how to go about adding records. NOTE* The posed code is really stripped down from the original. I've tried many things but to no avail, thanks for all the help in advance.

#include <stdio.h>
#include <stdlib.h>
#define STRINGSIZE 21

void addRecords( char **Names, int classSize);

int main(){
    char **Names;
    int classSize, i;

    //User will be able to choose how many records he woudld like to input.
    printf("Please indicate number of records you want to enter:\n");
    scanf("%d", &classSize);

    Names=malloc(classSize*sizeof(char*));

    for (i=0; i<classSize; i++) {
        Names[i]=malloc(STRINGSIZE*sizeof(char));
    }
    printf("Please input records of students (enter a new line after each record), with following format: first name....\n");

    for (i=0; i<classSize; i++) {
        scanf("%s", *(Names + i));
    }

    for (i=0; i<classSize; i++) {
        printf("%s ", *(Names+i));                
        printf("\n\n");
    }

addRecords(Names, classSize);
}

void addRecords(char **Names, int classSize){
    int addition, i;

    printf("How many records would you like to add?\n");
    scanf("%d", &addition);

    Names=realloc(Names, (classSize+addition)*sizeof(char*));

    for (i=classSize; i<(classSize+addition); i++) {
        Names[i]=malloc(STRINGSIZE*sizeof(char));
    }

    printf("Please input records of students (enter a new line after each record), with followingformat: first name....\n");

    for (i=classSize; i<classSize+addition; i++) {
        scanf("%s", *(Names + (classSize + i)));
    }
    printf("\n\n");
    for (i=0; i<classSize+addition; i++) {
        printf("%s ", *(Names+i));
    }

    printf("\n\n");
}
2501
  • 25,460
  • 4
  • 47
  • 87
Kenshin
  • 177
  • 1
  • 9

2 Answers2

2

You are writing out of the bounds of the array:

for (i=classSize; i<classSize+addition; i++) {
    scanf("%s", *(Names + (classSize + i)));

change to

for (i=classSize; i<classSize+addition; i++) {
    scanf("%s", *(Names + i));

Note that Names[i] is more readable than *(Names + i)

David Ranieri
  • 39,972
  • 7
  • 52
  • 94
2

First, your Names argument is passed by value to addRecords function, so you will be unable to observe the reallocation outside it (it may work if the reallocation does not give you a new address, but in general it does so).

Second, the loop in addRecords contains a mistake. You loop from classeSize up to classSize+addition and you use it in (Names + (classSize+i)). That should be either looping from 0 to addition or using it as Names + i.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69