How can I overwrite an array of chars (AKA a string), with a new array of chars in C?
int main(void) {
...
char A[32] = "00000000000000001111111111111110";
...
A = "11111111111111111111111111111111";
}
This is erroneous c-code for what I want to do. I want the string开发者_运维百科 in memory to be overwritten with a new string of the same length. I keep getting incompatible types -like errors.
Use strncpy:
char chararray[6];
(void)strncpy(chararray, "abcdefgh", sizeof(chararray));
Use strcpy(char *destination, const char *source);
.
#include <string.h>
int main(void) {
...
char A[32] = "00000000000000001111111111111110";
...
strcpy(A, "11111111111111111111111111111111");
}
Though safer is strncpy(char *destination, const char *source, size_t num)
, which will only copy num
amount of characters, preventing going out of bounds on the destination:
#include <string.h>
int main(void) {
...
char A[32] = "00000000000000001111111111111110";
...
strncpy(A, "11111111111111111111111111111111", sizeof(A));
}
memcpy(A,"11111111111111111111111111111111",32);
Among other possible ways, you can do
memcpy(A, "11111 etc.", 32);
You want to make 32 into a named constant, at the least. You also have to be careful of buffer overflows; in C this is not checked.
have a look into the library function strcpy
.
精彩评论