【问题标题】:Creating a dynamic array reader in C, segmentation fault在 C 中创建动态数组读取器,分段错误
【发布时间】:2021-05-19 19:37:45
【问题描述】:

"实现函数 int *create_dyn_array(unsigned int n),它为 n 个整数分配一个 int 数组。n 在调用时作为函数的参数给出。分配数组后,函数应该读取给定数量的整数使用scanf函数从用户到数组。在读取了正确数量的整数后,该函数返回指向动态分配数组的指针。"

无论我做什么,我都会遇到分段错误。此外,由于某种原因,scanf 接受 6 个整数,即使我将 for 循环“n”更改为像 3 这样的常量??绝对神秘。我究竟做错了什么?感谢您在这里提供任何可能的帮助...

  int *create_dyn_array(unsigned int n)
    {
        
        int *array = malloc(n * sizeof(*array));
    
        int i;
    
        for (i = 0; i < n; i++) {
            scanf("%d\n", &(*array)[i]);
        }
    
        return *array;
    }
    
    void printarray(const int *array, int size) {
        printf("{ ");
        for (int i = 0; i < size; ++i) {
            printf("%d, ", array[i]);
        }
        printf(" }\n");
    }
    
    int main()
    {
       
        int *array = create_dyn_array(5);
        printarray(array, 5);
    
       return 0;
    }

【问题讨论】:

  • &amp;(*array)[i] 更改为&amp;array[i]return *array 更改为return array。后者应该给你一个编译器的警告。
  • 哦,从scanf 中删除"\n"。请参阅:Using “\n” in scanf() in C

标签: arrays c pointers dynamic


【解决方案1】:

代码中有一些错误使其无法按预期工作,实际上它似乎根本无法编译。这是使用 cmets 的更正代码:

int *create_dyn_array(unsigned int n)
{

    int *array = malloc(n * sizeof *array);

    // since you use an unsigned int better to not compare it with int
    for (size_t i = 0; i < n; i++) 
    {
        scanf("%d", &array[i]); // your code had the address of a pointer to array 
                                // you need the address of the element of
    }                           // of the array where to store the value
 
    return array; // return the pointer itself
}

void printarray(const int *array, int size)
{
    printf("{ ");
    for (int i = 0; i < size; ++i)
    {
        printf("%d, ", array[i]);
    }
    printf(" }\n");
}

int main()
{

    int *array = create_dyn_array(5);
    printarray(array, 5);

    return 0;
}

应该可以的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 1970-01-01
    相关资源
    最近更新 更多