Lienau
Lienau

Reputation: 1353

Overwriting array of structs in C

I'm trying to pass a pointer to an array of structs to a function. Then have the function create its own array of structures, populate it with data and then overwright the the old array with the new array.

I'm pretty sure the problem is with occurring when I try to overwrite the memory. I think that I could be either using the wrong method to overwrite the memory(should I be using the memory functions?) or I might be trying to overwrite the wrong thing. I'm not quite sure what I'm doing wrong. If someone could point me in the right direction I would be extremely thankful; I've been pulling the hair out of my head for like three hours now.

Struct:

typedef struct
{
        char command;
        int argc;
        char* argv[];
}cmd;

Code:

int main(int argc, char *argv[])
{
    [... irrelevant code]
    cmd cmdv[count];
    cmd* cmdv_ptr = &cmdv[0];
    dissectCmd(cmdstr, cmdv_ptr);
    printf("%i", cmdv[0].argc);
    return 0;
}

void dissectCmd(char* str, cmd* cmdv)
{
    [... irrelevant code]
    cmd cmds[count];
    int i = 0;
    for(i = 0; i < count; i++)
    {
        cmd next;
        next.command = 'u';
        next.argc = 100;
        cmds[i] = next;
    }
    cmdv = cmds;
}

Upvotes: 0

Views: 1672

Answers (2)

davogotland
davogotland

Reputation: 2777

i'm not sure about this, but try declaring

void dissectCmd(char* str, cmd* cmdv)

as

void dissectCmd(char* str, cmd** cmdv)

changing

cmdv = cmds;

to

(*cmdv) = &cmds;

and changing current call from main which is now

dissectCmd(cmdstr, cmdv_ptr);

to

dissectCmd(cmdstr, &cmdv_ptr);

also, when you do this, you loose the address to the old array completely, creating a memory leak. unless you already free that memory in your second [... irrelevant code] passage :)

Upvotes: -1

Chris Dodd
Chris Dodd

Reputation: 126233

You're not overwriting the memory -- the statement cmdv = cmds just copies the pointer (making cmdv point at cmds.) If you want to actually copy the memory, you need memcpy(cmdv, cmds, count * sizeof(cmd));

Upvotes: 3

Related Questions