hello all

i have been writing the java code and new to C programing.I am very confused in point.i have the following code

#include<stdio.h>
main()
{
        int *ptr=50;
        printf("%d",*ptr);
        return 0;
}
~
~

why it is giving the segmentation fault.and when i print ptr then it gives value 50.and when i print &ptr it gives some long negative value.
Please explain all these three output so my doubts will be cleared.

int *ptr=50;

This is attempting to point ptr to address 50. Typically, you can only point to addresses within your process' address space, otherwise you'll get a segmentation fault. Java references are actually gimped pointers, which should give you an idea of how to use C pointers for basic object access. First you need a valid object, then you assign the address of that object to your pointer. Finally, you dereference the pointer to access the object:

#include <stdio.h>

int main(void)
{
    /*
        These two lines are the rough equivalent of 

        Integer p = new Integer(50);
    */
    int obj = 50;
    int *p = &obj;

    printf("%d\n", *p);

    return 0;
}
#include<stdio.h>

      main()

      {

      int *ptr=50;

      printf("%d",*ptr);

      return 0;

      }

your code is wrong becouse pointer variable just store Address of another variable so use anoter variable for the value of 50 ok sir

commented: If you don't know what you're doing, try not to confuse people by helping. -4

ya it's ok .thanks for clarification.

1.
#include<stdio.h>
2.
main()
3.
{
4.
int *ptr=50;
5.
printf("%d",*ptr);
6.
return 0;
7.
}
8.
~
9.
~
your code is wrong becouse pointer variable just store Address of another variable so use anoter variable for the value of 50 ok sir

YOUR always welcome boss ,any aanother question

Re: confused in pointer

You are getting segmentation fault right..?

Why because you are accessing the value from undefined area...?

First define some location for that pointer then point that value by using your pointer...

pointer variables are supposed to hold the address of compatible type of variables which are already declared.
pointers supposed to indicate value at that address.
You mentioned int *ptr=50. This is meaning less.
first declare int type of variable and assign the value to it.
Then pass the address of this variable to pointer variable.
Like
int a=10;
int *p;
p=&a;
Now the value can be accessed using a or *p.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.