在C中添加带指针的整数

时间:2011-03-08 00:54:23

标签: c pointers int memory-address addition

说我有int *a, int *b, int *c并说ab已指向某些整数。

我想在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);

2 个答案:

答案 0 :(得分: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有效 记忆。这将导致程序崩溃。
  2. 打印的价值 指针(a)而不是它的值 指向(* a)。这将导致显示非常大的数字。
  3. 不取消引用分配c = * a + * b而不是* c = * a + * b。在这种情况下,当您在分配后尝试取消引用c时,程序将崩溃。

答案 1 :(得分:2)

如果Ovendx,Ovendy指向有效的内存位置,然后要为该位置指定值,则需要取消引用它们。所以,它应该是 -

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

您在发布的代码段中没有取消引用。