2

I made this function:

char** parse_cmd(const char* cmdline) {
    int i;
    int j = 0 ,k = 0;
    char ch[100][100];
    for(i=0; i<strlen(cmdline); i++) {
        if(cmdline[i] != ' ') {
            ch[j][k] = cmdline[i];
            k++;
        } else {
            j++;
            k = 0;
        }
    }

    return ch;
}

But when I compile the program I have this warning:

shell.c: In function ‘parse_cmd’:
shell.c:25:2: warning: return from incompatible pointer type
shell.c:25:2: warning: function returns address of local variable

Why?

1
  • 7
    Apart from anything else you can't return local arrays from functions like that, or indeed at all. Commented May 15, 2011 at 17:06

3 Answers 3

3

You try to return a pointer to a memory location that will not be associated with the array after the function returned. If you want to permanently allocate the memory, then you have to copy it with malloc (or any similar function) before returning it.

e.g:

char** parse_cmd(const char* cmdline) {
int i;
int j = 0 ,k = 0;
char **ch = (char**)malloc(100*100);
for(i=0; i<strlen(cmdline); i++) {
    if(cmdline[i] != ' ') {
        ch[j][k] = cmdline[i];
        k++;
    } else {
        j++;
        k = 0;
    }
}
return ch;
}

EDIT: fixed typo. Thanx

Sign up to request clarification or add additional context in comments.

4 Comments

char **ch not char ch**. And you can't allocate a char ** with one malloc.
You can, if you cast, but that seems like a hack, doesn' it? :/
No you can't. Dereferencing a char ** gives a value of type char *. It expects to point somewhere. You need to a) allocate a char (*)[100], b) do a loop to allocate each row, or c) change it to char * and manually index via multiplication, i.e. ch[i * 100 + j] instead of ch[i][j].
Also you shouldn't cast the result of malloc in C.
3

You're returning a pointer to memory that lives on the stack. Use heap allocated memory instead.

Comments

2

The ch array is deallocated at the end of the function, that memory is stored on the stack which is invalid after the function returns. You should instead create a array in the calling function and pass the pointer into the parse_cmd() function.

1 Comment

+1 but it should also be noted that char [N][O] does not decay to char **, but to char (*)[O].

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.