Re: Allocating a pointer?         


Author: Barry Schwarz
Date: Apr 30, 2008 18:53

On Wed, 30 Apr 2008 17:04:37 +0200, saneman sadf.com> wrote:
>mimus wrote:
>> On Wed, 30 Apr 2008 15:03:08 +0200, saneman wrote:
>>
>>> In the below code the last call to myprint does not work (gives a
>>> segmentation error).
>>>
>>> But I thought that pointer variables local in main (or any other
>>> function) would first be deleted when the calling function returns. Why
>>> does it give a segmentation fault?
>>>
>>>
>>>
>>> #include
>>> #include
>>>
>>> void myprint(double* a) {
>>> printf("number is = %%f\n",*a);
>>>
>>> }
>>>
>>>
>>>
>>> int main() {
>>>
>>> /* Working! (static allocation) */
>>> double d1 = 1.1;
>>> myprint(&d1);
>>>
>>> /* Working! (dynamic allocation) */
>>> double* d2 = (double*) malloc(sizeof(double*));
>>> *d2 = 2.2;
>>> myprint(d2);
>>>
>>> /* Not working! (why? main does not return!) */
>>> double* d3;
>>> *d3 = 3.3;
>>> myprint(d3);
>>>
>>>
>>> return 0;
>>>
>>> }
>>
>> Only three things I see:
>>
>> First, you shouldn't be declaring variables in the body of the program.
>>
>> Second, shouldn't your dynamic allocation of d2 use sizeof(double)?
>>
>> And third, you declare but don't set d3 _as a pointer_ before you use it
>> for indirection, wot I presume it's initialized to NULL and giving you
>> your segmentation fault:
>
>
>Ok so I need to make it point to something before setting the content?

You need to make it point to something before dereferencing the
pointer to do anything to that something.

Remove del for email
diggit! del.icio.us! reddit!