Using realloc inside a function [duplicate]

心不动则不痛 提交于 2019-11-28 13:08:44

You need to pass a pointer to a pointer to myFunction

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

int myfunction(float **input) {
    int i,n=10;
    *input = realloc( *input, n*sizeof(float) );
    if(*input!=NULL) {
        for(i=0;i<n;i++) (*input)[i] = (float)i;
        return(n);
    }
    else return(-1);
}

int main(int argc, char *argv[]) {
    float *data = NULL;
    int n = myfunction(&data);
    int i;
    for(i=0;i<n;i++) printf("%f\n",data[i]);
    free(data);
    return 0;
}

It's easiest to pass the old pointer to myfunction(), and have it return the new pointer (which might be the same as the old, if realloc() managed to grow the area in-place).

Note that realloc() can fail, in that case you don't want to lose track of the old memory which is still allocated so overwriting the same pointer without checking is a bad idea.

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