簡體   English   中英

在C中通過引用傳遞雙精度數組:總線錯誤10

[英]Passing a double array by reference in C : Bus error 10

#include <stdio.h>
#include <stdlib.h>

void setZero (double **, int);

int main (void) {
        double *ptr = NULL;
        int i, size = 3;
        ptr = (double *)malloc(size * sizeof(double));
//*
        setZero(&ptr, size);
/*/
        // Sanity test
        for ( i = 0 ; i < size ; ++i ) {
                printf("index %d/%d\n", i, (size-1));
                ptr[i] = 0;  // NOT EXPLODING...
        }
//*/
        free(ptr);
        return 0;
}

void setZero (double **_ref_array, int _size) {
    int i;

    for ( i = 0 ; i < _size; ++i ) {
        printf("index %d/%d\n", i, (_size-1));
        *_ref_array[i] = 0;  // EXPLODING...
    }
}

1)為什么不起作用?

2)什么是“公交車錯誤10”

PS我知道比用這種方式初始化數組更好,但是這恰好是我不了解的基礎概念的簡單示例。

取消引用發生在索引之后。

這表示“在索引'i'處獲取雙指針 ,然后將值0設置為該指針內地址處的內存”。

*_ref_array[i] = 0; 

這說:“從_ref_array獲取雙精度數組的地址,然后將該地址按i-double索引。

(*_ref_array)[i] = 0;

從給出的代碼來看,您不需要將指針的地址傳遞給函數。 您應該使用:

void setZero(double *ptr, int size)
{
    for (int i = 0; i < size; i++)
        ptr[i] = 0.0;
}

和:

setZero(ptr, size);

正如WhozCraig所說,您遇到的麻煩是:

*_array_ref[i]

被解釋為:

*(_array_ref[i])

代替:

(*_array_ref)[i]

如您所願。 前者正在踐踏堆棧。 后者正在初始化分配的內存。

如果確實必須將指針傳遞給該函數的指針,則可以將括號括在取消引用周圍,也可以分配局部指針並正常使用該指針,直到需要使用double指針為止。指針以更改調用函數中的值。

void setZero(double **ptr, int size)
{
    double *base = *ptr;
    for (int i = 0; i < size; i++)
    {
        base[i] = 0.0;
        // Or: (*ptr)[i] = 0.0;
    }
    ...presumably some code here needs to assign to *ptr...
    ...if there is no such code, there is no need of the double pointer...
}

暫無
暫無

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

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