Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,939 questions

51,876 answers

573 users

How to define, input value and print srtuct array that include char * field in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define LEN 3
#define MAX_WORD_LEN 64

struct words_statistic 
{ 
    char *word; 
    int count_letters;
};

void print_struct(struct words_statistic ws[]);

int main(void)
{
    struct words_statistic ws[LEN];  
    char input[MAX_WORD_LEN];
    int i, word_len;
        
    for (i = 0; i < LEN; i++)
    {
        printf("Enter a word: ");
        gets(input);
        word_len = strlen(input);
        ws[i].word = (char *)malloc(word_len + 1);
        strcpy(ws[i].word, input);
        ws[i].count_letters = word_len;
    }
    
    print_struct(ws);
    
    for (i = 0; i < LEN; i++)
         free(ws[i].word);
    
    return 0;
}
void print_struct(struct words_statistic ws[])
{
    for (int i = 0; i < LEN; i++)
        printf("word: %s count: %d\n", ws[i].word, ws[i].count_letters);
    
}



/*
run:
 
Enter a word: aaa
Enter a word: ccccccccccccccc
Enter a word: qq
word: aaa count: 3
word: ccccccccccccccc count: 15
word: qq count: 2

*/

 



answered Nov 30, 2015 by avibootz
edited Nov 30, 2015 by avibootz
...