使用函数内的realloc [英] Using realloc inside a function

查看:126
本文介绍了使用函数内的realloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的道歉,我知道很多相关的问题已经被问,所以我会保持它非常简单。

My apologies, I know many related questions have already been asked, so I will keep it very simple.

尽管几年编程我找不到调整和修改函数中的数组(或几个)正确的语法。例如,说我希望有一个函数来填充与一组n的数字,其中n是该阵列中定义的阵列

Despite some years of programming I cannot find the correct syntax for resizing and modifying an array (or several) inside a function. For example, say I want a function to fill an array with a set of "n" numbers, where "n" is defined within the array:

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

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

我知道这是行不通的,因为我可能需要使用指针的指针,但我不能化解指针哪种组合,指针到指针,地址符号来使用内外功能的使用。

I know this will not work, as I probably need to use a pointer to a pointer, but I cannot resolve which combination of pointers, pointers-to-pointers, and address notation to use inside and outside the function to use.

任何简单的建议AP preciated!

Any simple suggestions appreciated!

推荐答案

您需要一个指向一个指针传递给 myFunction的

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;
}

这篇关于使用函数内的realloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆