th0k1a1 th0k1a1 - 2 months ago 15
C Question

C program using array char* crash

I want to build a program that allow to insert name and print out. But the program crash whenever it begin.

This is my main class:

void main(int argc, char *argv[]) {
int* n = (int*) malloc(sizeof(int));
char listStudent[100][31];
char* name = (char*) malloc(31);
int id;
*n = 0;
addStudent("John ABC", listStudent, n);
addStudent("David Davinci", listStudent, n);
}


And some function to call

void addStudent(char name[31], char listName[][31], int *pn) {
int id;
id = findName(name, listName, *pn);
if(id < 0) {
addName(name, listName, *pn);
printf("%s has been added", name);
} else
printf("The student was exist\n");
}


int findName(char name[31], char listName[][31], int n) {
int found = FALSE;
int i, id;
id = -1;
for(i = 0; i < n && (!found); i++)
if(stricmp(listName[i], name) == 0) {
found = TRUE;
id = i;
}

return id;
}

void addName(char str[31], char listName[][31], int* pn) {
if(*pn > 100)
printf("List is full !!");
else
strcpy(listName[(*pn)++],str);
}


Thanks advance for your help!!

Answer

It is not crashing. Now its up to you to make it work as you wish.

void addStudent(char* name, char listName[][31], int* n) {
    int id;
   // printf("%s", name);
    id = findName(name, listName, n);
    if(id < 0) {
        addName(name, listName, n);
        printf("%s has been added\n", name);
    } else
        printf("The student already exists\n");
}


int findName(char* name, char listName[][31], int n) {
    int found = 0;
    int i, id;
    id = -1;
    for(i = 0; i<100 && &(n) < 100 &&(!found); i++)
        if(strcmp(listName[i], name) == 0) {
            found = 1;
            id = i;
        }
    return id;
}

void addName(char str[31], char listName[][31], int* pn) {
    if(pn > 100)
        printf("List is full !!\n");
    else
        strcpy(listName[(*pn)++],str);
}


void main(int argc, char *argv[]) {
    int n = 0;
    char listStudent[100][31];
    int id;
    addStudent("John ABC", listStudent, &(n));
    addStudent("David Davinci", listStudent, &(n));
}