I have an array a whose values I wish to modify through another function. This is the code that I have:
#include "stdlib.h"
#include "stdio.h"
void myfunc(int* );
int main() {
int *a, i;
a = (int*) calloc(10,sizeof(int));
myfunc(&a);
for (i=0; i<10; i++) printf("%d\n", a[i]);
return 0;
}
void myfunc(int* a) {
int i;
for (i=0; i<10; i++) *a[i] = i;
}
Obviously something is wrong with my syntax and I Was wondering if someone could lend me a hand 🙂
Thanks!
In the main function, you’ve got a pointer to an integer,
a. Then you pass the address of this pointer tomyfunc, butmyfuncis expecting a pointer to an int, not a pointer to a pointer to an int. You need to change your call tomyfuncto this:But, you’ve also got a problem inside
myfunc. You don’t need to dereferencea[i]since that indexes into an arraya. These are (effectively) the same thing:and
(This isn’t 100%, I think, because in C pointers and arrays are not completely the same thing, so some expert C programmer can correct me)
You’re probably just get a bit confused by the collection of syntax around pointers and arrays:
The first one is the address of
a, the second dereferencesaas a pointer, the third is an index into an array and the fourth is dereferencingaas a pointer with an offset.You would only want to do this
*(a[i])if you had an array of pointers, not a pointer to an int.