-2

I want to swap two rows of string array in C.

e.g:

first row , second row

after swap: second row, first row

How should this function looks like, swap_rows() func doesnt work. Should I use strcpy() function somehow?

What I did:


#define N 100

static char **str_tab;

void tab_alloc(const int M) { str_tab = (char **)malloc((M * sizeof(char *))); for (int i = 0; i < M; i++) str_tab[i] = (char *)malloc(N * sizeof(char)); } void tab_fill() { size_t M = _msize(str_tab) / sizeof(char *); for (int i = 0; i < M; i++) gets_s(str_tab[i], N); } void swap_rows() { int row1, row2; puts("Which rows u want swap?"); puts("put 1:"); scanf_s("%d", &row1); puts("put 2:"); scanf_s("%d", &row2); char *temp = str_tab[row1]; strcpy(str_tab[row1], str_tab[row2]); // str_tab[row1] = str_tab[row2]; strcpy(str_tab[row2], temp); // str_tab[row2] = temp; }

UnknownP
  • 5
  • 2

1 Answers1

1

You can simply swap the pointers.

void swap_rows(char **array, int row1, int row2) {
    char *temp = array[row1];
    array[row1] = array[row2];
    array[row2] = temp;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612