使用指针从一个数组复制到另一个数组

标签 c pointers

我已经编写了一些代码来尝试复制一个数组,然后返回指向该新复制数组的指针。

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

//// Returns a pointer to a freshly allocated array that contains the
// same values as the original array, or a null pointer if the
// allocation fails. The caller is responsible for freeing the array
// later.

uint8_t* copy( const uint8_t array[], 
           unsigned int cols, 
           unsigned int rows )
{
  uint8_t* dest = malloc(rows*cols*sizeof(uint8_t));
  int i;
  for (i=0; i<rows*cols;i++)
    {memcpy(&dest[i], &array[i], sizeof(array[0]));}

  if (dest!=NULL)
    {return *dest;}
  else 
    {return NULL;}
}

// Print destination array 
int main(){
int i=0;
const uint8_t cols=3;
const uint8_t rows=2;
const uint8_t dest[rows*cols];
const uint8_t array[rows*cols];

array[rows*cols]={1,2,3,4,5,6};

dest=copy(array, cols,rows);

for (i=0; i<rows;i++)
        {printf("%d ,",dest[i]);}

return 0;
}

但是我遇到了这些编译错误

Testing_code.c: In function 'copy':
Testing_code.c:22:6: warning: return makes pointer from integer without a cast [enabled by default]
     {return *dest;}
      ^
Testing_code.c: In function 'main':
Testing_code.c:35:18: error: expected expression before '{' token
 array[rows*cols]={1,2,3,4,5,6};
                  ^
Testing_code.c:37:1: warning: assignment of read-only location 'dest' [enabled by default]
 dest=copy(array, cols,rows);
 ^
Testing_code.c:37:5: error: incompatible types when assigning to type 'const uint8_t[(sizetype)((int)rows * (int)cols)]' from type 'uint8_t *'
 dest=copy(array, cols,rows);
     ^

我不熟悉使用指针,所以我希望我能正确使用它们。我试图在 hemp 中为 dest 数组分配内存,将数组的值复制到 dest,然后返回指向 dest 的指针。

最佳答案

尝试返回 dest 而不是 *dest

关于使用指针从一个数组复制到另一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36251853/

相关文章:

c - gdb watch 指针还无效

c - C语言中的字符串输入问题

C++ const 结构指针不可访问

c++ - C仅使用指针从多维数组中提取特定列

delphi - 帕斯卡指针改变其指向值

c - 在 C 中释放内存的模式?

调用系统 UNIX - C 中的文件复制

c++ - 未知包装 nar - nar-maven-plugin

C++:如何将 memcpy 与指针 ** 一起使用?

c++ - 如何防止过滤来自非常量访问指针的指针 vector 的函数?