Click here to Skip to main content
14,932,010 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The same appears in another site (where people usually like to downvote rather than been helpful to others)

I have an exercise, where the user gives an word as input, and then using structs, the code should make lists and for each entered word count len of characters. So the code looks like the code appended below [1]

I can totally initialize and fill the COUNT [2]

So, ultimately, what needs to be done, is to call struct COUNT from inside struct occurrence and basically for every word that is given, store the length of it in the list. So, how should I initialize the struct occurrence and call the COUNT from within ?

What I have tried:


typedef struct node
{ int countwords;
struct node *nextnode;

struct occurrence
char word[30];
int count;
COUNT * ocurrence_list_thehead;

struct occurrence occurrences[30];

COUNT *first  = NULL;
COUNT *last  = NULL;

<pre>int counter=0;
int main()
  COUNT *node=NULL;
  char textin[N+1];
  while(1) {
  if (node==NULL) 
   printf("Cannot allocate memory");
  return 1;

  fgets(textin, sizeof(textin), stdin);
  if (strcmp(textin , "exit") == 0)
   node->countwords = strlen(textin);   
   if (first!=NULL){
    else {

struct occurrence *occ = &(occurrences[counter]);

occ->ocurrence_list_thehead-> countwords = strlen(textin);

 while (node!=NULL){
     printf ("\n %d length of string", node->countwords);
    return 0; 
Updated 26-Apr-21 10:17am

1 solution

You have declared an array of occurrence objects called occurrences:
struct occurrence occurrences[30];
So all you need is an index to the next free one, and get the address of it using:
struct occurrence *occ = &(occurrences[indexToNextFree++]);
The post increment moves you to the next ready for the next inputsession.
Just_Newbie 26-Apr-21 16:16pm
thanks for the rensponse.

However, if I try to

struct occurrence *occ = &(occurrences[counter]);

with the counter being an int that just gets increasing with the number of words the user enter, I still get a segmentation fault....
Rick York 26-Apr-21 20:30pm
You have a hard-coded limit of 30 and no way to add more. You have the basics of a linked list going there. If you adjust your implementation a little bit you can handle as many as the user will ever want to enter. The first thing to do is get rid of the hard-coded limit and then figure out how to dynamically allocate the occurrences.

Since you have a limit on 29 characters for words (remember the null) you might want to enforce it so the buffer is not overrun. There are very few words that big but some user might want to test it and it would be best to not crash when they do.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900