How can I add '.' to the char Array := "Hello World" in C, so I get a char Array: "Hello World." The Question seems simple but I'm struggling.
Tried the following:
char str[1024]; char tmp = '.'; strcat(str, tmp);
But it does not work. It shows me the error: "passing argument 2 of ‘strcat’ makes pointer from integer without a cast" I know that in C a char can be cast as int aswell. Do I have to convert the tmp to an char array aswell or is there a better solution?
Given an integer number N, the task is to convert it into a character array. Approach: The basic approach to do this, is to recursively find all the digits of N, and insert it into the required character array. Count total digits in the number. Declare a char array of size digits in the number.
Yes we can store integer value in a char type variable in C.
You can add the ASCII value of 0 to the value you want to store digit into the character array. For example if you want to store 0,1,...,9 into the character array A[10], you may use the following code. This works only if the integer you want to store is less than 10.
strcat
has the declaration:
char *strcat(char *dest, const char *src)
It expects 2 strings. While this compiles:
char str[1024] = "Hello World"; char tmp = '.'; strcat(str, tmp);
It will cause bad memory issues because strcat
is looking for a null terminated cstring. You can do this:
char str[1024] = "Hello World"; char tmp[2] = "."; strcat(str, tmp);
Live example.
If you really want to append a char you will need to make your own function. Something like this:
void append(char* s, char c) { int len = strlen(s); s[len] = c; s[len+1] = '\0'; } append(str, tmp)
Of course you may also want to check your string size etc to make it memory safe.
The error is due the fact that you are passing a wrong to strcat()
. Look at strcat()
's prototype:
char *strcat(char *dest, const char *src);
But you pass char
as the second argument, which is obviously wrong.
Use snprintf()
instead.
char str[1024] = "Hello World"; char tmp = '.'; size_t len = strlen(str); snprintf(str + len, sizeof str - len, "%c", tmp);
As commented by OP:
That was just a example with Hello World to describe the Problem. It must be empty as first in my real program. Program will fill it later. The problem just contains to add a char/int to an char Array
In that case, snprintf()
can handle it easily to "append" integer types to a char buffer too. The advantage of snprintf()
is that it's more flexible to concatenate various types of data into a char buffer.
For example to concatenate a string, char and an int:
char str[1024]; ch tmp = '.'; int i = 5; // Fill str here snprintf(str + len, sizeof str - len, "%c%d", str, tmp, i);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With