2

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.

0

4 Answers 4

3

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';
Sign up to request clarification or add additional context in comments.

5 Comments

can i get this with strlen(second)?
@Omer - you can get the size of second with strlen -- but you'll need a different method to get the size of the buffer pointed to by process_name. Typically either you're creating the buffer or being given the buffer; in the former case you know the size, and in the latter you can demand both the address and the size.
@BigMike - you caught me while I was still editing. But it's a good point -- I always just add it at the end of the buffer, which is harmless if strncpy wrote it, and necessary otherwise. :)
@AndyThomas-Cramer: don't worry, I think that every seasoned C programmer adds the '\0' automatically without even thinking about it, so it was just for completeness of information (hope to have said it properly) :D. +1 for the '\0' in the sample. Regards.
I solve my result like this, process_name = strdup(second); this works... =)
2

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.

Comments

1

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

2 Comments

AFAIK strncpy() will erase the original buffer. If he wants to ADD (append) a string, he should use strcat().
I was assumming poster wants to add from a position onwards.
0

I resolve this problem with strdup() function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.