-1

How can I pass an array of character pointers by reference? I tried passing with &tokens and de-referencing in func() but it still won't work.

Here's my code:

#include <stdio.h>

void func(char* tokens[10])
{
    char word[10] = "Hello\0";
    tokens[0] = word;
}

int main()
{
    char* tokens[10];

    func(tokens);
    printf("%s", tokens[0]);

    return 0;
}

Result:

He����
Azeem
  • 11,148
  • 4
  • 27
  • 40
Wizard
  • 1,533
  • 4
  • 19
  • 32

1 Answers1

0

You need to dynamically allocate the memory using malloc() to return and later de-allocate it using free(). Returning a local variable from a function wouldn't be right because that memory is on stack and won't be available when the function completes its execution.

Here's your working code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void func(char* tokens[10])
{
    char* word = malloc( 10 );
    strcpy( word, "Hello!" );
    tokens[0] = word;
}

int main() 
{
    char* tokens[10];

    func(tokens);
    printf("%s", tokens[0]);

    free( tokens[0] );

    return 0;
}

Output:

Hello!

Here's the live example: https://ideone.com/LbN2NX

Azeem
  • 11,148
  • 4
  • 27
  • 40
  • That's a side-problem, but not what OP asks about. OPs code contains more problems which are explained in every C textbook. Re your code: don't cast `void *` to pointers. There is no need and every unnecessary cast is one more place the compiler can't warn you about a problem. (oh, and there is no need to dynamically allocate the array at all). – too honest for this site Aug 25 '18 at 14:01
  • @toohonestforthissite : Thanks for pointing out. I'll update my answer. What do you mean by there's no need to dynamically allocate the array? – Azeem Aug 25 '18 at 16:43
  • I mean exactly what I wrote. What is unclear about this sentence? – too honest for this site Aug 25 '18 at 17:44