You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用函数给数组指定部分元素赋值?无需自定义void函数的方法

为数组指定部分元素赋值的优化实现方式

原场景回顾

我们可以通过指针实现返回动态数组的函数,示例如下:

#include <stdio.h>
#include <stdlib.h>

int* integers(int size)
{
   int* integers_array = malloc(size * sizeof(int));
   for(int j = 0; j < size; j++)
   {
      integers_array[j] = j;
   }
   return integers_array;
}

但要给已有数组x的第3个元素及之后的位置(即x+2指向的区域)赋值时,无法直接使用x+2 = integers(4);这类写法——赋值语句左侧不能是表达式。原方案通过自定义assignment函数规避问题,以下是无需自定义函数的更优实现方式:


方法1:使用标准库memcpy函数

C标准库<string.h>中的memcpy是专门用于内存块复制的函数,它的底层通常是优化过的汇编实现,效率远高于自定义循环,完全可以替代自定义的assignment函数。

示例代码:

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

int* integers(int size)
{
   int* integers_array = malloc(size * sizeof(int));
   for(int j = 0; j < size; j++)
   {
      integers_array[j] = j;
   }
   return integers_array;
}

int main()
{
    int size = 4;
    int* y;
    int x[] = {1, 1, 1, 1, 1, 1};
    
    y = integers(size);
    // 直接复制size个int的内存块到x+2指向的位置
    memcpy(x + 2, y, size * sizeof(int));
    
    // 务必释放动态分配的内存,避免内存泄漏
    free(y);
    return 0;
}

注意:memcpy按字节复制,第三个参数要计算总字节数(size * sizeof(int)),同时要确保目标数组剩余空间足够容纳size个元素,避免越界访问。


方法2:修改生成函数,直接写入目标位置

如果不需要保留原函数返回动态数组的功能,可以调整函数逻辑,让它直接把数据写入指定的目标指针,省去内存分配和复制的双重开销,这是效率最高的方案。

示例代码:

#include <stdio.h>

void generate_integers(int* dest, int size)
{
   for(int j = 0; j < size; j++)
   {
      dest[j] = j;
   }
}

int main()
{
    int size = 4;
    int x[] = {1, 1, 1, 1, 1, 1};
    
    // 直接将数据写入x+2指向的区域
    generate_integers(x + 2, size);
    
    return 0;
}

方法3:手动指针遍历赋值

如果不想依赖标准库函数,也可以直接在调用处用指针循环完成赋值,逻辑和自定义函数一致,但省去了函数调用的冗余:

示例代码:

#include <stdio.h>
#include <stdlib.h>

int* integers(int size)
{
   int* integers_array = malloc(size * sizeof(int));
   for(int j = 0; j < size; j++)
   {
      integers_array[j] = j;
   }
   return integers_array;
}

int main()
{
    int size = 4;
    int* y;
    int x[] = {1, 1, 1, 1, 1, 1};
    
    y = integers(size);
    // 用指针遍历完成赋值
    int* src = y;
    int* dest = x + 2;
    for(int j = 0; j < size; j++)
    {
        *dest++ = *src++;
    }
    
    free(y);
    return 0;
}

内容的提问来源于stack exchange,提问作者3sm1r

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 11:40:43