Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Returning string array

Tags:

arrays

c

I want this program to return an array, and then a variable from main to get this array from the function, and be usable in a part of code that has to verify a string against these values from the initial variable. But the variable doesn't get the returned array. I've seen some posts saying that you cannot return arrays in C, but I've also seen other post where this was possible.

But I want to know what can I do to catch this returned value.

int getUsers()
{
    char userVect[5][25];
    char user[24];
    int i = 0, j = 0, k;

    FILE  *usernames;
    usernames = fopen("usernames.cfg", "r");
    if (usernames == NULL){
        perror("usernames - err");
        return(-1);
    }

    while(fgets(user, sizeof(user), usernames) !=NULL){
        strcpy(userVect[j], user);
        j++;
    }

    fclose(usernames);
    for(k=0; k<j; k++)
        printf("Usernames are:  %s\n", userVect[k]);

    return userVect;
}

int main()
{
    printf("\nWelcome to Sys v1.24. To start off, please insert your command. \n");
    char *users;
    users = getUsers();
    printf("%c\n", users);

    return 0;
}
like image 319
Justplayit94 Avatar asked Jun 14 '26 16:06

Justplayit94


1 Answers

1. You want to return a string and your function has type int??

I see you return a 2-d array, then your function should be of type char ** -

char **getUser(void)

2. You return local variable (userVect) from your function. You cannot access it outside function block .

You should do this in you function getUser-

char **userVect;
userVect=malloc(5*sizeof(char **));              //allocate memory  
for(int i=0;i<5;i++)
   userVect[i]=malloc(25*sizeof(char));   

And in main do this -

char **user;
...
user=getUsers();                 // call function 

3. And to printuser in main -

for(int i=0;i<5;i++)
    printf("%s\n", user[i]);          //this is wrong in your code- printf("%c\n", users);

And then free it in main at then end-

for(int i=0;i<5;i++)
    free(user[i]);
free(user);
like image 114
ameyCU Avatar answered Jun 16 '26 06:06

ameyCU



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!