问题
I try to make a function that allocates an array in C and I don't get the right address.
this is the code:
#include <stdio.h>
#include <stdlib.h>
void allocate_array(int* arr, int size);
void print_array(int* arr, int size);
void main(){
int size;
int* arr;
printf("Please enter array size: ");
scanf("%d", &size);
allocate_array(arr, size);
print_array(arr, size);
}
void allocate_array(int* arr, int size){
int i;
arr = (int*)malloc(size*sizeof(int));
for(i=0; i<size; i++){
printf("arr[%d] = ",i);
scanf("%d", arr+i);
}
}
void print_array(int* arr, int size){
int i;
printf("\n");
for(i=0; i<size; i++){
printf("arr[%d] = %d\n", i, *(arr+i));
}
}
and this is the output that I get:
Please enter array size: 4
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[0] = 1
arr[1] = 0
arr[2] = 155039806
arr[3] = 32765
I tried to print the pointer in "allocate_array" function and in the "main" but I get different result.
Please help :)
Thanks!
来源:https://stackoverflow.com/questions/45420131/pointer-in-function-dont-return-correct-address