473,324 Members | 2,254 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

Allocating memory for a pointer passed from another function

I'm sure this is a fairly basic question. I want a pointer in main()
to be passed to a function, and to allocate memory for the pointer in
the function, and then have it available to main after.

This does not work:

#include <stdio.h>

void func(float *a)
{
a = malloc(5*sizeof(float));
*(a+5) = 15.0f;
}

int main()
{
float *ptr;
func(ptr);
printf("%g\n",*(ptr+5)); // prints something other than 15
return 0;
}

This sort of makes sense, since I'm passing ptr as an argument. Is
there a way to pass ptr so that it behaves as expected? Or do I have
to do this?

#include <stdio.h>

float* func()
{
float *a = malloc(5*sizeof(float));
*(a+5) = 15.0f;
return a;
}

int main()
{
float *ptr;
ptr = func();
printf("%g\n",*(ptr+5));
return 0;
}
Thanks,
Adam
Jan 10 '08 #1
5 8756
On Jan 10, 9:10 pm, Adam Baker <adamb...@gmail.comwrote:
I'm sure this is a fairly basic question. I want a pointer in main()
to be passed to a function, and to allocate memory for the pointer in
the function, and then have it available to main after.

This does not work:

#include <stdio.h>

void func(float *a)
{
a = malloc(5*sizeof(float));
*(a+5) = 15.0f;

}

int main()
{
float *ptr;
func(ptr);
printf("%g\n",*(ptr+5)); // prints something other than 15
return 0;

}

This sort of makes sense, since I'm passing ptr as an argument. Is
there a way to pass ptr so that it behaves as expected?
Function arguments are always passed by value in C.

You can pass a pointer to a pointer instead:

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

void func(float **a)
{
*a = malloc(6 * sizeof **a);
if(*a)
*(*a+5) = 15.0f;
else {
fputs("No memory\n", stderr);
exit(EXIT_FAILURE);
}
}

int main(void)
{
float *ptr;
func(&ptr);
printf("%g\n", *(ptr+5));
free(ptr);
return 0;
}

(Note some other subtle difference from your code, too.)
Jan 10 '08 #2
Adam Baker wrote:
I'm sure this is a fairly basic question. I want a pointer in main()
to be passed to a function, and to allocate memory for the pointer in
the function, and then have it available to main after.

This does not work:

#include <stdio.h>

void func(float *a)
{
a = malloc(5*sizeof(float));
*(a+5) = 15.0f;
}

int main()
{
float *ptr;
func(ptr);
printf("%g\n",*(ptr+5)); // prints something other than 15
return 0;
}
This is essentially FAQ 4.8:

<http://c-faq.com/ptrs/passptrinit.html>


Brian

--
Please don't top-post. Your replies belong following or interspersed
with properly trimmed quotes. See the majority of other posts in the
newsgroup, or:
<http://www.caliburn.nl/topposting.html>
Jan 10 '08 #3
Adam Baker wrote:
>
I'm sure this is a fairly basic question. I want a pointer in main()
to be passed to a function, and to allocate memory for the pointer in
the function, and then have it available to main after.

This does not work:

#include <stdio.h>

void func(float *a) {
a = malloc(5*sizeof(float));
*(a+5) = 15.0f;
}

int main() {
float *ptr;
func(ptr);
printf("%g\n",*(ptr+5)); // prints something other than 15
return 0;
}

This sort of makes sense, since I'm passing ptr as an argument. Is
there a way to pass ptr so that it behaves as expected? Or do I have
to do this?
Of course not. float receives a, of type float*, by value. Any
changes are not visible in main. You want:

void func(float* *a) {
if (*a = malloc(5 * sizeof(float))
*(*a + 4) = 15.0f;
/* ^-- *a only holds indices 0 thru 4 */
}

and in main you call "func(&ptr);". Better would be to have func
return the value of a, eliminating all the double **, and making
the call "ptr = func(ptr);".

--
Chuck F (cbfalconer at maineline dot net)
<http://cbfalconer.home.att.net>
Try the download section.

--
Posted via a free Usenet account from http://www.teranews.com

Jan 11 '08 #4
On Jan 10, 1:27 pm, Francine.Ne...@googlemail.com wrote:
On Jan 10, 9:10 pm, Adam Baker <adamb...@gmail.comwrote:
I'm sure this is a fairly basic question. I want apointerin main()
to be passed to afunction, and to allocate memory for thepointerin
thefunction, and then have it available to main after.
This does not work:
#include <stdio.h>
void func(float *a)
{
a = malloc(5*sizeof(float));
*(a+5) = 15.0f;
}
int main()
{
float *ptr;
func(ptr);
printf("%g\n",*(ptr+5)); // prints something other than 15
return 0;
}
This sort of makes sense, since I'm passing ptr as anargument. Is
there a way to pass ptr so that it behaves as expected?

Functionarguments are always passed by value in C.

You can pass apointerto apointerinstead:

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

void func(float **a)
{
*a = malloc(6 * sizeof **a);
if(*a)
*(*a+5) = 15.0f;
else {
fputs("No memory\n", stderr);
exit(EXIT_FAILURE);
}

}

int main(void)
{
float *ptr;
func(&ptr);
printf("%g\n", *(ptr+5));
free(ptr);
return 0;

}

(Note some other subtle difference from your code, too.)

Another example is strcpy(char *p, const char *s); why
it is not strcpy(char **p,const char *s)?
Jan 15 '08 #5
henry <he**********@yahoo.comwrites:
On Jan 10, 1:27 pm, Francine.Ne...@googlemail.com wrote:
>On Jan 10, 9:10 pm, Adam Baker <adamb...@gmail.comwrote:
[...]
[attribution lost]
>Function arguments are always passed by value in C.

You can pass a pointer to a pointer instead:
[...]
>void func(float **a)
{
*a = malloc(6 * sizeof **a);
if(*a)
*(*a+5) = 15.0f;
else {
fputs("No memory\n", stderr);
exit(EXIT_FAILURE);
}
[...]
>
Another example is strcpy(char *p, const char *s); why
it is not strcpy(char **p,const char *s)?
Because strcpy doesn't need to modify the pointer to the target
string; it only modifies the content of the string itself.

--
Keith Thompson (The_Other_Keith) <ks***@mib.org>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jan 15 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: soni29 | last post by:
hi, i'm reading a c++ book and noticed that the author seems to allocate memory differently when using classes, he writes: (assuming a class called CBox exists, with member function size()): //...
37
by: Ben | last post by:
Hi, there. Recently I was working on a problem where we want to save generic closures in a data structure (a vector). The closure should work for any data type and any method with pre-defined...
4
by: Sameer | last post by:
Hello Group, This is one problem in programming that is troubling me. there is a segmentation fault just before creating memory to a structure ..i.e, just after the "allocating memory "...
15
by: fix | last post by:
Hi all, I am writing a program using some structs, it is not running and I believe it is because there's some memory leak - the debugger tells me that the code causes the problem is in the malloc...
5
by: AK | last post by:
I'm writing a Windows Forms application in C++.NET. I've defined function F which takes 2 arguments a & b. I need to use the pointer of F inside another function G & I can't figure out how to do...
3
by: dice | last post by:
Hi, In order to use an external api call that requires a function pointer I am currently creating static wrappers to call my objects functions. I want to re-jig this so I only need 1 static...
17
by: Mike | last post by:
Hello, I have following existing code. And there is memory leak. Anyone know how to get ride of it? function foo has been used in thousands places, the signature is not allowed to change. ...
6
by: Praetorian | last post by:
This is actually 2 questions: The first one: I have a function (FuncA) calling another (FuncB) with a set of parameters which also includes an int * initialized to NULL before the call. Now...
1
by: aspire | last post by:
All, I am trying to allocate memory to a pointer to an array in another function, but i am not getting a successful compilation. I am getting error on a line shown below in code. ------------...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.