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"].

2
  • 4
    Tip: *(ans + i) is just a long way of writing ans[i] Commented Sep 22, 2022 at 16:39
  • 1
    It looks like you are trying to copy the selected pointers from arr to ans. Is that correct? If so, ans should be a char** too. Commented Sep 22, 2022 at 16:48

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

but the requirement is we need to return a char*** value and also use pointer arithmetic
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 as *(x+y). It's just easier to read. Feel free to use the hard to read version if you want.
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.