Reputation: 179
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
Upvotes: 1
Views: 1840
Reputation: 109547
Simply index on *secret
:
(*secret)[i]
or use a char* help variable:
char* s = *secret; ...
Upvotes: 3