converting a const char to an array

14,744

Solution 1

#include <string.h>
bool check(const char* word)
{
    char temp[51];
    if(strlen(word)>50)
        return false;
    strncpy(temp,word,51);
    // Do seomething with temp here
    return true;
}

Solution 2

If you want a non-const version, you'll have to copy the string:

char temp[strlen(word) + 1];
strcpy(temp, word);

Or:

char * temp = strdup(word);

if(!temp)
{
    /* copy failed */

    return false;
}

/* use temp */

free(temp);
Share:
14,744
Joshua McDonald
Author by

Joshua McDonald

Updated on June 25, 2022

Comments

  • Joshua McDonald
    Joshua McDonald almost 2 years

    I am trying to convert a const char, to a char... here is my code:

    bool check(const char* word)
    {
    
    char *temp[1][50];
    
    temp = word;
    
    return true;
    }
    

    It is a function with a const char passed in. I need to convert that const char to a char. When I run this code now, the compiler throws up this error:

    dictionary.c:28:6: error: array type 'char *[1][50]' is not assignable
    temp = word;
    

    How do I correctly complete this conversion?

    Thanks, Josh