Having Trouble about pointer to a string array in C

Viewed 49
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 Answers

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.

Related