I'm trying to resize an array to contain values with length of "newlen". If newlen is less than the original array length, the end of the array is discarded. If newlen is greater, the new integers should be zero. I came up with this function, but when I test it, I get segmentation fault. I also don't know how to add the zeroes to the end, how can I keep track of the index so that I can add int zeroes at the end? I did the first case (where newlen is less than len), but don't know how to do the other case.
Here's the structure for the array:
typedef struct {
int* data;
unsigned int len;
} intarr_t;
My function:
array_size( intarr_t* p, unsigned int newlength )
{
int i,m = 0;
if (newlength < len)
int *tmp;
tmp = realloc(p->data, (p->newlen)* sizeof *p->data);
if(tmp)
{
for (i; newlength < p->len; i++)
{ for (m; newlength < p->len; m++)
{
p->data[i] = p->data[m];
}
}
}
}
iis not initialized,lenis unknown variable,tmpis not used,newlenis not used,double infinite for... This code should not compile at allnewlengthisn't1. better yet make sure it is a power of two