它在这一行(在for循环中)中断了仅在程序的第二次运行中: (arrP + i)=(char )realloc((* arrP + i),(sizeof(char)* currentLen));
#include <stdio.h>
#include <string.h>
int main(void)
{
printf( "Please enter the amount of friends u have: \n\n \t" );
unsigned int friendsNum = 0;
scanf( "%d", &friendsNum );
getchar();
char** arrP = (char**)calloc( friendsNum, sizeof( char* ) );// pointer to a pointer array, that every item points on a str[0]
unsigned int i = 0;
unsigned int currentLen = 0;
unsigned const int BUFFER = 28; // The maximum length you expect
for (i = 0; i < friendsNum; i++)
{
*(arrP + i) = (char*)calloc( BUFFER, sizeof( char ) );
if (!(arrP + i))
{
printf( "ERROR, EXITING" );
return(1);
}
fgets( *(arrP + i), 20, stdin );
(*(arrP + i))[strcspn( *(arrP + i), "\n" )] = '\0';
currentLen = strlen( *(arrP + i) ) + 1;// including \0(+1)
*(arrP + i) = (char*)realloc( (*arrP + i) , (sizeof( char ) * currentLen));
if (!(arrP + i))
{
printf( "ERROR, EXITING" );
return(1);
}
}
getchar();
return 0;
}
答案 0 :(得分:0)
问题在于*(arrP + i)
与(*arrP + i)
不同:
arrP[i]
arrP[0]+i
如果您使用[]
运算符而不是指针算术切换到基于下标的访问,您将拥有更轻松的代码:
arrP[i] = realloc(arrP[i], currentLen);
请注意,您不会在C中投射malloc
,并且您可以依赖标准要求sizeof(char)
为1
的事实。