The array animals is an array of pointers. It is not an array of buffers of some size. Therefor, if you do
sizeof(*animals)
You will get the sizeof of the first element of that array. Equivalent to
sizeof(char*)
Because your array stores pointers. So, in the line that reads
char *output[sizeof(*animals)];
You allocate 4 or 8 pointers in one array (depends on how wide a pointer on your platform is. Usually it's either 4 or 8). But that's of course not senseful! What you wanted to do is create an array of pointers of the same size as animals. You will have to first get the total size of the animals array, and then divide by the size of one element
char *output[sizeof(animals)/sizeof(*animals)];
Now, that is what you want. But the pointers will yet have indeterminate values... Next you pass the array using *&animals (same for the other). Why that? You can pass animals directly. Taking its address and then dereference is the same as doing nothing in the first place.
Then in the function you call, you copy the strings pointed to by elements in animal to some indeterminate destination (remember the elements of the output array - the pointers - have yet indeterminate values. We have not assigned them yet!). You first have to allocate the right amount of memory and make the elements point to that.
while(*animals) {
// now after this line, the pointer points to something sensible
*output = malloc(sizeof("new animal ") + strlen(*animals));
sprintf(*output, "new animal %s", *animals);
output++; // no need to dereference the result
animals++; // don't forget to increment animals too!
}
Addition, about the sizeof above
There's one important thing you have to be sure about. It's the way we calculate the size. Whatever you do, make sure you always have enough room for your string! A C string consists of characters and a terminating null character, which marks the end of the string. So, *output should point to a buffer that is at least as large so that it contains space for "new animal " and *animals. The first contains 11 characters. The second depends on what we actually copy over - its length is what strlen returns. So, in total we need
12 + strlen(*animals)
space for all characters including the terminating null. Now it's not good style to hardcode that number into your code. The prefix could change and you could forget to update the number or miscount about one or two characters. That is why we use sizeof, which we provide with the string literal we want to have prepended. Recall that a sizeof expression evaluates to the size of its operand. You use it in main to get the total size of your array before. Now you use it for the string literal. All string literals are arrays of characters. string literals consist of the characters you type in addition to the null character. So, the following condition holds, because strlen counts the length of a C string, and does not include the terminating null character to its length
// "abc" would have the type char[4] (array of 4 characters)
sizeof "..." == strlen("...") + 1
We don't have to divide by the size of one element, because the sizeof char is one anyway, so it won't make a difference. Why do we use sizeof instead of strlen? Because it already accounts for the terminating null character, and it evaluates at compile time. The compiler can literally substitute the size that the sizeof expression returns.
The array animals is an array of pointers. It is not an array of buffers of some size. Therefor, if you do
sizeof(*animals)
You will get the sizeof of the first element of that array. Equivalent to
sizeof(char*)
Because your array stores pointers. So, in the line that reads
char *output[sizeof(*animals)];
You allocate 4 or 8 pointers in one array (depends on how wide a pointer on your platform is. Usually it's either 4 or 8). But that's of course not senseful! What you wanted to do is create an array of pointers of the same size as animals. You will have to first get the total size of the animals array, and then divide by the size of one element
char *output[sizeof(animals)/sizeof(*animals)];
Now, that is what you want. But the pointers will yet have indeterminate values... Next you pass the array using *&animals (same for the other). Why that? You can pass animals directly. Taking its address and then dereference is the same as doing nothing in the first place.
Then in the function you call, you copy the strings pointed to by elements in animal to some indeterminate destination (remember the elements of the output array - the pointers - have yet indeterminate values. We have not assigned them yet!). You first have to allocate the right amount of memory and make the elements point to that.
while(*animals) {
// now after this line, the pointer points to something sensible
*output = malloc(sizeof("new animal ") + strlen(*animals));
sprintf(*output, "new animal %s", *animals);
output++; // no need to dereference the result
animals++; // don't forget to increment animals too!
}
Addition, about the sizeof above
There's one important thing you have to be sure about. It's the way we calculate the size. Whatever you do, make sure you always have enough room for your string! A C string consists of characters and a terminating null character, which marks the end of the string. So, *output should point to a buffer that is at least as large so that it contains space for "new animal " and *animals. The first contains 11 characters. The second depends on what we actually copy over - its length is what strlen returns. So, in total we need
12 + strlen(*animals)
space for all characters including the terminating null. Now it's not good style to hardcode that number into your code. The prefix could change and you could forget to update the number or miscount about one or two characters. That is why we use sizeof, which we provide with the string literal we want to have prepended. Recall that a sizeof expression evaluates to the size of its operand. You use it in main to get the total size of your array before. Now you use it for the string literal. All string literals are arrays of characters. string literals consist of the characters you type in addition to the null character. So, the following condition holds, because strlen counts the length of a C string, and does not include the terminating null character to its length
// "abc" would have the type char[4] (array of 4 characters)
sizeof "..." == strlen("...") + 1
We don't have to divide by the size of one element, because the sizeof char is one anyway, so it won't make a difference. Why do we use sizeof instead of strlen? Because it already accounts for the terminating null character, and it evaluates at compile time. The compiler can literally substitute the size that the sizeof expression returns.
You haven't allocated any space in your output array to put the copy into. You'll need to use malloc to allocate some space before using sprintf to copy into that buffer.
void p_init(const char **animals, char **output)
{
while(*animals)
{
size_t stringSize = 42; /* Use strlen etc to calculate the size you need, and don't for get space for the NULL! */
*output = (char *)malloc(stringSize);
sprintf(*output, "new animal %s", *animals);
output++;
animals++;
}
}
Don't forget to call free() on that allocated memory when you are done with it.
I just fell foul of the fact that strncpy does not add an old terminator if the destination buffer is shorter than the source string. Is there a single function standard library replacement that I could drop in to the various places strncpy is used that would copy a null terminated string up to the length of the destination buffer, guaranteeing early (but correct) termination of the destination string, if the destination buffer is too short?
Edit:
-
Yes, I do need C-null terminated strings. This C API is called by something else that provides a buffer for me to copy into, with the expectation that it’s null terminated
Edit 2:
-
I know I can write a helper function that’s shared across relevant parts of the code, but I don’t want to do that because then each of those modules that need the function becomes coupled to a shared helper header file, which is fine in isolation but “oh I want to use this code in another project, better make sure I take all the misc dependencies” is best avoided. Necessary if necessary, but if possible using a standard function, even better.
Copying string literals in C into an character array - Stack Overflow
C - copy buffer to string - is it even possible? - Stack Overflow
loops - Copying characters from a source string to a buffer - C - Stack Overflow
printf - Copy a section of a string into buffer in C - Stack Overflow
Use strcpy(), strncpy(), strlcpy() or memcpy(), according to your specific needs.
With the following variables:
const char *tmp = "xxxx";
char buffer[50];
You typically need to ensure your string will be null terminated after copying:
memset(buffer, 0, sizeof buffer);
strncpy(buffer, tmp, sizeof buffer - 1);
An alternative approach:
strncpy(buffer, tmp, sizeof buffer);
buffer[sizeof buffer - 1] = '\0';
Some systems also provide strlcpy() which handles the NUL byte correctly:
strlcpy(buffer, tmp, sizeof buffer);
You could naively implement strlcpy() yourself as follows:
size_t strlcpy(char *dest, const char *src, size_t n)
{
size_t len = strlen(src);
if (len < n)
memcpy(dest, src, len + 1);
else {
memcpy(dest, src, n - 1);
dest[n - 1] = '\0';
}
return len;
}
The above code also serves as an example for memcpy().
Finally, when you already know that the string will fit:
strcpy(buffer, tmp);
Use strcpy, it is pretty much well documented and easy to find:
const char* tmp = "xxxx";
// ...
char array[50];
// ...
strcpy(array, tmp);
But of course, you must make sure that the length of the string that you are copying is smaller than the size of the array. An alternative then is to use strncpy, which gives you an upper limit of the bytes being copied. Here's another example:
const char* tmp = "xxxx";
char array[50];
// ...
array[49] = '\0';
strncpy(array, tmp, 49); // copy a maximum of 49 characters
If the string is greater than 49, the array will still have a well-formed string, because it is null-terminated. Of course, it will only have the first 49 characters of the array.
First, a C string is not just a char, but an array of char with the last element (or at least the last one that's counted as part of the string) set to the null character (numerically 0, also '\0' as a character constant).
Next, in the code you posted you probably meant char buffer[50] rather than char *buffer[50]... the version you have is an array of 50 char *s, but you need an array of 50 chars. After that's corrected, then...
Since fgets() always fills in a null char at the end of the string it read, buffer would already be a valid C string after you call fgets(). If you'd like to copy it to another string so you can reuse the buffer to read more input, you can use the usual string handling functions from <string.h>, such as strcpy(). Just make sure the string you copy it into is large enough to hold all the used characters plus a terminating null character.
This code copies the string into a newly malloc()ed string (error checking omitted):
char buffer[50];
char *str;
fgets(buffer,50,stdin);
str = malloc(strlen(buffer) + 1);
strcpy(str,buffer);
This code does the same, but copies to a char array on the stack (not malloc()ed):
char buffer[50];
char str[50];
fgets(buffer,50,stdin);
strcpy(str,buffer);
strlen() will tell you how many characters are used in the string, but doesn't count the terminating null (so you need to have one more character allocated than what strlen() returns). strcpy() will copy the characters and the null at the end from one string/buffer to another. It stops after the null, and doesn't know how much space you've allocated -- so you need to make sure it will find a null character before running out of space in the destination, or reaching the end of the source buffer. If in doubt, place a null at the end of the buffer yourself to make sure.
It should be char buffer[50]; and yes, you can then use strncpy (which does not care if it got a static or a heap allocated zone).
But I would recommend using getline in your case.
You need to assign to dest inside the function
int tokenCopy(char *dest, const char *src, int destSize) {
*dest = 0;
// rest of the code
}
After getting rid of the first for loop, you can modify the second for loop to something like
for ( i = 0; *src != '\0' && *src!= ' ' && (i < destSize-1) ; i++)
{
*dest++ = *src++;
}
*dest = '\0';
return new_value;
to get what you want. The modification includes
- getting rid of the redundant check on empty string.
- combining the copying of value and the pointer increment
- adding the destination length check as a terminating condition for the loop itself
A C string is a nul-terminated character array.
The C language does not allow assigning the contents of an array to another
array. As noted by Barry, you must copy the individual characters one by one
from the source array to the destination array. e.g. -
#define _CRT_SECURE_NO_WARNINGS
#include
#include
int main()
{
char str1[] = "Hello";
char str2[10] = {0};
for (int x = 0; x < strlen(str1); ++x)
{
str2[x] = str1[x];
}
printf("%s\n", str2);
return 0;
}
To make this common task easier there are standard library functions provided
which will perform this operation. e.g. - memcpy(), etc.
memcpy(str2, str1, 6);
When the array contains a nul-terminated string of characters you can use
strcpy(), etc.
strcpy(str2, str1);
Caveat: Some of the above functions are considered unsafe as they do not guard
against buffer overruns of the source and destination arrays. There are safer
versions provided by the compiler.
Note that if and when you start learning C++ you will find that there you can
assign a C++ std::string object to another object of the same type. However,
even in C++ the same rules apply when working with C strings, "raw" character
arrays, etc.
- Wayne
str2 is an array. It cannot appear on the left side of an assignment. You will need to use something like strcpy.
q is a pointer. It is perfectly legal to copy one pointer to another.
This is exactly what std::string's copy function does.
#include <string>
#include <iostream>
int main()
{
char test[5];
std::string str( "Hello, world" );
str.copy(test, 5);
std::cout.write(test, 5);
std::cout.put('\n');
return 0;
}
If you need null termination you should do something like this:
str.copy(test, 4);
test[4] = '\0';
First of all, strncpy is almost certainly not what you want. strncpy was designed for a fairly specific purpose. It's in the standard library almost exclusively because it already exists, not because it's generally useful.
Probably the simplest way to do what you want is with something like:
sprintf(buffer, "%.4s", your_string.c_str());
Unlike strncpy, this guarantees that the result will be NUL terminated, but does not fill in extra data in the target if the source is shorter than specified (though the latter isn't a major issue when the target length is 5).