简体   繁体   中英

Passing a pointer to an array in a function in C

I need to write a program that implements 3 ways of passing an array to a function.

2 functions work as intented, but I am having issues with the function that passes a pointer. I tried googling it, and testing other way, but I don't seem to understand how those pointers should work out. First function should output 1, 2, 3.

Second function should output 11, 12, 13

Third function should output 101, 102, 103

First and third function work, but the issues is with the second one. Here's what I wrote:

int main(void)
{
   int iArray[3] = {100,234,567};

   f1(iArray);
   f2(iArray);
   f3(iArray);

   return EXIT_SUCCESS;
}

void f1(int ia[3]) // sized array
{
   ia[0] = 1;
   ia[1] = 2;
   ia[2] = 3;

   for (int i = 0; i < 3; i++)
   {
      printf("%d\n", ia[i]);
   }
   printf("\n");
}

void f2(int* pi) // pointer
{
   *pi = 11, 12, 13;

   printf("%d", *pi);
   printf("\n\n");

}

void f3(int ia[]) // unsized array
{
   ia[0] = 101;
   ia[1] = 102;
   ia[2] = 103;

   for (int i = 0; i < 3; i++)
   {
      printf("%d\n", ia[i]);
   }
}

In C you can't pass an array, only pointers to their elements. That means for all arguments like int ia[] the compiler really treats it as int *ia . Any potential "array" size is irrelevant, all your functions are taking the exact came int * type argument.

This is because arrays naturally decay to pointers to their first elements.

In fact, the function calls

f1(iArray);
f2(iArray);
f3(iArray);

are actually equal to

f1(&iArray[0]);
f2(&iArray[0]);
f3(&iArray[0]);

Now for the problem with the second function, it's this line:

*pi = 11, 12, 13

That is equivalent to:

pi[0] = 11, 12, 13;

which is using the comma operator which makes it equivalent to:

pi[0] = 13;

To assign each element of the array you need to index each element just like you do with the "array" functions:

pi[0] = 11;
pi[1] = 12;
pi[2] = 13;

Of course you need to print the values the same way as well, with a loop.

The syntax for referencing pointers is the same as for an array:

   pi[0] = 1;
   pi[1] = 2;
   pi[2] = 3;

You'll also want to change the printf loop accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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