Is there a way to have a pointer in C that points to an array be reassigned so that it points to an array of a smaller size? For example, if I have a pointer ptr
that originally points to an array s
of size 3, and there also exists an array s1
of size 2, could I reassign ptr
so that it points to s
and thus points to a smaller array?
I tried the following code:
void changePtr(double* ptr);
int main()
{
double *ptr;
ptr = (double*)malloc(sizeof(double)*3);
double s[3]={1,2,3};
ptr=s;
changePtr(ptr);
return 0;
}
void changePtr(double* ptr) {
double s1[2]={4,5};
free(ptr);
ptr = (double*)malloc(sizeof(double)*2);
ptr=s1;
}
But when I run this in VIsual Studio, I get an error at free(ptr)
which says Debug Assertion failed! Expression: _CrtIsValidHeapPointer(block)
Why is this?
EDIT
New code is:
void changePtr(double* ptr);
int main()
{
double *ptr;
ptr = (double*)malloc(sizeof(double)*3);
double *s;
s = (double*)malloc(sizeof(double)*3);
s[0]=1; s[1]=2; s[0]=3;
for (int i=0; i<3; i++){
ptr[i]=s[i];
}
changePtr(ptr);
for (int i=0; i<2; i++){
printf("%f\t", ptr[i]);
}
free(ptr);
free(s);
return 0;
}
void changePtr(double* ptr) {
free(ptr);
double *s1;
s1 = (double*)malloc(sizeof(double)*2);
s1[0]=11; s1[1]=12;
ptr = (double*)malloc(sizeof(double)*2);
for (int i=0; i<2; i++){
ptr[i]=s1[i];
}
}
But I get garbage values like -1456815990147....1
when I print out the values of ptr
after calling changePtr
. Why is this?