Home > Software design >  Why this code giving me a segmentation fault?
Why this code giving me a segmentation fault?

Time:12-27

#include <stdio.h>
int main()
{
    int i,a;
    int* p;
    p=&a;
    for(i=0;i<=10;i  )
    {
        *(p i)=i;
        printf("%d\n",*(p i));
    }
    return 0;
}

I tried to assign numbers from 0 to 10 in a sequence memory location without using an array.

CodePudding user response:

a is only an integer. not an array.

you need to declare it differently:

 int i, a[10];

CodePudding user response:

You can not. Memory of int is 4 bytes and you can store only single number in that memory.

for int: -2,147,483,647 to 2,147,483,647

for unsigned int: 0 to 4, 294, 967 295

There are other types you can use with different sizes, but if you want to put different numbers into one variable you need to use array. int arr[10]; arr[0] = 0; arr[1] = 5; something like this.

  • Related