0
char*** get_func(int size, char** arr) {
    int i, num;
    char*** ans = (char***)malloc(size*sizeof(char**));
    for(i = 0; i < size; i++) {
        scanf("%d", &num);
        *(ans + i) = arr + (num - 1);
    }
    return ans;
}

What I want to achieve of this function is, for example, the arr = ["a", "b", "c"] and size = 2, then scanf get the index of the element in arr, num = 1 and 3, the returned ans should be ["a", "c"]. But I dont know where the bug is in my code, it just return the ["a", "b"].

1 Answers1

4

Using your notation, you are returning

[
   arr + 0,
   arr + 2
]

which is more or less

[
   [ "a", "b", "c" ],
   [ "c" ]
]

But you said you wanted

[
   "a",
   "c"
]

which is

[
   *( arr + 0 ),  // aka arr[ 0 ] aka arr[ 1 - 1 ]
   *( arr + 2 )   // aka arr[ 2 ] aka arr[ 3 - 1 ]
]

Start by fixing the return type, then replace

*(ans + i) = arr + (num - 1);

with

*(ans + i) = *(arr + (num - 1));

Fixed:

char** get_func( size_t n, char** arr ) {
   char** ans = malloc( n * sizeof( char* ) );
   // Error handling missing.

   for ( size_t i=0; i<n; ++i ) {
      size_t j;
      scanf( "%zu", &j );
      // Error handling missing.

      ans[ i ] = arr[ j - 1 ];
   }
 
   return ans;
}

I also switched to the more appropriate size_t, and used what I think are more conventional names. But that's not relevant to the question.

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • but the requirement is we need to return a char*** value and also use pointer arithmetic – Patrick Wong Sep 22 '22 at 16:50
  • 1
    Re "*but the requirement is we need to return a char*** value*", So what output do you want? You said you wanted `["a", "c"]`, which you previously established is a `char**` when you said `["a", "b", "c"]` is a `char**` /// Re "*also use pointer arithmetic*", I didn't remove any pointer arithmetic. `x[y]` IS pointer arithmetic. [It's 100% the same](https://stackoverflow.com/q/381542/589924) as `*(x+y)`. It's just easier to read. Feel free to use the hard to read version if you want. – ikegami Sep 22 '22 at 16:59
  • Thanks for your explanation. For fixing my words, as the requirements said, we can't return a char** which creates a new array, we are expected to point to high level indices in arr. – Patrick Wong Sep 22 '22 at 17:23
  • Again, if you want something other than what you specified in your question, you'll need to tell us what that is (by fixing your question). Feel free to leave a comment on my answer when you do. – ikegami Sep 22 '22 at 20:02