0

I'm trying to transfer an array from a function I've created, taking input an array of char and a short, copied below

    char transl [] (char **x, short num){
    char newword []  = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    short num = num;
    FILE * wd;
    wd  = fopen(argv[1], "r");
    short w=0;
    short arrayle=sizeof(x);
    if (arrayle>9){
    while((c = getchar() != '\n') && c != EOF);
    }
    while(((c = fgetc(wd)) != EOF)&& (num>=1)) {
    if (c == ' ') {
    num--;
    }
    if (num == 1) {
    newword [w] = ((c = fgetc(wd)));
    w++;       
    }
    }
    fclose(wd);
    return newword;
    }

I return the array of set size back into the main in the following way.

     char newDay [32];
     newDay  = transl (engw, daynum);

I get the following error:

assignment to expression with array type

I read on Stack that I would have to pass back a pointer to the array, but wouldnt that pointer be invalid in the main without the array itself being passed back?

Anyways, extremely confused. Please advise, and thank you a lot in advance!

Robert Columbia
  • 6,313
  • 15
  • 32
  • 40
Max Segal
  • 27
  • 3

1 Answers1

1

In order to pass back an array from a function you need to do one of two things:

  • Allocate the array in static memory - This approach works only in single-thread systems, and only in situations that do not require re-entrancy
  • Allocate the array in dynamic memory - This has no restrictions for re-entrancy or concurrency, but the callers will be required to free the memory they receive in order to avoid memory leaks.

Here is an example of the second approach:

char *newword = malloc(30);
memset(newword, 0, 30);
...
return newword;

The caller of your function will need to call

free(resultOfCall);

after he is done processing the returned array.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523