0

I was wondering if it was posible to declare an array of strings inside a function and return its pointer to main so as to keep working with the same array.

I already know how to send the pointer to an array to a function so I can work with the same array inside it, but I'm having trouble reversing this process. I tried several things but it doesn't seem to work and honestly I don't even know where to begin. I would appreciate it if someone could explain me what I am getting wrong because obviously I have no idea what I'm doing. This code was written in C, but I believe it would be the same or very similar for C++.

#include <stdio.h>
#define Y 8


char *ini();


int main() {
    //I have no idea what I'm doing
    char *chP= ini();
    char planets[Y][10] = chP;

    //Just for printing the array
    for(int i = 0;i<Y;i++){
        printf("\n%s", planets + i);
    }
    return 0;
}


char *ini() {
    char *chP;
    char planets[Y][10] = {
            "Mercury",
            "Venus",
            "Earth",
            "Mars",
            "Jupiter",
            "Saturn",
            "Uranus",
            "Neptune"
    };
    chP = planets;
    return chP;
}
afd2
  • 1
  • 2
    You may not return a pointer to a local array with automatic storage duration. So either an array must be declared with static storage duration using the keyword static or should be dynamically allocated. Pay attention to that the pointer in your program has an incorrect type relative to the declaration of the array. The array has to be declared like char ( *chP )[10]; – Vlad from Moscow Jan 24 '21 at 19:42
  • @VladfromMoscow I am sorry but I am a beginner to coding and I am having a bit of trouble understanding your answer. Would it be possible for you to elaborate a bit more on it? – afd2 Jan 24 '21 at 19:44
  • You are trying to return a pointer to a local array declared in a function that (array) will not be alive after exiting the function. So the pointer will be invalid – Vlad from Moscow Jan 24 '21 at 19:46
  • In simple terms, since planets is defined inside ini(), it "goes away" when ini() returns. You need "planets" to exist more permanently so you can refer to it back in main(). One way to fix this: use "static char planets[Y][10]" inside the ini() function. – dashrb Jan 24 '21 at 19:48
  • @afd2 I made a typo in the first comment. I meant that the pointer has to be declared like char ( *chP )[10]; – Vlad from Moscow Jan 24 '21 at 19:48
  • I think @afd2 misunderstanding is that `chP = planets` is not copying anything: only `chP` points to the variable `planets`, which gets freed once `ini` returns the control to main. There are several solutions to that: the both pointed by @Vlad from Moscow (declare it static with `static char planet...` or do it global `char planet[][] = /*...*/; char*ini(){ /*...*/}`), or (a new one) generate a dynamic array using `malloc` or `calloc`. – emi Jan 24 '21 at 19:56

0 Answers0