Reputation: 107
Trying to understand how a pointer works in a function that returns an array.
When the temp array is returned to the function, why is it that p[0] is 1 and p[1] is 3? Since x and y variable are swapped within the function and temp[0] and temp[1] are not swapped.
int *swap(int *x, int *y){
static int temp[2];
temp[0] = *x;
temp[1] = *y;
*x = temp[1];
*y = temp[0];
return temp;
}
int main() {
int x = 3;
int y = 1;
int *p = swap(&x, &y);
GPIO_PORTF_AHB_DATA_BITS_R[LED_RED] = LED_RED;//turn on red led
delay(p[0]);
GPIO_PORTF_AHB_DATA_BITS_R[LED_RED] = 0;//turn off red led
delay(p[1]);
}
Upvotes: 0
Views: 174
Reputation:
why is it that p[0] is 1 and p[1] is 3
It isn't.
Replacing your microcontroller-specific code with:
printf("p[0] = %d, p[1] = %d\n", p[0], p[1]);
and running your code on a computer gives me the output:
p[0] = 3, p[1] = 1
as expected.
Upvotes: 3