简体   繁体   中英

Reverse items in an array of strings in C

I need help on my code. I have done a code (below) to read the numbers from a .txt file. The first two numbers are to be put on a int variable, the numbers from the second line onwards are to be put on an array of strings. But now, i want to reverse the array of strings and put in a new array of strings. I've been having a problem trying to solve this but i'm not being able to.

Ex. File:

 3 8
 10000001
 11101001
 00100101
 11000010

i need: listOfNumbersReversed = {"11000010","00100101","11101001","10000001"}

Code:

int main() {
FILE *file = fopen("file.txt", "r");
if (file == NULL) {
    fprintf(stderr, "Cannot open file.txt: %s\n", strerror(errno));
    return 1;
}
// read the 2 numbers
int primNum, secNum;
if (fscanf(file, "%d %d\n", &primNum, &secNum) != 2) {
    fprintf(stderr, "invalid file format\n");
    fclose(file);
    return 1;
}
// count the number of items that can be read
char line[100];
int counter;
for (counter = 0; fscanf(file, "%99s", line) == 1; counter++)
     continue;

printf("Total number of items: %d\n", counter);

// Rewind and re-read the contents into the array
rewind(file);
char listOfNumbers[counter][100];
int i;
if (fscanf(file, "%d %d\n", &primNum, &secNum) != 2) {
    fprintf(stderr, "cannot reread the numbers\n");
    fclose(file);
    return 1;
}
for (i = 0; i < counter; i++) {
    if (fscanf(file, "%99s", listOfNumbers[i]) != 1) {
        // Cannot read all the numbers file changed ?
        printf("could only read %d numbers out of %d\n", i, counter);
        counter = i;
        break;
    }
}

// Testing Results
printf("1st Number: %d\n", primNum);
printf("2nd Number: %d\n\n", secNum);
printf("List of Numbers on Array:\n");
for (i = 0; i < counter; i++) {
    printf("%s\n", listOfNumbers[i]);
}
fclose(file);

//Reversing the array of strings
char listOfNumbersReversed[counter][secNum];
for(i = counter - 1; i>=0; i--){
    int j = 0;
    memcpy(&listOfNumbersReversed[j], &listOfNumbers[i], secNum);
    j++;
}

//Testing Results
printf("\n\nList of Numbers Reversed on Array:\n");
for (i = 0; i < counter; i++) {
    printf("%s\n", listOfNumbersReversed[i]);
}

return 0;
}

Ps: the secNum variable is the size of the itens in the array

You are really close but here are a few things.

  1. move the j variable outside the loop so it isn't reset to zero every time through the loop.
  2. add space in the array to store the '\0' string termination.
  3. add 1 to the number of characters to copy
    char listOfNumbersReversed[counter][secNum+1];
    int j = 0;
    for (i = counter - 1; i >= 0; i--)
    {
      memcpy (&listOfNumbersReversed[j][0], &listOfNumbers[i][0], secNum+1);
      j++;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM