简体   繁体   中英

How to print 2D array of strings in reverse order

I'm trying to create a function in C that will swap the indexes of my 2D array by replacing the last row index with the first row index on each iteration until the whole array is completely reversed. For example, the given sample of strings:

I am human
hello world
et is real
i am the knight

should output:

i am the knight
et is real
hello world
I am human

using my swap function. Instead the output I get (last string gets cut off) is this:

Ih am human
eello world
it is real

The function I've whipped up, looks like this:

void swap(char array[][COLS], int start, int end)
{
    for(int i = 0; i >= ROWS; i++)
    {
        int temp = array[start][i];
        array[start][i] = array[end][i];
        array[end][i] = temp;
        end--;
    }
}

I've defined ROWS and COLS to be of size 100. What am I doing wrong and how do I rectify this?

To get the desired output, you do not want to use any sort of assignment. Assignment, as you may already know, refers to setting one piece of memory to be equal to another. In other words, copying. These three lines in your code are all assignment and cause copies to be made:

int temp = array[start][i];
array[start][i] = array[end][i];
array[end][i] = temp;

The following method will require that your string array be defined as follows:

char** array = {
    "I am human",
    "hello world",
    "et is real",
    "i am the knight"
};

Since all you want to do is print the contents in reverse order, you simply need to start at the end row, and work your way back to the beginning row. If this is your printing function

void printStrings(char** array, int start, int end)
{
    while(start!=end)
    {
        printf("%s\n",array[start]);
        ++start;
    }
}

You would call it like this to print the strings in normal order:

printStrings(array,0,3);

Or

printStrings(array,0,sizeof(array)-1);

And to print it in reverse order, you would need a different function:

void printStringsReverse(char** array, int end, int start)
{
    while(end!=start)
    {
        printf("%s\n",array[end]);
        --end;
    }
}

And you would call this function like this:

printStringsReverse(array,3,0);

Or

printStringsReverse(array,sizeof(array)-1,0);

No assignment is needed. No copies are made. No malloc is used. You are simply printing what is already there so there is no need to move anything around. There are, of course, many ways that you could write these functions. In fact there is a way that you could write both functions to just be one function. But this is a simple method that will have very little overhead.

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