【每日一题C】基于排列构建数组

本文通过一个实例介绍了如何在C语言中使用动态内存分配创建数组,并利用指针函数处理数组元素。核心代码包括使用`malloc`创建指针变量,通过下标访问数组元素,并提供了一个指针函数`buildArray`来构建数组。最终,主函数验证了该功能的正确性,输出了预期的数组顺序。
摘要由CSDN通过智能技术生成

题目描述 :

思路分析:

1、 用“int *ans = (int *)malloc(sizeof(int)*numsSize);”构建指针变量ans;

2、*(ans+2)的值即为ans[2]的值,ans[2]=num[num2]];

3、创建指针函数buildArray,返回值为指针变量ans,为地址值;

关键代码展示:

(主要填写buildArray函数部分代码,主函数验证函数引用是否完成相应功能,具体待完善)

#include <stdio.h>
#include<stdlib.h>
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* buildArray(int* nums, int numsSize, int* returnSize){
  // Please fill this blank
  *returnSize=numsSize;
  int *ans = (int *)malloc(sizeof(int)*numsSize);
  for(int i=0;i<numsSize;i++){
      ans[i]=nums[nums[i]];
  }
  return ans;
}
int main(void) {
  int a[6]={0,2,1,5,3,4},*b,i,j;
  b=buildArray(a,6,&i);
  for(j=0;j<i-1;j++)
    printf("%d,",b[i]);
  printf("%d\n",b[j]);
  return 0;
}

运行结果:

0,1,2,4,5,3

参考链接:

https://blog.csdn.net/weixin_44373236/article/details/121929990

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林月明

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值