Home > Enterprise >  Getting segmentation fault while trying to use pointers
Getting segmentation fault while trying to use pointers

Time:11-16

Swapping two nos. by the use of pointers.

int main()
{
    int *a;
    int *b;
    a = 3;
    b = 5;
    *a=b;
    *b=a;
    printf("a=%d\n b=%d\n", *a, *b);

It is showing Segmentation fault at line "*a=b(7)"

I tried to introduce a new variable and assign it to *a and *b but it still shows the same error.

CodePudding user response:

The compilation error you are getting seems pretty descriptive. "assigment to 'int*' from 'int' makes pointer from integer without a cast." indicates that you are trying to assign an int to an int *, which is precisely what you are trying in the line a = 3. If a were set to the address of an int, you could assign to it with *a = 3, and you could initialize a with something like int x; int *a = &x;, but writing a = 3 is attempting to assign an int to an int *, which the compiler warns you about.

You are probably looking for something like:

#include <stdio.h>

int
main(void)
{
    int a, b;
    int *ap = &a;
    int *bp = &b;
    a = 3;
    b = 5;
    printf("a=%d b=%d\n", a, b);
    int tmp = a;
    *ap = b;
    *bp = tmp;
    printf("a=%d b=%d\n", a, b);
}

CodePudding user response:

A pointer is a data type that "points" to a memory address, so for example if you have int x = 12, you can set int *p = x, and p is a pointer to the memory value of x (where x is stored in the computer). You set your pointers to constant integers, which doesn't make much sense. The other problem is the *, which is confusing when you are new to pointers. The * is how you initialize pointers, which you used correctly. The other use of * is to dereference a pointer. In the previous example, pointer p points to x's memory address. If we dereference p, then p is set to the value of whatever is at the memory address of x, in this case, 12. If you don't want to dereference a pointer (set the pointer to the value which it is pointing at), then don't use the *. If you want to point a pointer to another pointer, you have to initialize the pointer as **.

  • Related