【问题标题】:Adding records with pointers to arrays使用指向数组的指针添加记录
【发布时间】:2014-12-24 01:16:40
【问题描述】:

我必须创建一个将记录添加到简单电话簿的程序。代码在下面,但它不起作用 - 函数结束,然后卡在声明 struct record x 并且不想显示我添加的记录 - 程序崩溃了。当我将这部分代码放在函数的末尾时(而不是“struct record x = array[0];”我放了“struct record x = (*array)[0]”)它可以工作 - 打印记录.所以我想问题出在指针上,但我很挣扎,我真的找不到问题所在。我记得几周前我创建了一个非常相似的程序,但它向整数数组添加了一条新记录,具有固定值并且运行良好,所以也许有一些我不知道的结构。感谢您的帮助!

我知道程序还没有完成,我知道我没有对 temp_array == NULL 进行任何操作,等我知道发生了什么之后再做。

struct record {
    char f_name[SIZE];
    char name[SIZE];
    long int phone;
};

int add_record(struct record** array, int n)
{
    struct record* temp_array = malloc((n+1) * sizeof(struct record));
    if (temp_array == NULL)
    {
        free(temp_array);
        return -1;
    }
    int i;
    for (i=0; i < n; i++)
    {
        temp_array[i] = (*array)[i];
    }
    struct record new_record;
    printf("\nAplly data.");
    printf("\nFirst name: "); /*fgets(new_record.f_name, SIZE, stdin);*/ scanf("%s", &new_record.f_name);
    printf("Surname: "); /*fgets(new_record.name, SIZE, stdin);*/ scanf("%s", &new_record.name);
    printf("Phone number: "); scanf("%d", &new_record.phone);
    temp_array[n] = new_record;
    free (*array);
    *array = temp_array;
    //struct record x = (*array)[0];
    //puts(x.f_name); puts(x.name); printf("%d", x.phone);
    return 0;
}

main()
{
    struct record* array; int n = 0;
    int choice;
    printf("\n1. Add record\n2. Delete record\n3. Find record\n0. Exit\n\nChoose action: ");
    scanf("%d", &choice);
    switch(choice) {
        case 0: printf("\nKsiazka zostala zamknieta.\n"); return;
        case 1: add_record(&array, n); n++; break;
        case 2: return;
        case 3: return;
        default: printf("Wrong choice.\n\n"); return;
    }
    struct record x = array[0];
    puts(x.f_name); puts(x.name); printf("%d", x.phone);
}

【问题讨论】:

  • “它停留在声明 struct record x [...] 程序崩溃”是什么意思?这是编译错误(发布整个错误)还是运行时问题(尽可能具有描述性)?
  • struct record* array=NULL;,并将%ld 用于long int
  • 这个程序有几个问题。如果temp_array == NULL 那么你不想做free(temp_array) 因为temp_array 从来没有分配一个有效的地址。你用&amp;array 调用add_record...,它的类型为struct record **array(它是一个指向指针的指针)。您应该只传递array,因为它已经是一个指针。当你用array 调用add_record 时,结构指针没有分配给它的有效地址,如果有,也没有数据分配给它。所以add_record的功能会失效。
  • @lurker 它不会伤害任何东西,但首先不需要这样做当然是正确的。 free() ing NULL 是已定义的无操作行为。
  • @BLUEPIXY 谢谢,但你能描述一下为什么会这样吗? free()实际上不是将指针设置为NULL吗?

标签: c arrays pointers struct


【解决方案1】:

struct record* array=NULL;,并将%ld 用于long int – BLUEPIXY

【讨论】:

    猜你喜欢
    • 2014-10-22
    • 2015-06-17
    • 2021-02-07
    • 2023-04-01
    • 2011-01-27
    • 2016-07-30
    相关资源
    最近更新 更多