0

Why I get on Segmentation fault for this code ?

#include <stdio.h>
void main(){
    int *ptr;
    *ptr =24;
     if(*ptr < 12)
        printf("************** 1\n");
     if(*ptr > 64)
      printf("************** 2");
 }

update: I need to compare the value of pointer *ptr =24; with the if statement, there is no output!

 int data = 24;
    int *ptr =&data;
     if(*ptr < 12){
    printf("************** 1\n");
    }
   if(*ptr > 64)
  {
      printf("************** 2");
  }
lena
  • 730
  • 2
  • 11
  • 23
  • `ptr =24;` You are using `24` as an address. Obviously that is not a valid memory location and hence dereferencing it results in Undefined Behaviour. What exactly are you trying to do and why do you think that should work? – kaylum Mar 09 '22 at 10:18
  • The first part of the answer in the linked duplicate answers the vast majority of these kind of questions: _"A pointer is a special type of variable, which can only contain an address of another variable. It cannot contain any data. You cannot "copy/store data into a pointer" - that doesn't make any sense. You can only set a pointer to point at data allocated elsewhere."_ – Lundin Mar 09 '22 at 10:20
  • I need to compare the value of pointer *ptr =24; with the if statement – lena Mar 09 '22 at 10:20
  • Maybe read what I just wrote instead. – Lundin Mar 09 '22 at 10:43

0 Answers0