How to copy a char pointer into a char array?

15,881

Solution 1

Use strncpy:

strncpy(stringArray, temporaryVariable->arrayOfElements, sizeof(stringArray));
stringArray[sizeof(stringArray) - 1] = '\0';

Solution 2

this code is also ok.

snprintf(stringArray,MAXIMUM_LINE_LENGTH + 1,"%s",temporaryVariable->arrayOfElements);
Share:
15,881

Related videos on Youtube

letter Q
Author by

letter Q

Updated on July 12, 2022

Comments

  • letter Q
    letter Q almost 2 years

    So I have a pointer to a char array:

    temporaryVariable->arrayOfElements; // arrayOfElements is char*
    

    I would like to copy into my char array declared with square brackets:

    char stringArray[MAXIMUM_LINE_LENGTH + 1];
    

    How can I do this?

  • Keith Nicholas
    Keith Nicholas over 10 years
    I'd also note he could check before hand to see if it would fit if truncating the string is not suitable