以下程序在v2
打印时会出现段错误,但在数组复制期间不会出现。有谁知道为什么?
#include <stdio.h>
#include <stdlib.h>
void cpyarray (void* dst, void* src, size_t memsize, size_t size) {
for (size_t i = 0; i < size; i++) {
*(((char*) dst) + i*memsize) = *(((char*) src) + i*memsize);
}
}
int main () {
size_t N = 10;
double* v1 = (double *) malloc(N * sizeof(double));
double* v2 = (double *) malloc(N * sizeof(double));
for (size_t i = 0; i < N; i++) *(v1+i) = i;
printf("\n\nv1: ");
for (size_t i = 0; i < N; i++) printf("%g ", v1[i]);
cpyarray(&v2, &v1, sizeof(double), N);
printf("\n\nv2: ");
for (size_t i = 0; i < N; i++) printf("%g ", v2[i]); // program crashes here
return 0;
}
编辑ints
:如果我复制数组而不是,代码不会崩溃doubles
。