[英]Reallocing an array in C
I'm trying to create a function that would append two vectors together, but I end up getting a segfault when trying to reallocate more memory to the first vector so the second one would fit. 我试图创建一个将两个向量附加在一起的函数,但是当尝试向第一个向量重新分配更多内存以便第二个向量适合时,我最终遇到了段错误。 Here's the code 这是代码
void vectorAppend(double** v1, size_t* s1, double const* v2, size_t s2){
assert(v1 && v2 && *s1 > 0 && s2 > 0);
(*v1) = realloc((*v1), (*s1 + s2)*sizeof(double));
for (size_t i = 0; i < s2; i++){
*v1[*s1+i]=v2[i];
}
*s1+=s2;
}
And this is how I call it from main 这就是我从主叫的方式
double *v1 = vectorConstruct(3, 2);
double *v2 = vectorConstruct(3, 0);
unsigned int s = 3;
vectorAppend(&v1, &s, v2, 3);
vectorConstruct returns a pointer to a vector that is initialized to the second argument. vectorConstruct返回指向初始化为第二个参数的向量的指针。
double* vectorConstruct(size_t s, double val){
assert(s>0);
double *ret = malloc(s*sizeof(double));
for(size_t i = 0; i < s;i++){
ret[i]=val;
}
return ret;
}
I can't seem to find the problem here so any answers are appreciated. 我似乎在这里找不到问题,因此感谢所有答复。
*v1[*s1+i]=v2[i];
should be 应该
(*v1)[*s1+i]=v2[i];
Unary *
has a surprisingly low precedence. 一元*
优先级低得惊人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.