c - reversing an array of strings.

My goal is if I have array of strings such as "hello", "world", "dog" calling reverse
should ensure it becomes "dog", "world", "hello".

In reverse, char** is the array of strings and num is just the number of elements

Two functions, reverse calls swap to swap until all elements are reversed. Doesn't seem to be working as intended. One of the issues is I am unsure as to how to make the changes stick like c++ call by reference, which doesn't seem to exist in c.

Any suggestions?

1
2
3
4
5
6
7
8
9
10
11
12
13
  void swap(char* a, char* b){
  char* temp = a;
  a = b;
  b = temp;
}


void reverse_arr(char** arr, int num){
    for(int i=0; i<num/2; i++){
      swap(*(arr+i), *(arr+num-1-i));
    }

}
Last edited on
My c is a little rusty but does this get it for you? A reference is not exactly a pointer, but a pointer can function as a reference. The difference is that a pure reference is the same compiler level token so it does not need to be an entity. A pointer usually must be an entity at compile time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>
  void swap(char **a, char **b)
 {
  char* temp = *a;
  *a = *b;
  *b = temp;
}


void reverse_arr(char** arr, int num)
{
    for(int i=0; i<num/2; i++)
	{
      swap(&(arr[i]), &arr[num-1-i]);
    }
}

int main()
{
  char* cpp[3];
  char h[] = "hello";  
  char w[] = "world";  
  char d[] = "dog";  
  cpp[0] = h;
  cpp[1] = w;
  cpp[2] = d;
  
reverse_arr(cpp,3);
printf("%s %s %s\n", cpp[0],cpp[1],cpp[2]); 
  
}
Last edited on
jonnin - Yes that seems to fix my issue perfectly. I appreciate your assistance! Seems so obvious now that I see it haha, but I spent hours scratching my head.
Last edited on
Topic archived. No new replies allowed.