gpt4 book ai didi

c - C 中的数组切片

转载 作者:行者123 更新时间:2023-12-01 12:38:05 25 4
gpt4 key购买 nike

在 Python 中,如果我想分配 vector x=(1,2)y=(0,0,0,0) 的前两个元素,我会做类似 y[:1] = x 的事情. C 中是否有等效项来分配 double x[2]={1.,2.}到可用 double y[4] = {0.,0.,0.,0.} 的前两个元素?还是我必须循环?

最佳答案

试试这个

#include <string.h>
#include <stdio.h>

int main()
{
double x[2] = {1., 2.};
double y[4] = {0., 0., 0., 0.};

memcpy(y, x, 2 * sizeof(*x));
/* ^ 2 elements of size -> sizeof(double) */

return 0;
}

而不是写 sizeof(double)没关系,我做了 sizeof(*x)因为如果我改变 x 的类型我不需要修复 memcpy ,但我还必须更改 y 的类型在这种情况下。

关于c - C 中的数组切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27725222/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com