Home > Net >  how to initialize a vector of unknown size the value 0
how to initialize a vector of unknown size the value 0

Time:09-11

Im doing this exercise that requires to read a string and print out the length of each word. Thing is supposedly we arent supposed to know how many words this sting has.

In this case for example its 4

viVa la VIDA loca

This is the part of the code i have made.

int textStats(char* filename);

int main()
{
    FILE*file;
    file=fopen("file","r");
    if(file==NULL)
    {
        printf("Error in opening the file ");
        exit(1);
    }
    textStats(file);
}

int textStats(char* filename)
{
    int i,j;

    int n=0;
    int N=20;
    char str[N];


    while(fscanf(filename,"%c",&str[n])!=EOF)
    {
        n  ;
    }
    for(i=0; i<n; i  )
    {
        printf("%c",str[i]);
    }
    
    i=j=0;
    int count[]={0};
    while(str[i]!='\0')
    {
        if(isalpha(tolower(str[i])))
        {
            count[j]  ;
        }
        if(isspace(str[i])|| str[i]=='\0')
        {
            j  ;
        }
        i  ;
    }

    for(i=0;i<j;i  )
    {
        printf("word %d with count %d\n",i 1,count[i]);
    }
}

What i dont understand why is it that if i initialize count[]={0} it will print errors but if i initialize it to count[]={0,0,0,0} it will return a correct value?

CodePudding user response:

Firstly, you don't need to store each word's length in an array. You can just print them out whenever you finish reading 1 word

{
    FILE*file;
    file=fopen("file","r");
    if(file==NULL)
    {
        printf("Error in opening the file ");
        exit(1);
    }
    textStats(file);
}

int textStats(char* filename)
{
    int i,j;

    int n=0;
    int N=20;
    char str[N];


    while(fscanf(filename,"%c",&str[n])!=EOF)
    {
        n  ;
    }
    for(i=0; i<n; i  )
    {
        printf("%c",str[i]);
    }
    
    i=j=0;
    int count=0;
    while(str[i]!='\0')
    {
        if(isalpha(tolower(str[i])))
        {
            count  ;
        }
        if(isspace(str[i])|| str[i]=='\0')
        {
            j  ;
            printf("word %d with count %d\n",j,count);
            count = 0;
        }
        i  ;
    }
}

If you really want to store each word's length inside an array, you can explore the use of dynamically growing array

CodePudding user response:

int count[]; is invalid, it's attempting to declare an array of incomplete size. int count[] = {0} creates an array matching the initializer list, in this case an array of 1 int items.

  •  Tags:  
  • c
  • Related