【问题标题】:Assign value to char * from ScanF从 ScanF 为 char * 赋值
【发布时间】:2013-09-16 05:45:15
【问题描述】:

有人可以帮我理解为什么当我尝试打印出 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 %s\n", *student_name);
            add_item(dictionary, stu_id[0], exam1[0], exam2[0], student_name);
    }
    free(dictionary);
    free(student_name);
    return 0;

}

【问题讨论】:

  • 你没有初始化i并在while(i &lt; s){...dictionary-&gt;table[i]=NULL;...}中使用并使用i作为索引 --> Undefined behaviour
  • 请分享您的结构哈希表代码和add_item代码
  • 你需要使op更大(即char op[128];)`。

标签: c pointers memory-management malloc


【解决方案1】:

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

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

另外,不要将整数变量声明为数组,而是在调用scanf 时使用地址运算符&amp;

char op;
int stu_id;
int exam1;
int exam2;

/* ... */

scanf("%c %d %d %d %s", &op, &stu_id, &exam1, &exam2, student_name)

您也不应该检查scanfEOF 的返回值,以防输入格式不正确。将其与您要扫描的值的数量进行比较,在您的情况下为五个。

【讨论】:

  • 问题是学生姓名没有被分配给我为它创建的字符 *,我不知道它为什么这样做。
  • @EricaFischer-Colbrie 当你这样做时,例如printf("Intializing %s\n", *student_name); 你告诉printf 打印一个字符串,但*student_name 返回第一个字符。这是未定义的行为,你应该得到一个警告。从student_name 中删除取消引用运算符*
【解决方案2】:

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

您需要在 main() 结束时释放为“dictionary->table”分配的内存。

【讨论】:

    猜你喜欢
    • 2020-07-15
    • 1970-01-01
    • 2020-12-10
    • 2018-04-03
    • 2013-02-01
    • 2011-08-13
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    相关资源
    最近更新 更多