Expression must have a constant value when trying to create a string

1.4k views Asked by At

I have a file which I want 20% the length of his string, so I first found the full length of his and then found the 20%, now I want to create a string which it's size is that 20%. I wrote this part of code:

int findres=0;
    int len, partlen;
    FILE *fp;
    if ((fopen_s(&fp, fname, "rb")) != NULL)
    {
        return(-1);
    }
    fseek(fp, 0, SEEK_END);
    len = ftell(fp);
    partlen = (len * 20) / 100;
    char temp[partlen];
    while ((fgets(temp, partlen, fp)) != NULL)
    {
        if ((strstr(temp, str)) != NULL)
        {
            fprintf(fs, "%s INFECTED\n", fname);
            findres++;
        }
    }

Now' it won't let me compile because it says I can't put partlen as the size of temp, because partlen is not constant, I couldn't figure out a way to fix this.

1

There are 1 answers

4
Hsyn On

In C, the storage of an array is allocated in compile time and it is located to the stack section of the executable file. The size of the array in your code is determined in the run-time, therefore; it is an error.

You have to use dynamic memory allocation functions which are malloc,calloc and realloc in standarts.

char *pStr; /* A pointer to keep the start address of the allocated memory in run-time */
pStr = malloc( sizeof(char) * partlen );

After that you must control the return value of the malloc.