0

No matter how many arrays are created in other_function(), the last array will always have the same memory address as the arr in mkarray1, which in this case makes "printf("%d %d %d\n", ptr[0], ptr[1], ptr[2])" print 1, 2, 3. Can somebody explain why? Thanks in advance.

#include <stdlib.h>
#include <limits.h>
#include <stdio.h>
#include <errno.h>

int *mkarray1(int a, int b, int c) {
int arr[3] = {a, b, c};
int *p = arr;
printf("the address of arr in mkarray1 is %p \n", &arr);
printf("the address of arr[0] is %p\n, arr[1] is %p\n, arr[2] is %p \n", &arr[0], &arr[1],&arr[12]);
return p;
}

void other_function(){
int arr[3] = {70, 80, 90};
printf("the address of arr in other_function is %p \n", &arr);
int notarr[3] = {40, 50, 60};
printf("the address of notarr in other_function is %p \n", &notarr);
int hello[3] = {1, 2, 3};
printf("the address of hello in other_function is %p \n", &hello);
}

int main() {
int *ptr = mkarray1(10, 20, 30);
printf("the address of ptr[0] is %p\n, ptr[1] is %p\n, ptr[2] is %p \n", &ptr[0], &ptr[1],&ptr[12]);
printf("the address of ptr in main is %p \n", &ptr);
other_function();
printf("the address of ptr after other_function is %p \n", &ptr);
printf("%d %d %d\n", ptr[0], ptr[1], ptr[2]);
}
itang3425
  • 1
  • 1
  • 1
    The pointer returned by `mkarray1()` points to invalid memory as it points to local variable. – kuro Feb 27 '23 at 05:44
  • 1
    Local variables only exist while the call to that function is active. When it returns, its local storage becomes available to subsequent function calls. If if didn't, you'd quickly run out of memory. That's why returning the address of a local variable results in an invalid pointer. That storage it pointed to is no longer valid. – Tom Karzes Feb 27 '23 at 05:55
  • 1
    is `arr[12]` in the print statements a typo? – Z4-tier Feb 27 '23 at 05:57
  • Also, there is no "always" here. Variables in different functions *can* use the same address, but they don't have to. – BoP Feb 27 '23 at 08:39

0 Answers0