3

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

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.

Any simple suggestions appreciated!

4

2 回答 2

6

您需要将指针传递给指向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;
}
于 2013-04-23T12:58:50.773 回答
0

将旧指针传递给 是最简单的,让它返回新指针(如果设法就地扩大区域,myfunction()它可能与旧指针相同)。realloc()

请注意,这realloc()可能会失败,在这种情况下,您不想丢失仍然分配的旧内存,因此在不检查的情况下覆盖相同的指针是一个坏主意。

于 2013-04-23T13:05:41.587 回答