Is there any solution to grow an dynamic array without free and reallocate it, then recopy the original value? I did some experiment as below, only works for 'int'(how good/reliable is it?) and nop the 'char'. Help!
[cpp]
void main()
{
int i, *pnum, *num;
char *pstr, *str;
// Grow 'int' type array
num = new int[5];
for (i=0; i<5; i++)
num = i;
//endfor
for (i=0; i<5; i++)
printf("%d%c",num,(i == 4) ? '\n':' ');
//endfor
pnum = &num[4];
pnum = new int[10];
for (i=5; i<8; i++)
num = i * 3;
//endfor
for (i=0; i<8; i++)
printf("%d%c",num,(i == 7) ? '\n':' ');
//endfor
// Grow 'char' type array
str = new char[5];
strcpy(str,"abcd");
printf("str = %s\n",str);
pstr = &str[3];
pstr = new char[100];
strcpy(pstr,"12345678");
printf("str = %s\n",str);
}
[/cpp]
The output:
[cpp]
0 1 2 3 4
0 1 2 3 4 15 18 21
str = abcd
str = abcd
[/cpp]
One more thing, how to get the number of array size(element), passed as parameter?
[cpp]
int getBufSize(char *buf)
{
// Output should 1024, nop 4
printf("sizeof(buf) = %d\n",sizeof(buf));
}
void main(int argc, char *argv[])
{
int i, *pnum, *num;
char *pstr, *str;
char buf[1024];
printf("sizeof(buf) = %d\n",sizeof(buf));
getBufSize(buf);
}
[/cpp]
-novice
