|
-
December 29th, 2005, 02:47 PM
#1
newbie C question
I'm still a bit new to C, and attempting to master pointers. I have a function that allocates a 2d pointer array, like so:
Code:
int main(int argc, char *argv[]){
float **data;
alloc_data(&data);
}
void alloc_data(float ***data){
int i, nx, ny;
float **tmp;
nx = 3;
ny = 3;
tmp = (float **) calloc(nx, sizeof(float *));
for (i=0; i<nx; i++)
tmp[i] = (float *) calloc(ny, sizeof(float));
*data = tmp;
}
works just fine, but how can I allocate data without having to alloc tmp and have data point to tmp? For example, if I do:
Code:
*data = (float **) calloc(nx, sizeof(float *));
for (i=0; i<nx; i++)
*data[i] = (float *) calloc(ny, sizeof(float));
it doesn't work as I expect - what am I missing here?
thanks for any help.
-Tim
-
December 29th, 2005, 02:54 PM
#2
Re: newbie C question
[] has higher precedence than *, so the compiler interperets *data[i] as *(data[i]) when what you want is (*data)[i].
-
December 29th, 2005, 02:57 PM
#3
Re: newbie C question
Aha! Thanks! Now I'll go learn my C precedence rules. 
-Tim
-
December 29th, 2005, 03:02 PM
#4
Re: newbie C question
Another way is to pass the double pointer as a reference:
Code:
void alloc_data(float** &data) // pass reference (to the double pointer)
{
int i, nx, ny;
nx = 3;
ny = 3;
data = (float **) calloc(nx, sizeof(float *));
for (i=0; i<nx; i++)
data[i] = (float *) calloc(ny, sizeof(float));
}
int main(int argc, char *argv[])
{
float **data;
alloc_data(data);
}
- petter
-
December 29th, 2005, 03:09 PM
#5
Re: newbie C question
I agree with Wildfrog; that is the method of choice in my opinion
-
December 29th, 2005, 03:28 PM
#6
Re: newbie C question
 Originally Posted by Eli Gassert
I agree with Wildfrog; that is the method of choice in my opinion 
The only problem: C++ might understand references, but C does not. The OP stated to use C so your solution won't help him at all.
-
December 29th, 2005, 03:40 PM
#7
Re: newbie C question
 Originally Posted by NoHero
The only problem: C++ might understand references, but C does not. The OP stated to use C so your solution won't help him at all.
Oh, I thought he was just another lazy C++ programmer (and dropped the obvious ++)
Well, then I'd go for evilsaltines solution:
Code:
void alloc_data(float*** data) // pass pointer (to the double pointer)
{
int i, nx, ny;
nx = 3;
ny = 3;
*data = (float **) calloc(nx, sizeof(float *));
for (i=0; i<nx; i++)
(*data)[i] = (float *) calloc(ny, sizeof(float));
}
int main(int argc, char *argv[])
{
float **data = 0;
alloc_data(&data);
}
- petter
-
December 29th, 2005, 04:30 PM
#8
Re: newbie C question
The code is currently in C, but I am fiddling a bit with C++ as well, so thanks for pointing out the handy pointer reference trick for C++.
-Tim
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|