2011-03-08 47 views
2

假設我有int *a, int *b, int *c並且說ab已經指向一些整數。在C中添加指針的整數

我想將它們添加下來ab整數,並保存到哪裏c指向

此:

*c = *a + *b; 

不起作用。它總是吐出「的無效參數‘一元*’爲什麼這麼

附加信息:? 這裏就是我正在努力實現它:

int getCoordinates(int argc, char *argv[], FILE *overlay, FILE *base, int *OVx, int *OVy, int *OVendx, int *OVendy, int *Bx, int *By, int *Bendx, int *Bendy) 
{ 

    ... // OVx and OVw are assigned here. I know it works so I won't waste your time with this part. 

    // Set overlay image's x and y defaults (0,0). 
    *OVx = 0; 
    *OVy = 0; 
    ... 

    OVendx = (*OVx) + (*OVw); 
    OVendy = (*OVy) + (*OVh); 
+4

它適用於我的機器。你到底有什麼問題? – 2011-03-08 00:57:43

+0

你確定你正確地賦值嗎? [這個例子](http://ideone.com/aRFAt)工作正常。 (請注意,您必須對指針進行取消引用以查看值,您可能不會這樣做。) – 2011-03-08 00:58:57

+0

完美地工作。發佈一個完整的例子,說明問題,以及您的預期和觀察到的行爲。 – 2011-03-08 00:59:22

回答

2

這裏是一個工作示例:

#include <stdio.h> 

int main(int argc, const char* argv[]) 
{ 
    int x = 1; 
    int y = 2; 
    int z = 0; 
    int *a = &x; 
    int *b = &y; 
    int *c = &z; 

    *c = *a + *b; 

    printf("%d + %d = %d\n", *a, *b, *c); 
    return 1; 
} 

運行率:您可能遇到

./a.out 
1 + 2 = 3 

常見錯誤:

  1. 沒有指向a,b或c。在有效 存儲器。這將導致您的程序崩潰。 (a)打印 指針(a)的值,而不是指向(* a)的值。這將導致顯示一個非常大的數字。
  2. 不取消引用賦值c = * a + * b而不是* c = * a + * b。在這種情況下,當您在分配後嘗試取消引用c時,程序會崩潰。
2

如果Ovendx,Ovendy指向一個有效的內存位置,那麼要爲該位置指定值,則需要對它們進行解引用。因此,它應該是 -

(*OVendx) = (*OVx) + (*OVw); 
(*OVendy) = (*OVy) + (*OVh); 

您不是在發佈的代碼段中取消引用。