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?
Syntax: char* strcpy (char* destination, const char* source); The strcpy() function is used to copy strings. It copies string pointed to by source into the destination . This function accepts two arguments of type pointer to char or array of characters and returns a pointer to the first string i.e destination .
The simplest way to copy a character array to another character array is to use memcpy. If you want to copy all elements of array src of size m to array dst of size n, you can use the following code. char src[m]; char dst[n];
char * a = "test"; These are both ok, and load the address of the string in ROM into the pointer variable. char a [] = "test"; This will create a 5 byte char array in RAM, and copy the string (including its terminating NULL) into the array.
Using the inbuilt function strcpy() from string. h header file to copy one string to the other. strcpy() accepts a pointer to the destination array and source array as a parameter and after copying it returns a pointer to the destination string.
Use strncpy
:
strncpy(stringArray, temporaryVariable->arrayOfElements, sizeof(stringArray));
stringArray[sizeof(stringArray) - 1] = '\0';
snprintf(stringArray,MAXIMUM_LINE_LENGTH + 1,"%s",temporaryVariable->arrayOfElements);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With