0

I have tried accessing each word member from my struct array outside the while loop where I read input but it doesnt print anything.It seems like the array is empty but if I were to put that print statement in my while loop, it works fine.Not sure why this is the case.

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

struct wordArr {
    char words[31];
    int wordCount;
};
 
int main(void) {
    const int ARRSIZE = 300;
    char tmpWord[30] = " ";
    char word[30] = " ";

    // allocate memories for n number of struct wordarr.
    // wordArrptr = (struct wordArr*) malloc(ARRSIZE * sizeof(struct wordArr));
    struct wordArr **wordList = malloc(ARRSIZE * sizeof(struct wordArr *));

    // const char delimiters[10] = " .,";
    for (int i = 0; i < ARRSIZE ; i++) {
        wordList[i] = malloc(sizeof(struct wordArr));
    }

    while (scanf("%s", tmpWord) != EOF) {
        memset(word, ' ', 30);
        int j = 0;
        int i = 0;

        for (int i = 0 ; i < strlen(tmpWord); i++) {
            if (isalpha(tmpWord[i])) {
                word[j] = tolower(tmpWord[i]);
                j++;
            }
        }

        strcpy(wordList[i]->words, word);

        // printf("%s=>\n", wordList[i]->words);
        wordList[i]->wordCount = 1;
        i++;
    }

    for (int i = 0 ; i < ARRSIZE ; i++) {
        printf("%s\n", wordList[i]->words);
    }

    return 0;
}

1 Answer 1

1

The %s format specifier for printf is only for C-style strings. C-style strings have a nul (zero) to mark their end. Your code never marks the end of entries in words with a terminator, so you cannot pass words to printf through %s.

Your final for loop goes through every entry -- even ones that you never initialized. That's going to print an awful lot of garbage and possibly even cause a crash as it will also pass things that aren't C-style strings (because they were never initialized at all) to printf through %ss.

Sign up to request clarification or add additional context in comments.

2 Comments

I have fixed the null terminator issue with my string but why would I need initialise when I have copied the values into the strict in the code block above the final for loop
You just set wordList[i] equal to the return value from malloc. You never assign wordList[i]->words any value at all, so it doesn't contain a C-style string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.