5

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!

2
  • 1
    c-faq.com/ptrs/passptrinit.html Commented Apr 23, 2013 at 12:59
  • fair comment, but not quite what i was looking for ;) Commented Apr 23, 2013 at 13:40

2 Answers 2

8

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

That's perfect, thanks! If I were explaining it to someone else, I'd say you need to pass the address of the array, tell the function to treat it as a pointer-to-a-pointer, and within the function refer to the pointer itself when using realloc() or assigning values. Cheers!
What if there are already values in the array? realloc in principle copies the values, but it is done in the function. Do the values get lost in this way?
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.

1 Comment

I appreciate your point and I do exactly that in other circumstances but the "real" program is a helluva lot more complex than the simple example I posted, and requires modification of two or more arrays, growing each of them with realloc() as needed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.