user3220347
user3220347

Reputation: 1

Array only adds duplicate values

When I print the contents of my array, it seems to override every element with the last command entered:

typedef struct
{
  int   argc;
  char* argv[10;
  char* myArray[80];
  size_t size;

} Command;

Inside main:

Command cmd;

cmd.myArray[cmd.size++] = buffer;

(Buffer being user input that I've checked with a printf to make sure it was the right thing being stored)

The function:

void myFunction(const Command* cmd)
{
  for (size_t i = 0; i < (cmd->size)-1; ++i)
    {
      printf("%s\n", cmd->myArray[i]);
    }
}

Any help would be greatly appreciated.

Upvotes: 0

Views: 55

Answers (3)

Ted Bigham
Ted Bigham

Reputation: 4341

If buffer is also a char*, you might need something like this instead:

cmd.myArray[cmd.size++] = buffer[cmd.size];

Upvotes: 0

Barmar
Barmar

Reputation: 780842

You're setting every element of myArray to the same thing, buffer. You need to make copies of it to get distinct values:

char *temp = malloc(strlen(buffer)+1);
strcpy(temp, buffer);
cmd.myArray[cmd.size++] = temp;

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

This assignment transfers the ownership of the buffer:

cmd.myArray[cmd.size++] = buffer;

In other words, from that assignment on you must not modify the buffer, because by doing so you would alter a previously stored command. In order for this to work properly, you need to either copy the buffer, or allocate a new one on each iteration. If you would like to use a copy, add a call to strdup:

cmd.myArray[cmd.size++] = strdup(buffer);

If you would prefer to allocate a new buffer, add

cmd.myArray[cmd.size++] = buffer;
buffer = malloc(BUF_SIZE); // buffer needs to be a `char *`

Upvotes: 2

Related Questions