0

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.

1
  • Are you allocating memory for char * pointer's before initializing it ?? And show what output you are getting. It would be easy to understand your questions Commented Jan 23, 2014 at 4:32

3 Answers 3

4

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;
Sign up to request clarification or add additional context in comments.

Comments

2

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 *`

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.