1

I need help with initializing a pointer to char array inside another function.

I'm passing a char array and pointer to char array to a function. I would like to copy characters from variable 'word' to 'secret' by address/reference/pointer.

I was able to do it by passing values to a function like this:

char    *set_secret(char *word, char *secret)
{
    int     i;

    for (i = 0; word[i] != '\0'; i++)
    {
        if (word[i] == ' ')
            secret[i] = ' ';
        else
            secret[i] = SECRET_SYMBOL;
    }
    secret[i] = '\0';

    return(secret);
}

How can I do to copy characters into the pointer of char array by reference ?


Here's what I have (have checked malloc, it's all good):

SOURCE:

void    init_secret(const char *word, char **secret)
{
    int     i;
    *secret = NULL;
    *secret = (char*)malloc( sizeof(char) * strlen(word) + 1 );

    // trying changing secret value by reference and not by value (copy)
    for (i = 0; word[i] != '\0'; i++)
    {
        if (word[i] == ' ')
            *secret[i] = ' ';
        else
            *secret[i] = '_';
    }
    *secret[i] = '\0';
}

int     main(void)
{
    char    *str = "TALK TO THE HAND";
    char    *secret = NULL;

    init_secret(str, &secret);
    printf("Secret word: %s\n", secret);

    return(0);
}

OUTPUT:

Bus error: 10
Jay
  • 179
  • 1
  • 5
  • 18
  • 1
    [Please don't cast the result of `malloc()`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858). – Quentin Feb 08 '15 at 00:42

1 Answers1

3

Simply index on *secret:

(*secret)[i]

or use a char* help variable:

char* s = *secret; ...
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Could you explain how it works ? I really thought *secret[i] was it. – Jay Feb 08 '15 at 00:48
  • 1
    @Jean-BaptisteBouhier `*` has lower precedence than `[]`. Also consider only assigning your string literals to `char const*`, and cranking up your compiler warnings. – Quentin Feb 08 '15 at 00:49
  • @Quentin like gcc -Wall -Wextra -Werror file.c ? Which flags would you suggest ? – Jay Feb 08 '15 at 01:00
  • 1
    @Jean-BaptisteBouhier `-Wwrite-strings` to be specific, or `-std=*` with one of the standards. Albeit I'm genuinely surprised that the default (gnu89 I believe) does not raise the warning. – Quentin Feb 08 '15 at 01:04