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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • momotaro
    Contributor
    • Sep 2006
    • 357

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

    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
  • RRick
    Recognized Expert Contributor
    • Feb 2007
    • 463

    #2
    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.

    Comment

    • unauthorized
      New Member
      • May 2009
      • 81

      #3
      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.

      Code:
      struct myStruct {
           int* p1;
      }
      
      // a very inefficient way to count to 100
      // we assume p1 is initialized here
      void func1(myStruct s)
      {
           cout << (*s.p1)++;
           if(*s.p1 == 100) return;
           else func1(s);
      }
      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.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        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.

        Comment

        • donbock
          Recognized Expert Top Contributor
          • Mar 2008
          • 2427

          #5
          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?

          Comment

          • momotaro
            Contributor
            • Sep 2006
            • 357

            #6
            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

            Comment

            • unauthorized
              New Member
              • May 2009
              • 81

              #7
              I don't get it. Shouldn't this be what you want:

              Code:
              int main(int argc, char* argv[])
              {
                   ptr* max;
                   ptr* min;
              
                  // TODO: initialize max and min
              
                   A(max, min);
                   B(max, min);
              }
              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:
              Code:
              A(ptr** myptr)
              {
                    ptr* newptr;
                    // TODO: initialize newptr
                    *myptr = &newptr;
              }
              
              int main(int argc, char* argv[])
              {
                   ptr someVariable;
                   ptr* changeme = &someVariable;
              
                   A(&changeme);    
              
                  // Now changeme will contain the address of newptr from A,
                  // and not the address of someVariable!
              }

              Comment

              • momotaro
                Contributor
                • Sep 2006
                • 357

                #8
                btw my data is two arrays

                Comment

                • weaknessforcats
                  Recognized Expert Expert
                  • Mar 2007
                  • 9214

                  #9
                  Passsing a function pointer is just like passing a regular pointer. Your function argument just needs to be a function pointer.

                  This function:
                  Code:
                  void A(ptr *max, ptr*min);
                  can be passed as a pointer to a function with this argument:

                  Code:
                  void MyFunc(void (*)(ptr *max, ptr*min));
                  Then you call MyFunc by:

                  Code:
                  MyFunc(A);
                  In fact, you can use any function as the argument provided that your function has two ptr* arguments and returns void.

                  Comment

                  • donbock
                    Recognized Expert Top Contributor
                    • Mar 2008
                    • 2427

                    #10
                    Does this look like what you're trying to do?
                    Code:
                    static void A(T *max, T *min);
                    static void B(T *max, T *min);
                    
                    int main(void) {
                       T max[N];
                       T min[N];
                       A(max, min);
                       B(max, min);
                       ...
                    }
                    
                    static void A(T *max, T *min) { ... }
                    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:
                    Code:
                    static void A(T *max, T *min, size_t nelem);
                    static void B(T *max, T *min, size_t nelem);
                    
                    int main(void) {
                       ...
                       A(max, min, N);
                       B(max, min, N);
                       ...
                    }
                    We wouldn't have to guess at what you're trying to do if you gave us more information.

                    Comment

                    • donbock
                      Recognized Expert Top Contributor
                      • Mar 2008
                      • 2427

                      #11
                      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.
                      Code:
                      void A(int *p);
                      void B(int *p);
                      
                      int main(void) {
                         int *p;
                         if (<something>) {
                            int a;
                            p = &a;
                            A(p);
                         } else {
                            int b;
                            p = &b;
                            A(p);
                         }
                         B(p);
                      }

                      Comment

                      • momotaro
                        Contributor
                        • Sep 2006
                        • 357

                        #12
                        This is exactly it !!!

                        The function B in my case has irrelevant data passed through the two pointers

                        Comment

                        • momotaro
                          Contributor
                          • Sep 2006
                          • 357

                          #13
                          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

                          Comment

                          • Banfa
                            Recognized Expert Expert
                            • Feb 2006
                            • 9067

                            #14
                            Originally posted by momotaro
                            well here is the whole picture:
                            ma trying to stay as modular as possible my main looks like this:

                            main()
                            {
                            A();
                            B();
                            .....
                            }
                            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

                            Comment

                            • momotaro
                              Contributor
                              • Sep 2006
                              • 357

                              #15
                              The main:
                              Code:
                              #include "common.h"
                              #include "Choix des Armes.h"
                              
                              #define MAX_SIZE 10000
                              
                              void main()
                              {
                              	Monstre Squelettique[MAX_SIZE], Grassouillet[MAX_SIZE];
                              	Eppee eppeeArr[MAX_SIZE];
                              	int nbrEppee;
                              	int *longestMonstre, *largestMonstre, *nbrSquelettique = 0, *nbrGrassouillet = 0;
                              	int oneEppee[MAX_SIZE], twoEppee[MAX_SIZE];
                              	do
                              	{
                              		MonstreFill(Squelettique, Grassouillet, nbrSquelettique, nbrGrassouillet);
                              		//MaxLongMaxLargMonstre(Squelettique, Grassouillet, longestMonstre, largestMonstre);
                              		//nbrEppee = EppeeFill(eppeeArr);
                              		//CandidateEppee(oneEppee, twoEppee, longestMonstre, largestMonstre, nbrSquelettique, nbrGrassouillet);
                              		test(Squelettique, Grassouillet, nbrSquelettique, nbrGrassouillet);
                              		//EppeeElue(monstreArr, eppeeArr);
                              	}while(UserSaysYes());
                              }

                              The two functions:

                              Code:
                              #include "common.h"
                              #include "Choix des Armes.h"
                              
                              
                              void MonstreFill(Monstre *Squelettique, Monstre *Grassouillet, int *nbrSquelettique, int *nbrGrassouillet)
                              {
                              	int i, j, nbrMonstre, monstreType, monstreTaille;
                              	printf("a l interieure de MONSTRE FILL\n");
                              	do
                              	{
                              		puts("Nombre de monstre ?");
                              		scanf("%d", &nbrMonstre);
                              
                              	}while(nbrMonstre < 1 || nbrMonstre > 10000);
                              
                              	//initialisation
                              
                              	for(i = 0; i < nbrMonstre; i++)
                              	{
                              		Squelettique[i].type = -1;
                              		Squelettique[i].taille = -1;
                              
                              		Grassouillet[i].type = -1;
                              		Grassouillet[i].taille = -1;
                              	}
                              
                              
                              	for(i = 0, j = 0; i < nbrMonstre - j, j < nbrMonstre - i; i++, j++)
                              	{
                              		do
                              		{
                              		puts("0->grand monstre, 1->petit monstre? largeur(petit monstre), longueur(grand monstre)?");
                              		scanf("%d %d", &monstreType, &monstreTaille);
                              
                              		/*nbrSquelettique = 0;
                              		nbrGrassouillet = 0;*/
                              
                              		}while(monstreType != 1 && monstreType != 0);
                              
                              		switch (monstreType)
                              		{
                              		case 0:
                              			Squelettique[i].taille = monstreTaille;
                              			Squelettique[i].type = 0;
                              			j--;
                              			break;
                              		case 1:
                              			Grassouillet[j].taille = monstreTaille;
                              			Grassouillet[j].type = 1;
                              			nbrGrassouillet++;
                              			i--;
                              			break;
                              		default: 
                              			puts("If you are reading this you don't existe !!!");
                              		}
                              	}
                              	nbrSquelettique = i;
                              	nbrGrassouillet = j;
                              	printf("%d %d", nbrSquelettique, nbrGrassouillet);
                              	printf("SORTIE DE MONSTRE FILL\n");
                              }

                              Code:
                              #include "common.h"
                              #include "Choix des Armes.h"
                              
                              void test(Monstre *Squelettique, Monstre *Grassouillet, int *nbrSquelettique, int *nbrGrassouillet)
                              {
                              	printf("%d %d", nbrSquelettique, nbrGrassouillet); // here wrong results!!!
                              	/*int i;
                              
                              	puts("Squelettique");
                              	for(i = 0; i < nbrSquelettique; i++)
                              		printf("%d\n", &Squelettique[i].taille);
                              
                              	puts("Grassouillet");
                              	for(i = 0; i < nbrGrassouillet; i++)
                              		printf("%d\n", &Grassouillet[i].taille);*/
                              }
                              and here is my defined types:
                              Code:
                              #include "common.h"
                              
                              typedef struct eppee{
                              	int eppeeID;
                              	int largeur;
                              	int longueur;
                              } Eppee;
                              
                              
                              typedef struct monstre{
                              	int type,
                              		taille;
                              }Monstre;
                              
                              
                              void MonstreFill(Monstre *, Monstre *, int *, int *); // YES
                              
                              int EppeeFill(Eppee *);
                              
                              void MaxLargMaxLongMonstre(Monstre *, Monstre *, int *, int *);
                              
                              void CandidateEppee(Eppee *, int *, int *, int *, int *);
                              
                              void Eppeeelue(int *);
                              
                              void test(Monstre *, Monstre *, int *, int *);

                              Comment

                              Working...