Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

mem allocation inside function 1

Status
Not open for further replies.

zub44

Programmer
Dec 18, 2003
7
US
I would like to pass a pointer to a function and have it allocate mememory for this pointer inside the function.


#include <stdio.h>
#include <stdlib.h>

void f (double **A);

main()
{
double *A;

f(A); /*or f(&A) ?? */
}

void f (double **A)
{
A = malloc(10*sizeof(double*) );
for (i = 0; i < N; i++)
A = malloc(10*sizeof(double) );
}


I understand that you can make memory allocation functions that can return a pointer. e.g.

double **Allocate_2D_Matrix (int N, int M)
{
int i;
double **A;

A = malloc(N*sizeof(double*) );
for (i = 0; i < N; i++)
A = malloc(M*sizeof(double) );
return A;
}

However, I would like f to do many other things such as reading in data. Thanks.
 
Well your first example is easier to write as a function returning a pointer.
Code:
#include <stdio.h>
#include <stdlib.h>

#define N 20

double **f (void);

int main()
{
   double **A = f();
   return 0;
}

double **f (void)
{
    double **A = malloc(N*sizeof(*A) );
    int i;
    for (i = 0; i < N; i++)
        A[i] = malloc(10*sizeof(*A[i]) );
    return A;
}

You could write it as
Code:
void f ( double ***A );
f(&A);
But that just creates an extra level of indirection all over the code.

> I would like f to do many other things such as reading in data
Not a problem - you can fill the allocated memory with data either way.

--
 
Im not sure why the following code will not work. I get a segmentation fault when *A is assigned to 1.0 inside F.


#include <stdio.h>
#include <stdlib.h>

#define N 5

void F (double **A);

main()
{
int i;
double *A;

F(&A);

for (i = 0; i < N; i++)
printf(&quot;%5f &quot;, A);
}

void F (double **A)
{
int i;

*A = malloc(N*sizeof(double) );

for (i = 0; i < N; i++)
*A = 1.0;
}
 
have you tried using

double **A;

instead of

double *A;

and sending the variable not the address?

-Sean
 
Please remember to use the [ignore]
Code:
[/ignore] tags when posting code
Code:
[i]
plays havoc with the formatting

Recall my previous example
Code:
double **f (void)
{
    double **A = malloc(N*sizeof(*A) );
    int i, j;
    for (i = 0; i < N; i++) {
        A[i] = malloc(10*sizeof(*A[i]) );
        for ( j = 0 ; j < 10 ; j++ ) {
            A[i][j] = 1.0;
        }
    }
    return A;
}


> *A = 1.0;
I'm guessing you did
Code:
*A[i]
It would work better if you did
Code:
(*A)[i]

--
 
That did it. (*A) instead of *A. I copied and pasted the code so the []'s must not of shown up.

Thanks again.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top