开发者

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 seco开发者_如何学Cnd. It contains several chars.

I want to copy second to process_name.


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


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.


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


I resolve this problem with strdup() function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜