如何定义自定义长度的数组并赋值

2025-04-16 08:13:51
推荐回答(2个)
回答1:

除常量数组外,数组必须是定长的,如果不知道长度,有几种办法,固定分配一个认为不会出现的维度值,或者对数组进行动态分配,如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

int *pArray,nCount;
int Insert(int * pArray,int nCount,int nElement)
{
int *pInt;

pInt = new int[nCount+1];
if(nCount>0)memcpy(pInt,nArray,nCount);
pInt[nCount++] = nElement ;
if(pArray)delete pArray;
pArray = pInt;
return nCount;
}
main()
{
nCount = 0,pArray = NULL;
nCount = Insert(pArray,nCount,99);
}

回答2:

void __fastcall TForm1::Button1Click(TObject *Sender)
{
String s[2][2];
for(int i = 0;i<2;i++)
for(int j = 0;j<2;j++)
{
s[i][j] = IntToStr(i+j);
ShowMessage(s[i][j]);
}
}