Why do the same functions have different results except for the parameter order of the functions?
Like, for example:
My Code
#include <stdio.h>
#define MAX_SIZE 100
void sum2(float *list, int n);
void sum3(int n, float *list);
float input[MAX_SIZE];
int main(void){
printf(" sum2(input, MAX_SIZE) \n");
sum2(input, MAX_SIZE);
printf(" sum3(MAX_SIZE, input) \n");
sum3(MAX_SIZE, input);
}
void sum2(float *list, int n)
{
printf("&list \t= %p\n\n", &list);
}
void sum3(int n, float *list){
printf("&list \t= %p\n\n", &list);
}
Output
sum2(input, MAX_SIZE)
&list = 0x16fc5b268
sum3(MAX_SIZE, input)
&list = 0x16fc5b260
Expected
sum2(input, MAX_SIZE)
&list = 0x16fc5b268
sum3(MAX_SIZE, input)
&list = 0x16fc5b268
As in the above code, other results were output from the same function except for the order of the parameters.
I tried to find a similar question, but I couldn't find it. I think that if it is a function with the same value, the same value should be output regardless of the order of the parameters. Is there an error in my opinion?
For your information, my compiler is Apple clang version 14.0.0 (clang-1400.0.29.202).
Thank you for any answers.
It is because you print the address (reference) of the local variable list
not the reference of the static storage duration array input
. How the parameters are passed to the function is implementation-defined and you should not make assumptions.
If you modify the program you will see the difference:
#include <stdio.h>
#define MAX_SIZE 100
void sum2(float *list, int n);
void sum3(int n, float *list);
float input[MAX_SIZE];
int main(void){
printf(" sum2(input, MAX_SIZE) \n");
sum2(input, MAX_SIZE);
printf(" sum3(MAX_SIZE, input) \n");
sum3(MAX_SIZE, input);
}
void sum2(float *list, int n)
{
printf("address of list \t= %p\n", (void *)&list);
printf("address kept in list \t= %p\n", (void *)list);
printf("address of input \t= %p\n\n", (void *)input);
}
void sum3(int n, float *list){
printf("address of list \t= %p\n", (void *)&list);
printf("address kept in list \t= %p\n", (void *)list);
printf("address of input \t= %p\n", (void *)input);
}
and the output is:
sum2(input, MAX_SIZE)
address of list = 0x7ffff4b9b178
address kept in list = 0x404060
address of input = 0x404060
sum3(MAX_SIZE, input)
address of list = 0x7ffff4b9b170
address kept in list = 0x404060
address of input = 0x404060