passing and filling pointers, a C question

Discussion in 'Mac Programming' started by vgoklani, Nov 20, 2006.

  1. vgoklani macrumors regular

    vgoklani

    Joined:
    Jul 2, 2004
    #1
    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.
     
  2. weg macrumors 6502a

    weg

    Joined:
    Mar 29, 2004
    Location:
    nj
    #2
    &key denotes the address of the variable key, i.e. *(&key) corresponds to key again.
     
  3. vgoklani thread starter macrumors regular

    vgoklani

    Joined:
    Jul 2, 2004

Share This Page