473,473 Members | 2,196 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

How to pass a pointer from a function to an other??

momotaro
357 Contributor
am working with pointers in function A and need them to be accessible for function B

the function B seems to not have the same values
plz help
May 4 '09 #1
22 2604
RRick
463 Recognized Expert Contributor
I'm not sure of your situation. Are you passing pointers from A to B? B to A? A and B? Each situation has it own hazards to watch for.

A better description and a code snippet would help.
May 5 '09 #2
unauthorized
81 New Member
Generally, if two functions need to share a lot of data, the best solution is to make them a C++ class.

If you are using C, you could also create a structure to host a bunch of parameters, therefore simplifying parameter passing.

Expand|Select|Wrap|Line Numbers
  1. struct myStruct {
  2.      int* p1;
  3. }
  4.  
  5. // a very inefficient way to count to 100
  6. // we assume p1 is initialized here
  7. void func1(myStruct s)
  8. {
  9.      cout << (*s.p1)++;
  10.      if(*s.p1 == 100) return;
  11.      else func1(s);
  12. }
Now there are complications when writing runtime libraries and changing structure layout, but if you are, you should know it.

You can't share locals between functions in any other way.
However, if you only have two funcs, you may consider merging them into one to reduce memory overhead.
May 5 '09 #3
weaknessforcats
9,208 Recognized Expert Moderator Expert
Having the pointers in function A available in function B takes two forms:

1) Function B does not change the value of the pointer in function A.

In this case, just pass the pointer using a pointer argument in function B. This will make a copy of the pointer in function A and that allows function B to use the address inside that pointer.

2) Function B needs to change the value of the pointer in function A

In this case, you pass the address of the pointer in function A to function B using a pointer-to-pointer argument in function B. Any changes made in function B by dereferencing the pointer-to-pointer argument will be made in function A.
May 5 '09 #4
donbock
2,426 Recognized Expert Top Contributor
What is the calling-hierarchy relationship between functions A and B?
  • Does function A call function B directly?
  • Are functions A and B called by the same caller?
  • Something else?
May 5 '09 #5
momotaro
357 Contributor
function A and B both are called from the main

void A(ptr *max, ptr*min);

void B(ptr *max, ptr*min);

need the two pointers to be accessible in the B function for proccessing

thx
May 7 '09 #6
unauthorized
81 New Member
I don't get it. Shouldn't this be what you want:

Expand|Select|Wrap|Line Numbers
  1. int main(int argc, char* argv[])
  2. {
  3.      ptr* max;
  4.      ptr* min;
  5.  
  6.     // TODO: initialize max and min
  7.  
  8.      A(max, min);
  9.      B(max, min);
  10. }
The above code will make the data pointed by max and min available to both functions so, after A modifies the data, B will have access to the modified data.

Or are you trying to change the pointer's address itself? In that case, you'd have to do this:
Expand|Select|Wrap|Line Numbers
  1. A(ptr** myptr)
  2. {
  3.       ptr* newptr;
  4.       // TODO: initialize newptr
  5.       *myptr = &newptr;
  6. }
  7.  
  8. int main(int argc, char* argv[])
  9. {
  10.      ptr someVariable;
  11.      ptr* changeme = &someVariable;
  12.  
  13.      A(&changeme);    
  14.  
  15.     // Now changeme will contain the address of newptr from A,
  16.     // and not the address of someVariable!
  17. }
May 7 '09 #7
momotaro
357 Contributor
btw my data is two arrays
May 7 '09 #8
weaknessforcats
9,208 Recognized Expert Moderator Expert
Passsing a function pointer is just like passing a regular pointer. Your function argument just needs to be a function pointer.

This function:
Expand|Select|Wrap|Line Numbers
  1. void A(ptr *max, ptr*min);
can be passed as a pointer to a function with this argument:

Expand|Select|Wrap|Line Numbers
  1. void MyFunc(void (*)(ptr *max, ptr*min));
Then you call MyFunc by:

Expand|Select|Wrap|Line Numbers
  1. MyFunc(A);
In fact, you can use any function as the argument provided that your function has two ptr* arguments and returns void.
May 7 '09 #9
donbock
2,426 Recognized Expert Top Contributor
Does this look like what you're trying to do?
Expand|Select|Wrap|Line Numbers
  1. static void A(T *max, T *min);
  2. static void B(T *max, T *min);
  3.  
  4. int main(void) {
  5.    T max[N];
  6.    T min[N];
  7.    A(max, min);
  8.    B(max, min);
  9.    ...
  10. }
  11.  
  12. static void A(T *max, T *min) { ... }
  13. static void B(T *max, T *min) { ... }
Where N is the number of elements in the arrays and T is the type of each entry in the arrays. Any changes that A and B make to the max and min arrays will be visible to main.

By the way, it is generally considered a good idea when passing arrays to a function to also pass the array size:
Expand|Select|Wrap|Line Numbers
  1. static void A(T *max, T *min, size_t nelem);
  2. static void B(T *max, T *min, size_t nelem);
  3.  
  4. int main(void) {
  5.    ...
  6.    A(max, min, N);
  7.    B(max, min, N);
  8.    ...
  9. }
We wouldn't have to guess at what you're trying to do if you gave us more information.
May 7 '09 #10
donbock
2,426 Recognized Expert Top Contributor
When passing pointers around you need to be careful that you don't use a pointer after the thing being pointed to ceases to exist. For instance, the following code demonstrates that mistake. When function B is called, p points to freed memory. Something bad will happen.
Expand|Select|Wrap|Line Numbers
  1. void A(int *p);
  2. void B(int *p);
  3.  
  4. int main(void) {
  5.    int *p;
  6.    if (<something>) {
  7.       int a;
  8.       p = &a;
  9.       A(p);
  10.    } else {
  11.       int b;
  12.       p = &b;
  13.       A(p);
  14.    }
  15.    B(p);
  16. }
May 7 '09 #11
momotaro
357 Contributor
This is exactly it !!!

The function B in my case has irrelevant data passed through the two pointers
May 7 '09 #12
momotaro
357 Contributor
well here is the whole picture:
ma trying to stay as modular as possible my main looks like this:

main()
{
A();
B();
.....
}

and there is all kind of pointers going forthand back between the functions

the problem is those pointers seems to not existe outside the function where they are treted the first time

plz help
May 7 '09 #13
Banfa
9,065 Recognized Expert Moderator Expert
@momotaro
No your main does not look like that. This example has NO pointers so your question is not relevant to it. You have several people in this thread who I am sure could provide you the answer you require if you would explain your problem accurately but you persist in not posting proper examples of what you are trying to do. The experts and moderators ability to answer your question is limited by the amount of information you provide them about the actual problem you are having and frankly for most of this thread you have left them guess what the problem you are having might be.

I have been following this thread and TBH if I were the Experts/Moderators here I would be quite frustrated by now.

Please post a proper example of your problem, that is a code snippet cut down the the minimum amount of code required to demonstrate your problem that either compiles or demonstrates the compiler errors you need help with.

Banfa
Adminsitrator
May 7 '09 #14
momotaro
357 Contributor
The main:
Expand|Select|Wrap|Line Numbers
  1. #include "common.h"
  2. #include "Choix des Armes.h"
  3.  
  4. #define MAX_SIZE 10000
  5.  
  6. void main()
  7. {
  8.     Monstre Squelettique[MAX_SIZE], Grassouillet[MAX_SIZE];
  9.     Eppee eppeeArr[MAX_SIZE];
  10.     int nbrEppee;
  11.     int *longestMonstre, *largestMonstre, *nbrSquelettique = 0, *nbrGrassouillet = 0;
  12.     int oneEppee[MAX_SIZE], twoEppee[MAX_SIZE];
  13.     do
  14.     {
  15.         MonstreFill(Squelettique, Grassouillet, nbrSquelettique, nbrGrassouillet);
  16.         //MaxLongMaxLargMonstre(Squelettique, Grassouillet, longestMonstre, largestMonstre);
  17.         //nbrEppee = EppeeFill(eppeeArr);
  18.         //CandidateEppee(oneEppee, twoEppee, longestMonstre, largestMonstre, nbrSquelettique, nbrGrassouillet);
  19.         test(Squelettique, Grassouillet, nbrSquelettique, nbrGrassouillet);
  20.         //EppeeElue(monstreArr, eppeeArr);
  21.     }while(UserSaysYes());
  22. }

The two functions:

Expand|Select|Wrap|Line Numbers
  1. #include "common.h"
  2. #include "Choix des Armes.h"
  3.  
  4.  
  5. void MonstreFill(Monstre *Squelettique, Monstre *Grassouillet, int *nbrSquelettique, int *nbrGrassouillet)
  6. {
  7.     int i, j, nbrMonstre, monstreType, monstreTaille;
  8.     printf("a l interieure de MONSTRE FILL\n");
  9.     do
  10.     {
  11.         puts("Nombre de monstre ?");
  12.         scanf("%d", &nbrMonstre);
  13.  
  14.     }while(nbrMonstre < 1 || nbrMonstre > 10000);
  15.  
  16.     //initialisation
  17.  
  18.     for(i = 0; i < nbrMonstre; i++)
  19.     {
  20.         Squelettique[i].type = -1;
  21.         Squelettique[i].taille = -1;
  22.  
  23.         Grassouillet[i].type = -1;
  24.         Grassouillet[i].taille = -1;
  25.     }
  26.  
  27.  
  28.     for(i = 0, j = 0; i < nbrMonstre - j, j < nbrMonstre - i; i++, j++)
  29.     {
  30.         do
  31.         {
  32.         puts("0->grand monstre, 1->petit monstre? largeur(petit monstre), longueur(grand monstre)?");
  33.         scanf("%d %d", &monstreType, &monstreTaille);
  34.  
  35.         /*nbrSquelettique = 0;
  36.         nbrGrassouillet = 0;*/
  37.  
  38.         }while(monstreType != 1 && monstreType != 0);
  39.  
  40.         switch (monstreType)
  41.         {
  42.         case 0:
  43.             Squelettique[i].taille = monstreTaille;
  44.             Squelettique[i].type = 0;
  45.             j--;
  46.             break;
  47.         case 1:
  48.             Grassouillet[j].taille = monstreTaille;
  49.             Grassouillet[j].type = 1;
  50.             nbrGrassouillet++;
  51.             i--;
  52.             break;
  53.         default: 
  54.             puts("If you are reading this you don't existe !!!");
  55.         }
  56.     }
  57.     nbrSquelettique = i;
  58.     nbrGrassouillet = j;
  59.     printf("%d %d", nbrSquelettique, nbrGrassouillet);
  60.     printf("SORTIE DE MONSTRE FILL\n");
  61. }

Expand|Select|Wrap|Line Numbers
  1. #include "common.h"
  2. #include "Choix des Armes.h"
  3.  
  4. void test(Monstre *Squelettique, Monstre *Grassouillet, int *nbrSquelettique, int *nbrGrassouillet)
  5. {
  6.     printf("%d %d", nbrSquelettique, nbrGrassouillet); // here wrong results!!!
  7.     /*int i;
  8.  
  9.     puts("Squelettique");
  10.     for(i = 0; i < nbrSquelettique; i++)
  11.         printf("%d\n", &Squelettique[i].taille);
  12.  
  13.     puts("Grassouillet");
  14.     for(i = 0; i < nbrGrassouillet; i++)
  15.         printf("%d\n", &Grassouillet[i].taille);*/
  16. }
and here is my defined types:
Expand|Select|Wrap|Line Numbers
  1. #include "common.h"
  2.  
  3. typedef struct eppee{
  4.     int eppeeID;
  5.     int largeur;
  6.     int longueur;
  7. } Eppee;
  8.  
  9.  
  10. typedef struct monstre{
  11.     int type,
  12.         taille;
  13. }Monstre;
  14.  
  15.  
  16. void MonstreFill(Monstre *, Monstre *, int *, int *); // YES
  17.  
  18. int EppeeFill(Eppee *);
  19.  
  20. void MaxLargMaxLongMonstre(Monstre *, Monstre *, int *, int *);
  21.  
  22. void CandidateEppee(Eppee *, int *, int *, int *, int *);
  23.  
  24. void Eppeeelue(int *);
  25.  
  26. void test(Monstre *, Monstre *, int *, int *);
May 7 '09 #15
Banfa
9,065 Recognized Expert Moderator Expert
Expand|Select|Wrap|Line Numbers
  1. void main()
  2. {
  3. ...
  4. }
int main()

Always, every time. void is a extension supported by a few compilers but on any other system it is undefined behaviour.

Expand|Select|Wrap|Line Numbers
  1. void MonstreFill(Monstre *Squelettique, Monstre *Grassouillet, int *nbrSquelettique, int *nbrGrassouillet)
  2. {
  3.     <snip>
  4.  
  5.         switch (monstreType)
  6.         {
  7.         case 0:
  8.             Squelettique[i].taille = monstreTaille;
  9.             Squelettique[i].type = 0;
  10.             j--;
  11.             break;
  12.         case 1:
  13.             Grassouillet[j].taille = monstreTaille;
  14.             Grassouillet[j].type = 1;
  15.             nbrGrassouillet++;
  16.             i--;
  17.             break;
  18.         default: 
  19.             puts("If you are reading this you don't existe !!!");
  20.         }
  21.     }
  22.     nbrSquelettique = i;
  23.     nbrGrassouillet = j;
  24. }
Everywhere you access nbrSquelettique and nbrGrassouillet you write the local pointer value, you don't use the pointer to access the external variable in the calling function so when it is passed to the next function no data has been changed. You want the syntax

(*nbrGrassouillet)++;
or
*nbrSquelettique = i;

Expand|Select|Wrap|Line Numbers
  1. void test(Monstre *Squelettique, Monstre *Grassouillet, int *nbrSquelettique, int *nbrGrassouillet)
  2. {
  3. /* Same error in this function too */
  4. }
May 8 '09 #16
momotaro
357 Contributor
it was the first thing Iu wrote but gave me a run time error!!!
don't know y???
May 8 '09 #17
momotaro
357 Contributor
this is the error:

Unhandled exception at 0x00f219a5 in Choix des Armes.exe: 0xC0000005: Access violation reading location 0x00000000.
May 8 '09 #18
momotaro
357 Contributor
normally this error emergs when you are trying to access a non memory allocated pointer !!!!
May 8 '09 #19
momotaro
357 Contributor
using visual studio 2008 pro
May 8 '09 #20
scruggsy
147 New Member
@momotaro
Yes, exactly.
In your main routine you did this:
Expand|Select|Wrap|Line Numbers
  1.     int *longestMonstre, *largestMonstre, *nbrSquelettique = 0, *nbrGrassouillet = 0;
creating 4 pointers to int initialized to zero.
You never assign a valid address to nbrSquelettique or nbrGrssouillet in your code, so *nbrSquelettique is an error - the pointer doesn't point to anything.
In MonstreFill() you do this:
Expand|Select|Wrap|Line Numbers
  1.      nbrSquelettique = i;
  2.     nbrGrassouillet = j;
assigning integer values to pointer variables. That's not valid.

It seems to me that what you want to do is this:
Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.   int nbrSquelettique, nbrGrssouillet = 0;  // these are int, not int*
  4.   MonstreFill(blah, blah, &nbrSquelettique, &nbrGrssouillet);  // pass the ADDRESSES of your ints
  5.   // ...
  6. }
  7.  
  8. void MonstreFill(blah, blah, int* nbr1, int* nbr2)
  9. {
  10.   // ...do stuff
  11.   *nbr1 = i;  // now nbrSquelettique's value has changed
  12.   *nbr2 = j;  // same for nbrGrassouillet
  13. }
May 8 '09 #21
momotaro
357 Contributor
thank you that is working!!
May 8 '09 #22
Banfa
9,065 Recognized Expert Moderator Expert
See I said things would get fixed more quickly if you provided a proper example and explanation :D
May 8 '09 #23

Sign in to post your reply or Sign up for a free account.

Similar topics

110
by: Mr A | last post by:
Hi! I've been thinking about passing parameteras using references instead of pointers in order to emphasize that the parameter must be an object. Exemple: void func(Objec& object); //object...
14
by: Abhi | last post by:
I wrote a function foo(int arr) and its prototype is declared as foo(int arr); I modify the values of the array in the function and the values are getting modified in the main array which is...
10
by: Robert Dailey | last post by:
Hi, I noticed in Python all function parameters seem to be passed by reference. This means that when I modify the value of a variable of a function, the value of the variable externally from the...
6
by: lisp9000 | last post by:
I've read that C allows two ways to pass information between functions: o Pass by Value o Pass by Reference I was talking to some C programmers and they told me there is no such thing as...
11
by: venkatagmail | last post by:
I have problem understanding pass by value and pass by reference and want to how how they are or appear in the memory: I had to get my basics right again. I create an array and try all possible...
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...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
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,...
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 ...

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.