简体   繁体   English

在C中使用指针添加整数

[英]Adding integers with pointers in C

Say i have int *a, int *b, int *c and say a and b already point to some integers. 说我有int *a, int *b, int *c并说ab已经指向一些整数。

I want to add the integers down a and b and save them to wherever c is pointing to 我想在ab下添加整数并将其保存到c指向的任何位置

This: 这个:

*c = *a + *b;

does not work. 不起作用。 It always spits out "invalid argument of 'unary *'. Why so? 它总是吐出“'一元*'的无效参数。为什么这样?

ADDITIONAL INFO: here's how I'm trying to implement it: 其他信息:这是我尝试实现的方法:

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

Here is a working example: 这是一个工作示例:

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

Running yields: 运行收益:

./a.out 
1 + 2 = 3

Common errors you might have encountered: 您可能遇到的常见错误:

  1. Not pointing a, b or c at valid memory. 没有将a,b或c指向有效内存。 This will result in your program crashing. 这将导致您的程序崩溃。
  2. Printing the value of the pointer (a) rather than the value it points to (*a). 打印指针的值(a),而不是它指向的值(* a)。 This will result in a very large number being displayed. 这将导致显示非常大的数字。
  3. Not dereferencing the assignment c = *a + *b rather than *c = *a + *b. 不取消引用分配c = * a + * b而不是* c = * a + * b。 In this case, the program will crash when you try to dereference c after the assignment. 在这种情况下,当您尝试在分配后取消引用c时,程序将崩溃。

If Ovendx, Ovendy are pointing to a valid memory locations, then to assign values to that location, you need to dereference them. 如果Ovendx,Ovendy指向有效的内存位置,则要为该位置分配值,您需要取消引用它们。 So, it should be - 因此,应该是-

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

You aren't dereferencing in the snippet posted. 您没有在发布的代码段中取消引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM