I've only been doing C for a few weeks so I am quite new to it.
I've seen things like
* (variable-name) = -* (variable-name)
in lecture notes but what exactly would it do? Would it just negate the value being pointed to?
I've only been doing C for a few weeks so I am quite new to it.
I've seen things like
* (variable-name) = -* (variable-name)
in lecture notes but what exactly would it do? Would it just negate the value being pointed to?
Yes. When you add the star it means it is pointing to the value. It is essentially saying: to the value at address (variable-name), become -1* the value of (variable-name).
If you are new to C, you may find it easier to use & instead of pointers. &'s are essentially the opposite of *. & doesn't point, it gives the address of a variable (which I find to be a simpler concept).
The following is an example which should demonstrate the use of *
and &
.
#include <stdio.h>
int main(void)
{
int blah = 6;
int *num = &blah;
(*num) = -(*num);
printf("%d\n", num); //Displays num
}
Yes it negates the value being pointed to. We cannot write operations on addresses so operations are done on deferenced pointers. Here, *d = -*c
means:
*d = (-1) * (*c)
Sample code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *c;
int *d;
d = (int *)malloc(sizeof(int));
c = (int *)malloc(sizeof(int));
*c = 9;
*d = -*c;
printf("%d", *d);
free(c);
free(d);
return 0;
}