You can't directly do array2 = array1, because in this case you manipulate the addresses of the arrays (char *) and not of their inner values (char).
What you, conceptually, want is to do is iterate through all the chars of your source (array1) and copy them to the destination (array2). There are several ways to do this. For example you could write a simple for loop, or use memcpy.
That being said, the recommended way for strings is to use strncpy. It prevents common errors resulting in, for example, buffer overflows (which is especially dangerous if array1 is filled from user input: keyboard, network, etc). Like so:
Copy// Will copy 18 characters from array1 to array2
strncpy(array2, array1, 18);
As @Prof. Falken mentioned in a comment, strncpy can be evil. Make sure your target buffer is big enough to contain the source buffer (including the \0 at the end of the string).
You can't directly do array2 = array1, because in this case you manipulate the addresses of the arrays (char *) and not of their inner values (char).
What you, conceptually, want is to do is iterate through all the chars of your source (array1) and copy them to the destination (array2). There are several ways to do this. For example you could write a simple for loop, or use memcpy.
That being said, the recommended way for strings is to use strncpy. It prevents common errors resulting in, for example, buffer overflows (which is especially dangerous if array1 is filled from user input: keyboard, network, etc). Like so:
Copy// Will copy 18 characters from array1 to array2
strncpy(array2, array1, 18);
As @Prof. Falken mentioned in a comment, strncpy can be evil. Make sure your target buffer is big enough to contain the source buffer (including the \0 at the end of the string).
If your arrays are not string arrays, use:
memcpy(array2, array1, sizeof(array2));
How to copy a string into an array of chars without using any built-in function?
Copying string into char array. - C++ Forum
Copying string literals in C into an character array - Stack Overflow
How to Copy a Char Array into another Ch - C++ Forum
Videos
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.
If I have array of strings like string a = {"Hello", "Bye", "HI"};
I want to copy hello in an array of char such as char copy. So that I can iterate over characters of Hello one by one.
How can I achieve this?
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.
use strncpy() rather than strcpy()
/* code not tested */
#include <string.h>
int main(void) {
char *src = "gkjsdh fkdshfkjsdhfksdjghf ewi7tr weigrfdhf gsdjfsd jfgsdjf gsdjfgwe";
char dst[10]; /* not enough for all of src */
strcpy(dst, src); /* BANG!!! */
strncpy(dst, src, sizeof dst - 1); /* OK ... but `dst` needs to be NUL terminated */
dst[9] = '\0';
return 0;
}
use strncpy to be sure to not copy more charachters than the char[] can contains
char *s = "abcdef";
char c[6];
strncpy(c, s, sizeof(c)-1);
// strncpy is not adding a \0 at the end of the string after copying it so you need to add it by yourself
c[sizeof(c)-1] = '\0';
Edit: Code added to question
Viewing your code the segmentation fault could be by the line
strcpy(c, token)
The problem is if token length is bigger than c length then memory is filled out of the c var and that cause troubles.
First off struct employee* emps[maxemps]; creates an array of pointers to struct employee with array size maxemps. You haven't actually set aside any space in memory for the actual structs, just the pointers that will point to them. To dynamically allocate space on the heap for your structs so you can use them in a meaningful way, you'll need to loop over a call to malloc() like so:
for (i = 0; i < maxemps; i++) {
emps[i] = malloc(sizeof(struct employee));
}
You'll also want a similar loop at the end of your program which will free() each pointer.
Next, when you are getting input from a user you really want to be using fgets() over scanf() because fgets() allows you to specify the number of characters to read in so you can prevent overflows on your destination buffer.
Update
If you want to work with a single struct employee without the use of pointers this is accomplished by declaring one or more struct employee on the stack and then using the . member access operator as follows:
struct employee emp;
fgets(emp.lastname, sizeof(emp.lastname), stdin);
Update2
I found a number of errors in your code. Please see this link for a working sample with comments.
You only need:
scanf("%10s", (emps[i])->last_name);
Here "%10s" denotes a string with a maximum length of 10, and it will load the string to last_name.
In C the string is represented as a char array, with '\0' as the end.
Using scanf here is vulnerable to buffer attacks if the user-input is longer than 10: http://en.wikipedia.org/wiki/Scanf#Security, so you need to assign a maximum length to the format.
Simplest way I can think of doing it is:
string temp = "cat";
char tab2[1024];
strcpy(tab2, temp.c_str());
For safety, you might prefer:
string temp = "cat";
char tab2[1024];
strncpy(tab2, temp.c_str(), sizeof(tab2));
tab2[sizeof(tab2) - 1] = 0;
or could be in this fashion:
string temp = "cat";
char * tab2 = new char [temp.length()+1];
strcpy (tab2, temp.c_str());
Ok, i am shocked that no one really gave a good answer, now my turn. There are two cases;
A constant char array is good enough for you so you go with,
const char *array = tmp.c_str();Or you need to modify the char array so constant is not ok, then just go with this
char *array = &tmp[0];
Both of them are just assignment operations and most of the time that is just what you need, if you really need a new copy then follow other fellows answers.
we simply use the strcpy function to copy the array into the pointer.
char str[] = "Hello World";
char *result = (char *)malloc(strlen(str)+1);
strcpy(result,str);
In your first snippet you modify the pointer in the loop, so after the loop it will no longer point to the same location returned by the malloc call.
Look at it this way, after the call to malloc the pointer and the memory look like this:
result | v +---+---+---+---+---+---+---+---+---+---+---+---+ | | | | | | | | | | | | | +---+---+---+---+---+---+---+---+---+---+---+---+
After the first iteration of the loop it will look like this:
result
|
v
+---+---+---+---+---+---+---+---+---+---+---+---+
| H | | | | | | | | | | | |
+---+---+---+---+---+---+---+---+---+---+---+---+
And after the loop is done it will look like this
result
|
v
+---+---+---+---+---+---+---+---+---+---+---+----+
| H | e | l | l | o | | W | o | r | l | d | \0 |
+---+---+---+---+---+---+---+---+---+---+---+----+
The copying is made, but the pointer no longer points to the original position.
[Note: Before the copying, the memory allocated by malloc will not be "empty" or initialized in any way, I just show it like that here for simplicity's sake.]
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).