Assigning pointers

Something we could run would be nice.

What is Dictionary(*beg, *end) doing?
And you can't compare C-style strings with <. You need to use std::strcmp(t, *k) < 0 (and include <cstring>)

I'm not entirely sure of your setup, but you seem to want to move pointers around so I'm assuming you are passing in an array of pointers to c-strings. (I.e., you don't want to copy strings around.) So maybe something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cstring>

void sort(const char** beg, const char** end) {
  for (const char **i = beg; i != end; ++i) {
    const char *t = *i, **j = i;
    for (const char **k = i - 1; j != beg && std::strcmp(t, *k) < 0; --j, --k)
      *j = *k;
    *j = t;
  }
}

int main() {
    const char *words[] = {
        "one", "two", "three", "four", "five",
        "six", "seven", "eight", "nine", "ten"
    };
    int size = sizeof words / sizeof words[0];
    sort(words, words + size);
    for (int i = 0; i < size; ++i)
        std::cout << words[i] << '\n';
}
Last edited on
No, you didn't set your pointers correctly. See my example.

If you are using your own comparison function then you need to use it instead of <. Using it to compare *beg and *end makes no sense. end doesn't even point to a string. It points one past the end of the array.

In the integer code you are basing this off of, the first line is just checking if the input array is of a size less than 2, in which case there is nothing to sort. It's not comparing the integers themselves. If you want to do the same thing in your code, you would use exactly the same code:

 
if (end - beg < 2) return;

Last edited on
@jtruth914

Please DON'T delete your question after getting an answer. It makes this thread useless to others as a learning resource. It's a selfish abuse of this forum.
Topic archived. No new replies allowed.