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
1

1 Answer 1

3

Simply index on *secret:

(*secret)[i]

or use a char* help variable:

char* s = *secret; ...
Sign up to request clarification or add additional context in comments.

4 Comments

Could you explain how it works ? I really thought *secret[i] was it.
@Jean-BaptisteBouhier * has lower precedence than []. Also consider only assigning your string literals to char const*, and cranking up your compiler warnings.
@Quentin like gcc -Wall -Wextra -Werror file.c ? Which flags would you suggest ?
@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.

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.