pointer in function don't return correct address [duplicate]

匆匆过客 提交于 2019-12-13 07:34:59

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!