473,471 Members | 1,981 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

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 8763
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: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.