Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handing array over to function. Correct use of pointers?

Tags:

c

pointers

I have an array/pointer related problem. I created an int array myArray of size 3. Using a function I want to fill this array. So I'm calling this function giving her the adress &myArray of the array. Is the syntax correct for the function declaration`? I'm handing over the pointer to the array, so the function can fill the array elements one by one. But somehow my array is not filled with the correct values. In Java I could just give an array to a method and have an array returned. Any help is appreciated! Thanks!

#include <stdio.h>

int myArray[3];

void getSmth(int *anArray[]);

int main(void)
{
  getSmth(&myArray);

}

void getSmth(int *anArray[])
{
  for(i=0...)
  {
    *anArray[i] = tmpVal[i];
  }
}
like image 791
tzippy Avatar asked May 27 '26 05:05

tzippy


1 Answers

Remove one level of indirection:

#include <stdio.h>

int myArray[3];

void getSmth(int anArray[]);

int main(void)
{
  getSmth(myArray);

}

void getSmth(int anArray[])
{
  for(i=0...)
  {
    anArray[i] = tmpVal[i];
  }
}

Also, as others have suggested, it would be a good idea to pass the size of the array into getSmth().

like image 147
NPE Avatar answered May 30 '26 03:05

NPE