2

Say i have int *a, int *b, int *c and say a and b already point to some integers.

I want to add the integers down a and b and save them to wherever c is pointing to

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);
10
  • 4
    It works on my machine. What problem exactly are you having? Commented Mar 8, 2011 at 0:57
  • Are you sure you're assigning the values correctly? This example works fine. (Notice you have to dereference the pointer to see the value. You might not be doing this.) Commented Mar 8, 2011 at 0:58
  • 4
    Have you initialized the pointer c to point to a valid memory location ? Commented Mar 8, 2011 at 1:00
  • 2
    It appears you need to dereference your assignment: *OVendx = (*OVx) + (*OVw); Your version is just moving the pointer. Commented Mar 8, 2011 at 1:09
  • 1
    Some of us suspected as much. Again, when posting questions, please don't leave out the critical lines that identify the bug. Commented Mar 8, 2011 at 1:44

2 Answers 2

2

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. This will result in your program crashing.
  2. Printing the value of the pointer (a) rather than the value it points to (*a). This will result in a very large number being displayed.
  3. Not dereferencing the assignment c = *a + *b rather than *c = *a + *b. In this case, the program will crash when you try to dereference c after the assignment.
Sign up to request clarification or add additional context in comments.

Comments

2

If Ovendx, Ovendy are pointing to a valid memory locations, then to assign values to that location, you need to dereference them. So, it should be -

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

You aren't dereferencing in the snippet posted.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.