如何在Heap中存储字符串数组? 我已经阅读了this,但我无法解决问题。 例如,这个程序不起作用:
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
int main() {
int n,i;
char *ptr;
printf("How many students?\n");
scanf("%d",&n);
ptr=(char*)calloc(n,sizeof(char));
for(i=0;i<n;i++){
printf("Enter the name of student:\n");
scanf("%s",&ptr[i]);
}
for(i=0;i<n;i++){
printf("%s",ptr[i]);
}
}
&#34;该程序已停止工作&#34;
答案 0 :(得分:-1)
以下提议的代码:
getline()
POSIX功能size_t
和ssize_t
ptr
为char **
malloc
正确调用char*
而不是char
现在,建议的代码:
// expose getline() function via:
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
size_t numStudents;
printf("How many students?\n");
scanf("%lu",&numStudents);
char **ptr = malloc( numStudents * sizeof(char*) );
if( !ptr )
{
perror( "calloc failed" );
exit( EXIT_FAILURE );
}
// implied else, calloc successful
for( size_t i=0; i<numStudents; i++ )
{
printf("Enter the name of student:\n");
ssize_t bytesRead;
size_t length = 0;
char *line = NULL;
bytesRead = getline( &line, &length, stdin );
if( bytesRead <= 0 )
{
perror( "getline failed" );
exit( EXIT_FAILURE );
}
// implied else, getline successful
ptr[i] = line;
}
for( size_t i=0; i<numStudents; i++ )
{
printf( "%s\n", ptr[i] );
free( ptr[i] ); // cleanup
}
}