在此声明中
char **s = calloc(n, 10 * (sizeof(char) + 1));
您分配了一个内存,其地址分配给了指针s。由于调用函数calloc,内存被初始化为零。
所以在这个声明中
fgets(*(s + i), 10 * (sizeof(char) + 1), stdin);
指针s 被取消引用,或者是空指针(因为指向的内存被零初始化)或者如果表达式s + i 指向分配的内存之外,则具有不确定的值。
您需要分配char * 类型的指针数组,并为每个指针分配已分配字符数组的地址。
通常您还应该检查calloc 或malloc 调用的返回值。
您的代码还有另一个问题。打完scanf
scanf("%i", &n); //number of strings being inputted
输入缓冲区包含新行字符'\n',它将被fgets 的以下调用读取。所以fgets 的第一次调用实际上会读取一个空字符串。
另一个问题是您应该删除可以通过fgets 附加到读取字符串的换行符。例如,一些读取的字符串可以包含新的 .line 字符,而另一些可以不包含它,具体取决于用户键入的字符数。
如果你想在不使用带指针的下标运算符的情况下编写程序,那么它可以查看例如以下方式。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
size_t n = 0;
if ( scanf( "%zu", &n ) == 1 )
{
scanf( "%*[^\n]" );
scanf( "%*c" );
}
char **s = NULL;
if ( n != 0 ) s = calloc( n, sizeof( char * ) );
if ( s != NULL )
{
size_t len = 11;
size_t m = 0;
while ( m < n && ( *( s + m ) = malloc( len * sizeof( char ) ) ) != NULL ) m++;
size_t i = 0;
while ( i < m && fgets( *( s + i ), len, stdin ) != NULL ) i++;
m = i;
for ( i = 0; i < m; i++ ) //print the strings
{
( *( s + i ) )[ strcspn( *( s + i ), "\n" )] = '\0';
// or without the subscript operator
// *( *( s + i ) + strcspn( *( s + i ), "\n" ) ) = '\0';
puts( *( s + i ) );
}
for ( i = 0; i < n; i++ ) free( *( s + i ) );
}
free( s );
return 0;
}
程序输出可能看起来像
10
one
two
three
four
five
six
seven
eight
nine
ten
one
two
three
four
five
six
seven
eight
nine
ten