JonnyMca1081
JonnyMca1081

Reputation: 49

Is There way to take the contents of an array and store it into a pointer?

I am writing a a program that produces similar results to the command ls -l. Currently I can produce the results through loops, but now I want to store certain variables into a linked list so I can later put it through a lexical-graphic sorter. I can store most of the variable into the node properly, but the problems stems from when I'm trying to store the permission variable. Is there a way I can get the contents of an char[] to a char *?

With the way I have it set up the permissions are stored in a char[], but I haven't found away to use char[] as a return type, so I decided a char * would be more appropriate but now I'm trying to figure out how to go from char[] to a char*.

char* find_perms(mode_t st) {
    char* perms_ptr;
    char perms[11];
    if(st && S_ISREG(st)) perms[0]='-';
    else if(st && S_ISDIR(st)) perms[0]='d';
    else if(st && S_ISFIFO(st)) perms[0]='|';
    else if(st && S_ISSOCK(st)) perms[0]='s';
    else if(st && S_ISCHR(st)) perms[0]='c';
    else if(st && S_ISBLK(st)) perms[0]='b';
    else perms[0]='l';  // S_ISLNK
    perms[1] = (st && S_IRUSR) ? 'r':'-';
    perms[2] = (st && S_IWUSR) ? 'w':'-';
    perms[3] = (st && S_IXUSR) ? 'x':'-';
    perms[4] = (st && S_IRGRP) ? 'r':'-';
    perms[5] = (st && S_IWGRP) ? 'w':'-';
    perms[6] = (st && S_IXGRP) ? 'x':'-';
    perms[7] = (st && S_IROTH) ? 'r':'-';
    perms[8] = (st && S_IWOTH) ? 'w':'-';
    perms[9] = (st && S_IXOTH) ? 'x':'-';
    perms[10] = '\0';
    printf("%s ",perms);
    perms_ptr = perms;
    return perms_ptr;
}

as it is right now this does return a char*, but instead of pointing to the array that I was hoping I could use later it points to an empty string. When I used gdb to view what perms_ptr was pointing to it just showed up as "".

Upvotes: 0

Views: 68

Answers (1)

Roberto Caboni
Roberto Caboni

Reputation: 7490

A char [] symbol can be accessed exactly like a char *. It can be easily returned, but it has to be dynamically allocated inside the function or otherwise passed as a parameter of the function.

Returning a local variable is a mistake that leads to undefined behaviour, because it is stored in the stack and will be overwritten as soon as the funtion returns.

In your function returning perms is ok (no need to define another pointer) if you allocate it with perms = malloc (11);

(You will have to free it outside your function).

Upvotes: 1

Related Questions