它仅在程序的第二次运行中在此行(在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;
}

最佳答案

问题是*(arrP + i)(*arrP + i)不同:


第一个表达式等效于arrP[i]
第二个表达式等效于arrP[0]+i


如果您使用[]运算符而不是指针算术切换到基于下标的访问,则代码会更简单:

arrP[i] = realloc(arrP[i], currentLen);


请注意,您没有在C中强制转换malloc,并且可以依靠标准要求sizeof(char)为常数1的事实。

10-08 09:26