簡體   English   中英

在 C 中創建動態數組讀取器,分段錯誤

[英]Creating a dynamic array reader in C, segmentation fault

"Implement function int *create_dyn_array(unsigned int n) that allocates an int array for n integers. n is given as argument to the function when it is called. After allocating the array, the function should read the given number of integers to the array來自用戶,使用 scanf function。在讀取了適量的整數后,function 返回指向動態分配數組的指針。”

無論我做什么,我都會遇到分段錯誤。 此外,由於某種原因,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;
    }

代碼中有一些錯誤使其無法按預期工作,實際上它似乎根本無法編譯。 這是帶有注釋的更正代碼:

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

那應該這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM