Ömer Faruk AK
Ömer Faruk AK

Reputation: 2439

Add String to Char Pointer in C

I want to add a string to char pointer, how can i do?

For example:

char pointer is char * process_name; and i have an char array named second. It contains several chars.

I want to copy second to process_name.

Upvotes: 2

Views: 12376

Answers (4)

Ömer Faruk AK
Ömer Faruk AK

Reputation: 2439

I resolve this problem with strdup() function.

Upvotes: 0

lhw
lhw

Reputation: 548

You can use 'strcat' or 'strncat' to concatenate two strings. But your process_name buffer has to be big enough to contain both strings. strcat will handle the \0-bytes for you but i'd still suggest you use strncat with fixed length.

 char *strcat(char *restrict s1, const char *restrict s2);
 char *strncat(char *restrict s1, const char *restrict s2, size_t n);

Example usage would be:

process_name = realloc(process_name, strlen(process_name) + strlen(second));
strncat(process_name, second, strlen(second));

This might not be the best example but it should show the general direction.

Upvotes: 2

Mitch Wheat
Mitch Wheat

Reputation: 300559

Strictly speaking, you cannot 'add a string' to a char pointer.

You can add a string to a buffer pointed to by a char pointer IF there is sufficient allocated space in the buffer (plus one for the terminating '\0') using a standard library call such as strncpy() [depends on your precise requirements, insert versus append etc].

Upvotes: 1

Andy Thomas
Andy Thomas

Reputation: 86411

If you know the size of the buffer to which process_name points, you can use strncpy().

char * strncpy ( char * destination, const char * source, size_t num );

For example:

strncpy( process_name, second, process_name_size );
process_name[ process_name_size - 1 ] = '\0';

Upvotes: 3

Related Questions