Reputation: 41
The following code give that error. The code is not all mine some parts where given from my professor, my code is under the commend /add your code/. I don't know the line that causes the error and i can't understand anything i find online, I'm only a freshman.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct charact {
char ch;
int occurs;
struct charact *next;
};
typedef struct charact Char;
typedef Char * ListofChar;
typedef Char * CharNode_ptr;
void letters(char name[50], ListofChar * chars_ptr);
void report(ListofChar chars);
Char * createnode(char ch);
int main(void)
{
char name[50];
ListofChar chars = NULL;
scanf("%49s", name);
letters(name, &chars);
report(chars);
return 0;
}
Char * createnode(char ch)
{
CharNode_ptr newnode_ptr ;
newnode_ptr = malloc(sizeof (Char));
newnode_ptr -> ch = ch;
newnode_ptr -> occurs = 0;
newnode_ptr -> next = NULL;
return newnode_ptr;
}
void letters(char name[50], ListofChar * lst_ptr)
{
/* add your code */
Char chars[50];
size_t i,j;\
/* lst_ptr = malloc(sizeof(name));*/
memset(chars,0,50*sizeof(ListofChar));
for(i=0;name[i]!='\0';i++){
chars[i].ch=name[i];
for(j=i+1;name[j]!='\0';j++){
if(name[i]==name[j]){
chars[i].occurs = j-i;
break;
}
}
}
return;
}
void report(ListofChar chars)
{
/* add your code */
int i = 0;
while(!(chars[i].ch=='\0')){
printf("%c:%d\n",chars[i].ch,chars[i].occurs);
i++;
}
return;
}
Upvotes: 1
Views: 105
Reputation: 27
The segmentation fault is happening at line 58 because chars is NULL
.
You are passing in letters the variable chars as an argument ,but you don't change it's value. Then you call the function report with chars as an argument but chars is still NULL
. So !(chars[i].ch=='\0')
is causing the error.
You probably have to remove Char chars[50]
and instead use lst_ptr
inside the function letters.
Upvotes: 1