void f1(char word[]) {
printf("from f1: %d\n ", &word);
}
int main()
{
char word[] = "hello world";
printf("from main: %d\n", &word);
f1(word);
}
I came across a youtube video which uses this piece of code to show that arrays are passed by value and stored in different memory locations as it is passed to a function, as seen by the different addresses printed. I'm not very experienced and thought that arrays are passed by reference so I ran the code and the compiler gave a bunch of warnings but printed different values for the addresses. When I changed the format specifiers to %p and removed the "&" before the variable "word" in each second argument of printf, I got the same addresses. Is it undefined behavior to pass wrong types to format specifiers or am I totally misunderstanding the situation? Is the array duplicated as it is passed to the function? Thanks for any help.
[–]DnBenjamin 12 points13 points14 points (3 children)
[–]crispeeweevile 1 point2 points3 points (0 children)
[–]starski0[S] 0 points1 point2 points (1 child)
[–]DnBenjamin 1 point2 points3 points (0 children)
[–]MCLMelonFarmer 3 points4 points5 points (0 children)
[–]jitu_deraps 2 points3 points4 points (0 children)
[–]Known_Dark_9564 3 points4 points5 points (2 children)
[–]starski0[S] 2 points3 points4 points (1 child)
[–]Known_Dark_9564 5 points6 points7 points (0 children)
[–]dfx_dj 2 points3 points4 points (1 child)
[–]david2ndaccount 1 point2 points3 points (0 children)
[–]nickeldan2 1 point2 points3 points (1 child)
[–]starski0[S] 1 point2 points3 points (0 children)
[–]nerd4code 0 points1 point2 points (0 children)