C程序使用数组char *崩溃

时间:2016-10-05 14:11:32

标签: c crash

我想构建一个允许插入名称和打印出来的程序。但程序一旦开始就会崩溃。

这是我的主要课程:

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);
}

还有一些函数可以调用

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);  
}

感谢您的帮助!!

1 个答案:

答案 0 :(得分:0)

它没有崩溃。 现在由您决定是否按照您的意愿工作。

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));
}