简体   繁体   中英

Copying arrays in C

In my C program I am trying to copy an array of char's to another array whilst removing the first element (element 0).

I have written:

char array1[9];
char array2[8];
int i, j;

for(i = 1, j = 0 ; i < 10, j < 9; i++, j++){
        array2[j] = array1[i];
}
printf(array2);

When I print array2, it gives me a stack overflow.

Any ideas?

Two issues: First, when printing a string with printf , and working with other standard C string functions in general, your char arrays need to be null-terminated so the functions know where the string ends. You are also writing one past the end of your arrays.

Second, when using printf , it is almost always a bad idea to use the string you want to print as the format string. Use

printf("%s", array2);

instead. If you use printf as in the original example and array2 can be influenced by the user, then your program is likely vulnerable to a format string vulnerability.

Your string isn't null-terminated, so when its printed it continues printing characters past the 8 you've allocated looking for one but runs out of stack space before then. You're also writing to one character more than you've allocated and your conditions should be "combined" with && -- a , ignores the result of the first expression. You should also avoid using a string variable as the string formatter to printf .

Here's your code fixed :

char array1[10] = "123456789";
char array2[9];
int i, j;
for(i = 1, j = 0 ; i < 10 && j < 9; i++, j++){
        array2[j] = array1[i];
}
printf("%s\n", array2);

You can also simplify the loop by using a single index variable i and indexing array2 with i+ . You can also remove the loop entirely by using strncpy , but be aware that if n is less than the length of the string + 1 it won't add a null-terminator.

Use memcpy():

memcpy( array2, &array1[1], 8 );

Thats easier.

不必使用额外的array2

printf("%.8s",array1+1);

When you say printf(array2) , it thinks it's printing a null-terminated string. Since there is (possibly) no \\0 in array2 , printf continues on past the end of array2 , wandering into memory it isn't supposed to.

To further expand on marcog's answer: you are declaring array1 with 9 elements, 0-8, and then writing from 0-9 (10 elements). Same thing with array2.

Just use strcpy() (if they're both strings!) strcpy() wants a pointer to the source and a pointer to the destination. If you want to skip the first element of the source array just pass source + 1 :

char source[] = "ffoo";
char dest[] = "barbar";

strcpy(dest, source + 1);

// now dest is "foo" (since the ending \0 is copied too)

printf("\n%s\n", dest);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM