Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a char pointer into a char array? [duplicate]

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?

like image 544
Wang-Zhao-Liu Q Avatar asked Nov 28 '13 22:11

Wang-Zhao-Liu Q


People also ask

How do I copy a char pointer?

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 .

How do I copy a character array to another char array?

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];

How do you copy a character array to a pointer?

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.

How do I copy a string to a char pointer?

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.


2 Answers

Use strncpy:

strncpy(stringArray, temporaryVariable->arrayOfElements, sizeof(stringArray));
stringArray[sizeof(stringArray) - 1] = '\0';
like image 198
user4815162342 Avatar answered Sep 28 '22 08:09

user4815162342


this code is also ok.

snprintf(stringArray,MAXIMUM_LINE_LENGTH + 1,"%s",temporaryVariable->arrayOfElements);
like image 27
freedoo Avatar answered Sep 28 '22 07:09

freedoo