Эта программа работает отлично:таНос в функции - ошибка сегментации
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NUM 2
int tempfunction (char **comments)
{
char str1[]="First string\n";
char str2[]="This is the second string\n";
*(comments+0)=(char *) malloc(strlen(str1)+1);
*(comments+1)=(char *) malloc(strlen(str2)+1);
strcpy(*(comments+0), str1);
strcpy(*(comments+1), str2);
return 0;
}
int main(void)
{
char **comments;
/* This is the section I am talking about */
comments=(char **) malloc(MAX_NUM*sizeof(char *));
if (comments==NULL)
{
printf("\n### ERROR: malloc failed.\n");
exit(EXIT_FAILURE);
}
/* Upto here............................. */
tempfunction(comments);
printf("%s%s", comments[0], comments[1]);
return 0;
}
Но для удобства в дальнейшем я хотел бы положить раздел внутри tempfunction
malloc
. Когда я это делаю, я получаю ошибку ошибки сегментации.
Я думал, что это может быть из-за инициализации, поэтому вместо char **comments;
я пишу:
char a = 'a';
char *P = &a;
char **comments = &P;
Но она по-прежнему не работает. Я был бы очень благодарен, если бы вы могли помочь мне понять, почему это происходит и как это исправить.
[Не использовать введите возвращаемое значение 'malloc()'] (http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858)! –
'char * comments [2] = {NULL, NULL};' будет делать. – wildplasser
http://c-faq.com/malloc/mallocnocast.html – devnull