gpt4 book ai didi

c++ - 如何在 C++ 中确定 2D 无符号短指针数组长度

转载 作者:行者123 更新时间:2023-11-30 18:09:08 28 4
gpt4 key购买 nike

我发现很难确定二维无符号短指针数组中列的长度。据我所知,我已经正确地分配了内存。并能正确打印。

请参阅以下代码段:

int number_of_array_index_required_for_pointer_abc=3;
char A[3][16];


strcpy(A[0],"Hello");
strcpy(A[1],"World");
strcpy(A[2],"Tumanicko");


cout<<number_of_array_index_required_for_pointer_abc*sizeof(unsigned short)<<endl;
unsigned short ** pqr=(unsigned short **)malloc(number_of_array_index_required_for_pointer_abc*sizeof(unsigned short));




for(int i=0;i<number_of_array_index_required_for_pointer_abc;i++)
{

int ajira = strlen(A[i])*sizeof(unsigned short);
cout<<i<<" = "<<ajira<<endl;
pqr[i]=(unsigned short *)malloc(ajira);
cout<<"alocated pqr[i]= "<<sizeof pqr<<endl;


int j=0;
for(j=0;j<strlen(A[i]);j++)
{
pqr[i][j]=(unsigned short)A[i][j];

}
pqr[i][j]='\0';


}


for(int i=0;i<number_of_array_index_required_for_pointer_abc;i++)
{

//ln= (sizeof pqr[i])/(sizeof pqr[0]);

//cout<<"Size of pqr["<<i<<"]= "<<ln<<endl;


// I want to know the size of the columns i.e. pqr[i]'s length instead of finding '\0'

for(int k=0;(char)pqr[i][k]!='\0';k++)
cout<<(char)pqr[i][k];
cout<<endl;

}

最佳答案

你就快到了。你有这个循环:

for(int k=0;(char)pqr[i][k]!='\0';k++) ...

一旦这个循环完成,k将有行的长度。所以这会给你 pqr[i] 的长度(不包括空终止符):

int k;
for (k=0; pqr[i][k] != 0; k++)
;
cout<<"The length is "<< k <<endl;
<小时/>

编辑:

您现在补充说,即使空终止符不存在,您也想知道大小。没有办法做到这一点。您需要有某种终止符,或者将大小存储在某个地方。如果您使用vector<unsigned short> ,它会为您存储尺寸。由于它还处理分配和释放,因此这是推荐的选择。

<小时/>

请注意,您的分配有两个错误:

  1. pqr是一个指针数组,但您分配的大小为 C*sizeof(unsigned short) 。那应该是 C*sizeof(unsigned short *)相反。

  2. 您没有为每个字符串末尾的空终止符分配内存:您应该分配 (strlen(A[i])+1) * sizeof(unsigned short)对于每个字符串。

关于c++ - 如何在 C++ 中确定 2D 无符号短指针数组长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2728724/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com