Reputation: 9
I want to assign an array to another array. Both arrays do not have the same size:
char array1[7] = "abcdefg";
char array2[3];
How can i assign three(3) values from array1 into array 2? I tried so:
array2[3] = {array1[2], array1[3], array1[4]};
and i´d become the following error message:
expected expression before ´{´token
I know that i can use (memcpy()
) when the arrays have the same size.
I have more experience with VHDL and verilog. In VHDL it could look like this:
array2 := arry1(2 upto 4);
But i do not have much experience with C programing.
Thank you
Upvotes: 0
Views: 7370
Reputation: 50328
If you wish to do the copy at run-time, you can either use memcpy()
:
memcpy(array2, array1 + 2, 3);
or just write your own copy loop:
for (int i = 0; i < 3; i++) array2[i] = array1[i + 2];
Note that, depending on the surrounding code and your C compiler and optimization settings, these two methods may or may not end up compiling into the same binary. Specifically, it's quite possible for an optimizing compiler to both inline memcpy()
and to transform the explicit copy loop into a call to memcpy()
, depending on what the compiler thinks would be most efficient.
Also note that, if the arrays were of some type other than char
, the length argument to memcpy()
would need to be multiplied by the size of the element type in bytes. However, the C standard guarantees that sizeof(char) == 1
.
Upvotes: 2
Reputation: 310930
If you indeed mean the assignment then you can use еру standard function strncpy
declared in header <string.h>
.
Here is a demonstrative program
#include <stdio.h>
#include <string.h>
int main(void)
{
char array1[7] = "abcdefg";
char array2[4];
size_t n = 3;
strncpy( array2, array1 + 2, n );
array2[n] = '\0';
puts( array2 );
return 0;
}
Its output is
cde
Take into account that if you want that the array array2
would contain a string then its size shall be equal to 4 to store the three copied characters and the terminating zero.
Upvotes: 1
Reputation: 3154
This works on Windows 7
#include <stdio.h>
#include <string.h>
int main() {
char array1[7] = "abcdefg";
char array2[3];
strncpy(&array2[0],&array1[2],3);
printf("%s\n",array2);
}
Output:
cde
Upvotes: 0
Reputation: 588
When you initialize your array2[3]
, you can copy the values like you do
Just do this,
char array1[7] = "abcdefg";
char array2[3] = {array1[2], array1[3], array1[4]};
Upvotes: 2