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.
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.
Related
I have two variables as stated below. How do I copy the contents of "varOrig" to "varDest" (no loops for ou while)?
const char* varDest = "";
char varOrig[34] = "12345";
If you want to copy the address of the array to the pointer, do this:
varDest = varOrig;
Otherwise, you will need to allocate memory and copy the string.
strdup is useful for this:
varDest = strdup(varOrig);
You need to free varDest after using this.
memcpy is the fastest library routine for memory-to-memory copy. It is usually more efficient than strcpy, which must scan the data it copies or memmove, which must take precautions to handle overlapping inputs.
// Defined in header <string.h>
void* memcpy( void *dest, const void *src, size_t count );
This code.
#include<string.h>
#include<stdlib.h>
...
char varOrig[34] = "12345";
// calculate length of the original string
int length = strlen(varOrig);
// allocate heap memory, length + 1 includes null terminate character
char* varDest = (char*)malloc((length+1) * sizeof(char));
// memcpy, perform copy, length + 1 includes null terminate character
memcpy(varDest, varOrig, length+1);
I know this code is sloppy, I'm trying to relearn string manipulation in C. If I have a string ABBCCCD and I want to store the separate letters in a struct, is there an efficient way to do so? I have some code down below to demonstrate the long way of what I'm trying to do. (Also, do I have to manually add the null-terminator when I'm doing a strncpy?)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct dst_struct {
char a[2];
char b[3];
char c[4];
char d[2];
} dst_struct_t;
int main(void) {
char* test = "ABBCCCD";
char* src = malloc(strlen(test)+1);
strncpy(src, test, strlen(test)+1);
printf("%s\n", src);
dst_struct_t dst;
strncpy(dst.a, src, 1);
strncpy(dst.b, src+1, 2);
strncpy(dst.c, src+3, 3);
strncpy(dst.d, src+6, 1);
printf("dst.a: %s\n", dst.a);
printf("dst.b: %s\n", dst.b);
printf("dst.c: %s\n", dst.c);
printf("dst.d: %s\n", dst.d);
free(src);
}
There isn't really any better way to do this, except that you don't need to copy test to src first.
You also need to add the null terminators to all the strings. It would probably be best to write a function that does both steps: strncpy() and adding the null terminator.
function copy_n(char *dest, char *src, size_t offset, size_t len) {
strncpy(src+offset, dest, len);
dest[len] = '\0';
}
int main(void) {
char* test = "ABBCCCD";
copy_n(dst.a, test, 0, 1);
copy_n(dst.b, test, 1, 2);
copy_n(dst.c, test, 3, 3);
copy_n(dst.d, test, 6, 1);
printf("dst.a: %s\n", dst.a);
printf("dst.b: %s\n", dst.b);
printf("dst.c: %s\n", dst.c);
printf("dst.d: %s\n", dst.d);
}
From the strcpy/strncpy man page:
char *strcpy(char *dest, const char *src);
char *strncpy(char *dest, const char *src, size_t n);
The strcpy() function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy. Beware of buffer overruns! (See BUGS.)
The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated.
The n argument of strncpy is generally meant to be the length of the destination buffer, as the point of the function is to be like strcpy but prevent overflowing the destination buffer if the source string is too long or not NULL-terminated. If used in that manner, your destination string will be NULL-terminated if the source string fits that length, otherwise the final byte of the buffer will contain the nth character of the source string.
However, the way you seem to be using strncpy is to set the exact number of characters you want to copy from the source buffer to place in the destination buffer. That is not really the intended purpose of strncpy. Instead, what you'd want to use is memcpy, since you are really not concerned with the zero-termination of the source string, but rather just copying a set number of characters from a set location. And yes, you will have to manually add the null-terminator if you use memcpy.
I can't seem to get my head around this, what is the basic difference between these two functions:
char *strncpy(char *str1, const char *str2, size_t count);
and
size_t strxfrm(char *str1, const char *str2, size_t count);
To me it seems they both copy count characters from str2 to str1. What I really want to know is, when should I use either of them?
The difference is in the return value:
The strcpy() and strncpy() functions return a pointer to the destination string.
Upon successful completion, strxfrm() shall return the length of the transformed string (not including the terminating null byte). If the value returned is n or more, the contents of the array pointed to by s1 are unspecified.
The following code doesnt copy the contents of matches 2 to keys[0].
Why is that so?
char **keys;
char matches[2000];
char *matches2;
matches2 =strtok(matches," ");
strncpy(keys[0],matches2, sizeof keys[0]);
You forgot to allocate space for keys to point to, as well as space for keys[#] to point to.
Also, are you really sure you want to use strncpy? It does not guarantee 0-termination, instead copying at most n byte of the ggiven string and 0-filling the rest of the buffer.
The size for a string is the number of elements including 0-terminator: strlen(s)+1
For creating a copy of a string, you might look into non-standard strdup, a possible implementation:
char* strdup(const char* s) {
size_t n = strlen(s)+1;
char* r = malloc(n);
if(r)
memcpy(r, s, n);
return r;
}
Try this assuming that you already have allocated space for keys[0]
strncpy(keys[0], matches2, /*your desired size*/);
or
strcpy(keys[0], matches2);
Can u Give solution for this code of typecasting, LPCTSTR(here lpsubkey) to Char*
for below code snippet ,
char* s="HKEY_CURRENT_USER\\";
strcat(s,(char*)lpSubKey);
printf("%S",s);
here it makes error of access violation ,so what will be the solution for that?.
...thanks in advance
There are several issues with your code that might well lead to the access violation. I don't think any have anything to do with the cast you mentioned.
You are assigning a pointer to the first element of a fixed size char array to a char * and then attempt to append to this using strcat. This is wrong as there is no additional space left in the implicitly allocated string array. You will need to allocate a buffer big enough to hold the resulting string and then copy the string constant in there before calling strcat. For example, like so:
char *s = (char*)malloc(1024 * sizeof(char));
strcpy(s, "HKEY_CURRENT_USER\\");
strcat(s, T2A(lpSubKey));
printf("%s", s);
free(s);
Please note that the fixed size array I'm allocating above is bad practise. In production code you should always determine the correct size of the array on the go to prevent buffer overflows or use functions like strncat and strncpy to ensure that you are not copying more data into the buffer than the buffer can hold.
These are not the same thing. What are you trying to do?
The problem is you are trying to append to a string that you have not reserved memory for.
Try:
char s[1024] = "HKEY_CURRENT_USER";
strcat(s,(char*)lpSubKey );
printf("%S",s);
Do be careful with the arbitrary size of 1024. If you expect your keys to be much longer your program will crash.
Also, look at strcat_s.
ATL and MFC has set of macros to such conversion, where used next letters:
W - wide unicode string
T - generic character string
A - ANSI character string
OLE - BSTR string,
so in your case you need T2A macros
strcat does not attempt to make room for the combination. You are overwriting memory that isn't part of the string. Off the top of my head:
char *strcat_with_alloc(char *s1, char *s2)
{
if (!s1 || !s2) return NULL;
size_t len1 = strlen(s1);
size_t len2 = strlen(s2);
char *dest = (char *)malloc(len1 + len2 + 1);
if (!dest) return NULL;
strcpy(dest, s1);
strcat(dest, s2);
return dest;
}
now try:
char* s="HKEY_CURRENT_USER\\";
char *fullKey = strcat_with_alloc(s,(char*)lpSubKey);
if (!fullKey)
printf("error no memory");
else {
printf("%S",fullKey);
free(fullKey);
}