Hello, I need to allocate memory dynamically for arrays in FUNCTIONs
(Here for R), but I can not use that memory in my main function
Thank you so much

typedef float MYFLOAT;

//    or Called Standalone
#define MYPRINT printf
#define MYMAIN main

#include <string>
#include <cstdio>
#include <cctype>
#include <stdio.h>
#include <stdlib.h>

void MAKE(MYFLOAT *R)
{
    MYFLOAT RI[]={-1,4,3.34,4.78,5.23};
    
    R=new MYFLOAT [5];
    for(int i=0;i<5;i++)
        R[ i ]=RI[ i ];
    MYPRINT("R: %f %f\n",R[0],R[4]);
}

int MYMAIN()
{
  MYFLOAT *R;
        
    MAKE(R);
    
    MYPRINT("RI: %f %f\n",RI[0],RI[4]);
    MYPRINT("R: %f %f\n",R[0],R[4]);
    
    //  Memory Release
    delete []R;
    
    //  Outputs
	return 1;
}

<< moderator edit: added code tags: [code][/code] and other cleanup >>

Recommended Answers

All 2 Replies

I don't know that I fully understand your question. If you want to modify a pointer, in C you would pass a pointer to a pointer.

typedef float MYFLOAT;

//    or Called Standalone
#define MYPRINT printf
#define MYMAIN main

#include <string>
#include <cstdio>
#include <cctype>
#include <stdio.h>
#include <stdlib.h>

void MAKE(MYFLOAT **R)
{
    MYFLOAT RI[]={-1,4,3.34,4.78,5.23};
    
    (*R)=new MYFLOAT [5];
    for(int i=0;i<5;i++)
        (*R)[ i ]=RI[ i ];
    MYPRINT("R: %f %f\n",(*R)[0],(*R)[4]);
    MYPRINT("RI: %f %f\n",RI[0],RI[4]);
}

int MYMAIN()
{
  MYFLOAT *R;
        
    MAKE(&R);
    
    MYPRINT("R: %f %f\n",R[0],R[4]);
    
    //  Memory Release
    delete []R;
    
    //  Outputs
	return 1;
}

/* my output
R: -1.000000 5.230000
RI: -1.000000 5.230000
R: -1.000000 5.230000
*/

Someone will likely follow up with a better method for C++, but it's late for me...).

Hi rkarimi,
You should use reference variable to solve this problem.

typedef float MYFLOAT;

//    or Called Standalone
#define MYPRINT printf
#define MYMAIN main

#include <string>
#include <cstdio>
#include <cctype>
#include <stdio.h>
#include <stdlib.h>

void MAKE(MYFLOAT*[B]&[/B] R)
{
    MYFLOAT RI[]={-1,4,3.34,4.78,5.23};
    
    R=new MYFLOAT [5];
    for(int i=0;i<5;i++)
        R[ i ]=RI[ i ];
    MYPRINT("R: %f %f\n",R[0],R[4]);
	
}

int MYMAIN()
{
  MYFLOAT *R;
        
    MAKE(R);
    
    MYPRINT("R: %f %f\n",R[0],R[4]);
    //MYPRINT("RI: %f %f\n",RI[0],RI[4]);
    //RI is local to MAKE
    //  Memory Release
    delete []R;
    
    //  Outputs
	return 1;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.