简体   繁体   中英

Why am i getting segmentation fault in C code?

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

int main()
{
    int t,i,rem,l[i],b[i];
    scanf("%d",&t);
    for (i=0;i<t;i++)
    {
        scanf("%d %d",&l[i],&b[i]);
    }

    for (i=0;i<t;i++)
    {
        if (l[i] > b[i])
        {
            rem = l[i]/b[i];
            rem +=1;
            printf("%d \n",rem);
        }
        else if (l[i] > b[i])
        {
            rem = b[i]/l[i];
            rem +=1;
            printf("%d \n",rem);
        }
        else 
        {
            printf("1 \n");
        }
    }

    return 0; 
}

Hi my code is getting compiled but not running due to a segmentation fault. Please help me in figuring out whether its become of some memory issue or scanf statements

Here:

int t,i,rem,l[i],b[i];

i is not initialized and you are creating arrays of size i (what's the value of i currently?). Arrays are of fixed size and it won't change when the value of i changes.

Fix the problem by changing

int t,i,rem,l[i],b[i];

to

int t, i, rem;

and add

int l[t], b[t]; /* You want arrays of `t` size */

after

scanf("%d",&t);

so that t gets initialized when the VLAs (Variable Length Arrays) are created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM