Adam
Adam

Reputation: 10016

Shifting elements in array of strings, C

I want to shift each string in an array of strings one element to the left:

   char historyArray[HISTORY_DEPTH][COMMAND_LENGTH];

Neither of my two attempts below work. Can someone explain to me what I'm doing wrong?

for (int i = 1; i < HISTORY_DEPTH; i++) {
            strcpy(historyArray[i-1], historyArray[i]);
        }

for (int i = 1; i < HISTORY_DEPTH; i++) {
            historyArray[i-1] = historyArray[i];
        }

Upvotes: 1

Views: 2090

Answers (2)

sabbahillel
sabbahillel

Reputation: 4425

define historyArray as char *historyArray[HISTORY_DEPTH]; This defines historyArray as an array of character string pointers. Then historyArray[0] points to teststring as a result of the assignment. As an array of pointers, you can handle each string pointer properly. You can then malloc a buffer pointer to use as an element in the array. and use strcpy to copy into that buffer.

char *historyArray[HISTORY_DEPTH];
// put initialization code here
for (int i = 1; i < HISTORY_DEPTH; i++) {
    historyArray[i-1] = historyArray[i];
}
historyArray[HISTORY_DEPTH-1] = NULL; //empty the last element pointer

This now moves the pointers into the previous element of the array.

Note that the original contents of historyArray[0] are now lost which would cause a memory leak if you had used malloc to create it. As a result, it should have had a free() applied to it. If it was a fixed buffer and does not need to be freed then you would not have to worry about it.

char historyArray[HISTORY_DEPTH][MAX_SIZE];
for (int i = 1; i < HISTORY_DEPTH; i++) {
    // Or use the memset with strlen(size+1)
    // to ensure that the ending '\0' is also copied
    strcpy(historyArray[i-1], historyArray[i]);
}
historyArray[HISTORY_DEPTH-1][0] = '\0'; // make the last an empty string

The strcpy of the second, will copy the contents of each string pointed to by historyArray into the buffer pointed to by the previous element without moving the pointers themselves. This assumes that each buffer is large enough to hold the character string. The last pointer continues to also hold the same data as it did before unless you put in an empty string.

Upvotes: 2

Bran
Bran

Reputation: 647

Are you saying that if you have a string like

aaa, bbb, ccc

You want

aaa, ccc, ccc

as the result? Because your index starts at 1, which I suspect is not your intention. If it is the case, this can get you bbb, ccc, ccc using this

for (int i = 0; i < HISTORY_DEPTH-1; i++) {
    strcpy(historyArray[i], historyArray[i+1]);
}

Upvotes: 0

Related Questions