Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Passing an array as argument to a function

Passing an array as argument to a function

Scheduled Pinned Locked Moved C / C++ / MFC
questiondata-structures
61 Posts 7 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • C Calin Negru

    Hi What is the syntax when you want to pass an array as argument? I`m looking for syntax for both function call and function definition.

    L Offline
    L Offline
    Lost User
    wrote on last edited by
    #2

    Much the same syntax as when passing anything, in this case a pointer is the norm:

    int myFunction(char* anArrayOfChars) // a pointer to the array
    {
    // function code ...
    }

    ...

    // calling code
    char anArray[32];
    // fill the array
    int value = myFunction(anArray) // name of the array is a pointer to its content

    C 2 Replies Last reply
    0
    • L Lost User

      Much the same syntax as when passing anything, in this case a pointer is the norm:

      int myFunction(char* anArrayOfChars) // a pointer to the array
      {
      // function code ...
      }

      ...

      // calling code
      char anArray[32];
      // fill the array
      int value = myFunction(anArray) // name of the array is a pointer to its content

      C Offline
      C Offline
      Calin Negru
      wrote on last edited by
      #3

      Thanks will modifying the array content within the function make the edit permanent i.e. the modification will remain after the function ceased to exist. i.e. "myFunction(&anArray)" won`t this edit outside the function. I need the edit to work backwards.

      L 1 Reply Last reply
      0
      • C Calin Negru

        Thanks will modifying the array content within the function make the edit permanent i.e. the modification will remain after the function ceased to exist. i.e. "myFunction(&anArray)" won`t this edit outside the function. I need the edit to work backwards.

        L Offline
        L Offline
        Lost User
        wrote on last edited by
        #4

        Yes, if the function changes anything in the array then that data will remain when the function returns to the caller. Note: you do not need the addressof operator (&) on an array name. Just code it as I showed in my example. Try this simple test:

        void myFunc(char* somedata)
        {
        strcpy(somedata, "Bad stuff");
        return;
        }

        //...
        char myArray[] = "Good stuff";
        myFunc(myArray);
        printf("Returned value %s\n", myArray);

        C 1 Reply Last reply
        0
        • L Lost User

          Yes, if the function changes anything in the array then that data will remain when the function returns to the caller. Note: you do not need the addressof operator (&) on an array name. Just code it as I showed in my example. Try this simple test:

          void myFunc(char* somedata)
          {
          strcpy(somedata, "Bad stuff");
          return;
          }

          //...
          char myArray[] = "Good stuff";
          myFunc(myArray);
          printf("Returned value %s\n", myArray);

          C Offline
          C Offline
          Calin Negru
          wrote on last edited by
          #5

          I edited my previous post a bit also

          void myFunc(char* somedata)
          {
          strcpy(somedata, "Good stuff");
          return;
          }

          //...
          char myArray[] = "Bad stuff";
          myFunc(myArray);
          printf("Returned value %s\n", myArray);

          Quote:

          void myFunc(char* somedata) { strcpy(somedata, "Good stuff"); return; } //... char myArray[] = "Bad stuff"; myFunc(myArray); printf("Returned value %s\n", myArray);

          will this function? the array has 9 elements(bad stuff 9 chars.) "good stuff" is 10.

          L Greg UtasG 2 Replies Last reply
          0
          • C Calin Negru

            I edited my previous post a bit also

            void myFunc(char* somedata)
            {
            strcpy(somedata, "Good stuff");
            return;
            }

            //...
            char myArray[] = "Bad stuff";
            myFunc(myArray);
            printf("Returned value %s\n", myArray);

            Quote:

            void myFunc(char* somedata) { strcpy(somedata, "Good stuff"); return; } //... char myArray[] = "Bad stuff"; myFunc(myArray); printf("Returned value %s\n", myArray);

            will this function? the array has 9 elements(bad stuff 9 chars.) "good stuff" is 10.

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #6

            Well, of course that breaks it so you may find that your code crashes. You must not overwrite arrays that are passed to you with more data than it can hold. But this conversation is missing some vital information. Maybe you can explain exactly what problem you are trying to solve.

            C 1 Reply Last reply
            0
            • L Lost User

              Well, of course that breaks it so you may find that your code crashes. You must not overwrite arrays that are passed to you with more data than it can hold. But this conversation is missing some vital information. Maybe you can explain exactly what problem you are trying to solve.

              C Offline
              C Offline
              Calin Negru
              wrote on last edited by
              #7

              @Richard Meh I`m really not doing anything worth much attention. My code is stashed with hacks so I`m just trying to fix on it.

              "DreamLand Page" on facebook

              L 1 Reply Last reply
              0
              • C Calin Negru

                @Richard Meh I`m really not doing anything worth much attention. My code is stashed with hacks so I`m just trying to fix on it.

                "DreamLand Page" on facebook

                L Offline
                L Offline
                Lost User
                wrote on last edited by
                #8

                fearless_ wrote:

                My code is stashed with hacks

                So it all needs a lot of attention.

                C 1 Reply Last reply
                0
                • L Lost User

                  fearless_ wrote:

                  My code is stashed with hacks

                  So it all needs a lot of attention.

                  C Offline
                  C Offline
                  Calin Negru
                  wrote on last edited by
                  #9

                  Thanks for pointing how things are meant to be done Richard

                  "DreamLand Page" on facebook

                  K 1 Reply Last reply
                  0
                  • C Calin Negru

                    I edited my previous post a bit also

                    void myFunc(char* somedata)
                    {
                    strcpy(somedata, "Good stuff");
                    return;
                    }

                    //...
                    char myArray[] = "Bad stuff";
                    myFunc(myArray);
                    printf("Returned value %s\n", myArray);

                    Quote:

                    void myFunc(char* somedata) { strcpy(somedata, "Good stuff"); return; } //... char myArray[] = "Bad stuff"; myFunc(myArray); printf("Returned value %s\n", myArray);

                    will this function? the array has 9 elements(bad stuff 9 chars.) "good stuff" is 10.

                    Greg UtasG Offline
                    Greg UtasG Offline
                    Greg Utas
                    wrote on last edited by
                    #10

                    You can write it like this

                    void myFunc(char somedata[]) // edited to remove * after char: see Richard's post below

                    to highlight that it's actually an array rather than just a pointer to a single char. Given that it's an array, its size is often provided to avoid the kind of trampling that you pointed out:

                    void myFunc(char somedata[], size_t n)

                    Robust Services Core | Software Techniques for Lemmings | Articles

                    <p><a href="https://github.com/GregUtas/robust-services-core/blob/master/README.md">Robust Services Core</a>
                    <em>The fox knows many things, but the hedgehog knows one big thing.</em></p>

                    C L 2 Replies Last reply
                    0
                    • Greg UtasG Greg Utas

                      You can write it like this

                      void myFunc(char somedata[]) // edited to remove * after char: see Richard's post below

                      to highlight that it's actually an array rather than just a pointer to a single char. Given that it's an array, its size is often provided to avoid the kind of trampling that you pointed out:

                      void myFunc(char somedata[], size_t n)

                      Robust Services Core | Software Techniques for Lemmings | Articles

                      C Offline
                      C Offline
                      Calin Negru
                      wrote on last edited by
                      #11

                      thanks Greg for that tip

                      L Greg UtasG 2 Replies Last reply
                      0
                      • C Calin Negru

                        Thanks for pointing how things are meant to be done Richard

                        "DreamLand Page" on facebook

                        K Offline
                        K Offline
                        k5054
                        wrote on last edited by
                        #12

                        Further to what Richard has said, you could also do some defensive programming by passing in the length of the array. eg:

                        void myFunc(int* somedata, size_t data_len)
                        {
                        for(size_t i = 0; i < data_len; ++i)
                        somedata[i] *= 2;
                        return;
                        }

                        //...
                        int myArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
                        const size_t arrLen = sizeof(myArray)/sizeof(myArray[0]);
                        myFunc(myArray), arrLen);
                        // ... etc

                        This will prevent data overflows, and/or segfaults, when accessing myArray inside the function. Things to note: * we can get the compiler to tell us how many elements in the array using the sizeof(myArray)/sizeof(myArray[0]) construct. This is calculated at compile time and in release mode, in most cases it will be optimized out, so it does not add to your memory usage, if that's a concern. * Using the constant arrLen means that if we change the number of elements in myArray, we don't need to go through the code and find all uses of myArray and make sure we're passing in the right number * If we had used arrLen = sizeof(myArray)/sizeof(int), we need to remember to change the definition of arrLen if we change the type of myArray. Using sizeof(myArray[0] mean that if we change the type of myArray from int[] to double[], for example, we don't need to remember to change the definition of arrLen as well

                        Keep Calm and Carry On

                        L 1 Reply Last reply
                        0
                        • C Calin Negru

                          thanks Greg for that tip

                          L Offline
                          L Offline
                          leon de boer
                          wrote on last edited by
                          #13

                          Under C any pointer is already a pointer to an array it's built into the language along with pointer arithmetic ... you need to just learn that. Literally declare any pointer of anything lets do a float float* p; now you can access it as an array p[0] = 5.0; p[100] = 10.0; It will crash because the pointer isn't really to any memory but it makes the point the pointer is already a pointer to an array There are no exceptions to the rule it doesn't matter if the pointer is to a fundamental type or struct .... so I don't get how you could ever forget that. In the C community the [] use is rare because it's two extra characters to type. It also has implication when declaring variables because it puts that array on the stack not on data memory or constant memory (rodata) if it determines its a constant. So if you get into the habit of using that form you can get some undesirable things happen. Personally you are learning and I would learn to live without it and just learn them as you will most often see them written. The topic is well covered in dummies guide to C but you will note the last statement How to Use Arrays and Functions Together in C Programming - dummies[^]

                          In vino veritas

                          C 1 Reply Last reply
                          0
                          • K k5054

                            Further to what Richard has said, you could also do some defensive programming by passing in the length of the array. eg:

                            void myFunc(int* somedata, size_t data_len)
                            {
                            for(size_t i = 0; i < data_len; ++i)
                            somedata[i] *= 2;
                            return;
                            }

                            //...
                            int myArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
                            const size_t arrLen = sizeof(myArray)/sizeof(myArray[0]);
                            myFunc(myArray), arrLen);
                            // ... etc

                            This will prevent data overflows, and/or segfaults, when accessing myArray inside the function. Things to note: * we can get the compiler to tell us how many elements in the array using the sizeof(myArray)/sizeof(myArray[0]) construct. This is calculated at compile time and in release mode, in most cases it will be optimized out, so it does not add to your memory usage, if that's a concern. * Using the constant arrLen means that if we change the number of elements in myArray, we don't need to go through the code and find all uses of myArray and make sure we're passing in the right number * If we had used arrLen = sizeof(myArray)/sizeof(int), we need to remember to change the definition of arrLen if we change the type of myArray. Using sizeof(myArray[0] mean that if we change the type of myArray from int[] to double[], for example, we don't need to remember to change the definition of arrLen as well

                            Keep Calm and Carry On

                            L Offline
                            L Offline
                            Lost User
                            wrote on last edited by
                            #14

                            There is also the _countof() macro, which gives the number of elements in arrays of any simple or composite type.

                            L K 2 Replies Last reply
                            0
                            • Greg UtasG Greg Utas

                              You can write it like this

                              void myFunc(char somedata[]) // edited to remove * after char: see Richard's post below

                              to highlight that it's actually an array rather than just a pointer to a single char. Given that it's an array, its size is often provided to avoid the kind of trampling that you pointed out:

                              void myFunc(char somedata[], size_t n)

                              Robust Services Core | Software Techniques for Lemmings | Articles

                              L Offline
                              L Offline
                              Lost User
                              wrote on last edited by
                              #15

                              Greg Utas wrote:

                              char* somedata[]

                              That's an array of pointers.

                              L Greg UtasG C 3 Replies Last reply
                              0
                              • L Lost User

                                Greg Utas wrote:

                                char* somedata[]

                                That's an array of pointers.

                                L Offline
                                L Offline
                                leon de boer
                                wrote on last edited by
                                #16

                                good pick didn't even notice the * because that form is so foreign to me.

                                In vino veritas

                                1 Reply Last reply
                                0
                                • L Lost User

                                  There is also the _countof() macro, which gives the number of elements in arrays of any simple or composite type.

                                  L Offline
                                  L Offline
                                  leon de boer
                                  wrote on last edited by
                                  #17

                                  Best macro ever added into C standard ... wish more people would use it.

                                  In vino veritas

                                  L 1 Reply Last reply
                                  0
                                  • L leon de boer

                                    Best macro ever added into C standard ... wish more people would use it.

                                    In vino veritas

                                    L Offline
                                    L Offline
                                    Lost User
                                    wrote on last edited by
                                    #18

                                    They probably would if it was easier to find; after all it is in the documentation. ;)

                                    1 Reply Last reply
                                    0
                                    • L Lost User

                                      There is also the _countof() macro, which gives the number of elements in arrays of any simple or composite type.

                                      K Offline
                                      K Offline
                                      k5054
                                      wrote on last edited by
                                      #19

                                      I didn't know about _countof(). Is it an MS only extension? Trying to compile with gcc under linux produces an implicit declaration warning in C and a not declared in this scope in C++

                                      Keep Calm and Carry On

                                      L L 2 Replies Last reply
                                      0
                                      • L leon de boer

                                        Under C any pointer is already a pointer to an array it's built into the language along with pointer arithmetic ... you need to just learn that. Literally declare any pointer of anything lets do a float float* p; now you can access it as an array p[0] = 5.0; p[100] = 10.0; It will crash because the pointer isn't really to any memory but it makes the point the pointer is already a pointer to an array There are no exceptions to the rule it doesn't matter if the pointer is to a fundamental type or struct .... so I don't get how you could ever forget that. In the C community the [] use is rare because it's two extra characters to type. It also has implication when declaring variables because it puts that array on the stack not on data memory or constant memory (rodata) if it determines its a constant. So if you get into the habit of using that form you can get some undesirable things happen. Personally you are learning and I would learn to live without it and just learn them as you will most often see them written. The topic is well covered in dummies guide to C but you will note the last statement How to Use Arrays and Functions Together in C Programming - dummies[^]

                                        In vino veritas

                                        C Offline
                                        C Offline
                                        Calin Negru
                                        wrote on last edited by
                                        #20

                                        float* p;
                                        now you can access it as an array
                                        p[0] = 5.0;
                                        p[100] = 10.0;

                                        I understand "p[0] = 5.0;" since that`s the first element, but then "p[100] = 10.0;" don`t you need to alocate first "p = new float[101]"

                                        1 Reply Last reply
                                        0
                                        • K k5054

                                          I didn't know about _countof(). Is it an MS only extension? Trying to compile with gcc under linux produces an implicit declaration warning in C and a not declared in this scope in C++

                                          Keep Calm and Carry On

                                          L Offline
                                          L Offline
                                          Lost User
                                          wrote on last edited by
                                          #21

                                          The documentation on MSDN (_countof Macro | Microsoft Docs[^]) does not identify it as MS only.

                                          S 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups