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;
}
6
  • 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]; Commented Jan 24, 2021 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? Commented Jan 24, 2021 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 Commented Jan 24, 2021 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. Commented Jan 24, 2021 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]; Commented Jan 24, 2021 at 19:48

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.