简体   繁体   English

使用memcpy将数据复制到数组中

[英]copying datas into the array using memcpy

#include <stdio.h>

int main(){
    int a[4];
    int b[4],i;
    a[0] = 4;
    a[1] = 3;
    a[2] = 2;
    a[3] = 1;
    memcpy(&b, &a, sizeof(a));
    for (i = 0; i < 4; i++){
        printf("b[%d]:%d",i,b[i]);
    }
    printf("%d",sizeof(b));
}

ANS: ANS:

b[0]:4b[1]:3b[2]:2b[3]:116
Exited: ExitFailure 2

I'm getting the correct answers. 我得到了正确的答案。 But getting a exception as Exited: ExitFailure 2. 但是获得Exited:ExitFailure 2的异常。

Is this way of copying the array datas using memcpy is wrong? 这种使用memcpy复制数组数据的方法是错误的吗?

Try adding a return 0; 尝试添加return 0; at the end of main() . main()的末尾。

Omitting the return value is probably causing the function to return stack garbage. 省略返回值可能导致函数返回堆栈垃圾。 (that's not 0) (那不是0)

The test app/script is therefore complaining of failure when it sees a non-zero return value. 因此,测试应用程序/脚本在看到非零返回值时会抱怨失败。


Prior to C99, omitting the return statement is technically undefined behavior. 在C99之前,省略return语句是技术上未定义的行为。 Starting from C99, it will default to 0 if it is omitted. 从C99开始,如果省略则默认为0

More details here: Why main does not return 0 here? 更多细节在这里: 为什么main不会在这里返回0?

Correction: 更正:

Not explicitly returning 0 ( return 0; ) leads to undefined behaviour prior to C99 . 未明确返回0( return 0; )会导致C99之前的undefined behaviour

However, since a particular register is usually used for storing a return value (for example eax in x86 ) from a function, the value in that register is returned. 但是,由于特定寄存器通常用于存储函数的返回值(例如x86 eax ),因此返回该寄存器中的值。

It just happen to be that printf("%d",sizeof(b)); 恰好是printf("%d",sizeof(b)); is storing the size of the char array in the same register that is used for returning a value from a function. char数组的大小存储在用于从函数返回值的同一寄存器中。

Because of this, the returned value is 2 . 因此,返回值为2

Original answer: 原始答案:

Since you do not state return 0; 既然你没有说明return 0; at the end of main, the last printf call is interpreted as the return value of main. 在main的末尾,最后一次printf调用被解释为main的返回值。

sizeof(b) returns 16 which is 2 characters long, thus the program returns 2 as exit code. sizeof(b)返回16 ,其长度为2字符,因此程序返回2作为退出代码。

There is problem in your memcpy statement. memcpy语句中存在问题。

1) You should pass pointer to your array in stead you are passing pointer to pointer of 1)您应该将指针传递给您的数组,而不是将指针传递给指针
your array. 你的阵列。

2) You should pass size of your array, sizeof(a) will return only size of int so u have to multiply it with max index of array. 2)你应该传递数组的大小,sizeof(a)将只返回int的大小,所以你必须将它与数组的最大索引相乘。

You have to do little modification in your code as given below, 您必须对代码进行少量修改,如下所示,

memcpy(b, a, sizeof(a) * 4); memcpy(b,a,sizeof(a)* 4);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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