Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

vgoklani

macrumors regular
Original poster
Jul 2, 2004
186
0
Hi,

I would like to do the following, create a pointer in main(), pass it as a function where it is filled with numbers, and then return the pointer. This is my code:

#include <stdio.h>

void function(double **key, double ten)
{
int i;

double *key1 = malloc(sizeof(double)*ten);

for(i = 0; i < ten; ++i)
key1 = i;

for(i = 0; i < ten; ++i)
printf("\nFUNCTION: #%f\n", key1);

*key = key1;
}

int main(int argc, char argv[])
{
double ten = 10;
double *key = NULL;
int i;

function(&key, ten);

for(i = 0; i < ten; ++i)
printf("\n#MAIN: %f\n", key);

}

My question is, why do I have to pass the address of key, ie: &key? Since key is a pointer, what does &key mean? (ie: key itself holds a memory address, and *key is the value stored in key, so what does &key mean?). If I pass key, ie: function(key, ...) I get a "bus error".

---

I should also add, that when I do the following:

#include <stdio.h>

double* function(double **key, double max)
{
int i;

double *key1 = malloc(sizeof(double)*max);

for(i = 0; i < max; ++i)
key1 = i;

for(i = 0; i < max; ++i)
printf("\nIn Main:#%f\n", key1);

return key1;
}

int main(int argc, char argv[])
{
double max = 10;
double *key = NULL;
int i;

double *key2 = function(&key, max);

for(i = 0; i < max; ++i)
printf("\nIn function:#%f\n", key2);

}

there is no reason to use a pointer to a pointer.
 

weg

macrumors 6502a
Mar 29, 2004
888
0
nj
Hi,

My question is, why do I have to pass the address of key, ie: &key? Since key is a pointer, what does &key mean? (ie: key itself holds a memory address, and *key is the value stored in key, so what does &key mean?). If I pass key, ie: function(key, ...) I get a "bus error".

&key denotes the address of the variable key, i.e. *(&key) corresponds to key again.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.