[英]Copying from one array to another using pointers
I've written some code to try and copy an array and then return a pointer to that new, copied array.我已经编写了一些代码来尝试复制一个数组,然后返回一个指向该新复制数组的指针。
#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;
}
But I'm getting these compile errors但我收到这些编译错误
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);
^
Im new to using pointers so I hope I'm doing them correctly.我是使用指针的新手,所以我希望我正确地使用它们。 I've tried to allocate memory in hemp for the dest array, copy the values of array into dest and then rerturn a pointer to dest.
我试图在麻中为 dest 数组分配内存,将数组的值复制到 dest,然后返回一个指向 dest 的指针。
尝试返回 dest 而不是 *dest
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.