C语言 从 ScanF 将值分配给字符 *



有人可以帮助我理解为什么当我尝试打印出student_name的值时,它只返回 null?我正在用 C 实现一个基本的哈希表来存储学生姓名、id 和 2 个测试。 其他一切都正确存储,无论我尝试什么,我都无法保存student_name。 我有两个结构,哈希表本身,然后记录,我打算放在表中的元素。字符串的长度永远不会超过 18 个字符。

int main(){
    char op[1];
    int stu_id[1];
    int exam1[1];
    int exam2[1];
    char * student_name = (char*)malloc(18*sizeof(char));
    struct hashtable * dictionary = malloc(sizeof(struct hashtable));
    dictionary->size = 13;
    dictionary->table = malloc(13*sizeof(struct record *));
    if(dictionary==NULL||dictionary->table==NULL){
        printf("Unable to allocate memory for the dictionary.n");
        return;
    }
    int i;
    int s = 13;
    while(i<s){
        dictionary->table[i]=NULL;
        i++;
    }
    while(scanf("%s %d %d %d %s", op, stu_id, exam1, exam2, student_name) !=EOF){
        if(*op=='i'){
            printf("Intializing %sn", *student_name);
            add_item(dictionary, stu_id[0], exam1[0], exam2[0], student_name);
    }
    free(dictionary);
    free(student_name);
    return 0;
}

请记住,字符串始终必须包含特殊的终止符字符 ( '' )。这意味着长度为 1 的字符串(如 op 数组)实际上是两个字符。

这意味着当你读入op时,你实际上是在超出数组的边界写入,从而导致未定义的行为。您要么需要增加op的大小(至少两个),要么将其声明为单个char(即不是数组)并使用'%c'格式代码读取单个字符。

此外,不要将整数变量声明为数组,而是在调用scanf时使用 address-of 运算符&

char op;
int stu_id;
int exam1;
int exam2;
/* ... */
scanf("%c %d %d %d %s", &op, &stu_id, &exam1, &exam2, student_name)

你也不应该根据EOF检查scanf的返回值,以防输入格式不正确。将其与要扫描的值数进行比较,在本例中为五个。

我想您正在为 add_item() 中的学生记录分配内存并将它们分配给字典>表。从您发布的代码来看,您分配内存是为了保存指向结构学生记录的指针,而不是记录本身。

您需要释放在 main() 末尾为 "dictionary->table" 分配的内存。

最新更新