C : reverse array using pointers?











up vote
-1
down vote

favorite
1












I don't see where I have made an error in this code :



void swap(int* a, int* b)
{
int temp = *a;

*a = *b;
*b = temp;
}

void array_reverse(int *begin, int *end)
{
int *end2 = end;
int *q = 0;
for (q = begin; q < end; q += 1)
{
swap(q, end2);
end2 -= 1;
}
}


it should reverse the array:



arr{ 1, 2, 3}


becomes:



arr{ 3, 2, 1}


My output:



[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10] 


becomes :



[111009824,  2,  3,  4,  5,  6,  7,  8,  9, 10]


(well actually this first element always changes each time I compile and test my function and gives me random values I guess )










share|improve this question
























  • What output do you get?
    – Ajay Brahmakshatriya
    Nov 21 at 22:32










  • Yes i know this, but then why here: stackoverflow.com/questions/53420928/c-array-sum-using-pointers we do p ++ it's the same ?
    – whohasfriends3
    Nov 21 at 22:32












  • If you don't stop in the middle of the array, you'll reverse it twice and end up where you started.
    – Weather Vane
    Nov 21 at 22:34










  • How can I stop in the middle of the array please
    – whohasfriends3
    Nov 21 at 22:36










  • pre-decrement end2 cos at first it points to invalid data
    – Jean-François Fabre
    Nov 21 at 22:36















up vote
-1
down vote

favorite
1












I don't see where I have made an error in this code :



void swap(int* a, int* b)
{
int temp = *a;

*a = *b;
*b = temp;
}

void array_reverse(int *begin, int *end)
{
int *end2 = end;
int *q = 0;
for (q = begin; q < end; q += 1)
{
swap(q, end2);
end2 -= 1;
}
}


it should reverse the array:



arr{ 1, 2, 3}


becomes:



arr{ 3, 2, 1}


My output:



[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10] 


becomes :



[111009824,  2,  3,  4,  5,  6,  7,  8,  9, 10]


(well actually this first element always changes each time I compile and test my function and gives me random values I guess )










share|improve this question
























  • What output do you get?
    – Ajay Brahmakshatriya
    Nov 21 at 22:32










  • Yes i know this, but then why here: stackoverflow.com/questions/53420928/c-array-sum-using-pointers we do p ++ it's the same ?
    – whohasfriends3
    Nov 21 at 22:32












  • If you don't stop in the middle of the array, you'll reverse it twice and end up where you started.
    – Weather Vane
    Nov 21 at 22:34










  • How can I stop in the middle of the array please
    – whohasfriends3
    Nov 21 at 22:36










  • pre-decrement end2 cos at first it points to invalid data
    – Jean-François Fabre
    Nov 21 at 22:36













up vote
-1
down vote

favorite
1









up vote
-1
down vote

favorite
1






1





I don't see where I have made an error in this code :



void swap(int* a, int* b)
{
int temp = *a;

*a = *b;
*b = temp;
}

void array_reverse(int *begin, int *end)
{
int *end2 = end;
int *q = 0;
for (q = begin; q < end; q += 1)
{
swap(q, end2);
end2 -= 1;
}
}


it should reverse the array:



arr{ 1, 2, 3}


becomes:



arr{ 3, 2, 1}


My output:



[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10] 


becomes :



[111009824,  2,  3,  4,  5,  6,  7,  8,  9, 10]


(well actually this first element always changes each time I compile and test my function and gives me random values I guess )










share|improve this question















I don't see where I have made an error in this code :



void swap(int* a, int* b)
{
int temp = *a;

*a = *b;
*b = temp;
}

void array_reverse(int *begin, int *end)
{
int *end2 = end;
int *q = 0;
for (q = begin; q < end; q += 1)
{
swap(q, end2);
end2 -= 1;
}
}


it should reverse the array:



arr{ 1, 2, 3}


becomes:



arr{ 3, 2, 1}


My output:



[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10] 


becomes :



[111009824,  2,  3,  4,  5,  6,  7,  8,  9, 10]


(well actually this first element always changes each time I compile and test my function and gives me random values I guess )







c arrays pointers reverse






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 at 22:34

























asked Nov 21 at 22:28









whohasfriends3

103




103












  • What output do you get?
    – Ajay Brahmakshatriya
    Nov 21 at 22:32










  • Yes i know this, but then why here: stackoverflow.com/questions/53420928/c-array-sum-using-pointers we do p ++ it's the same ?
    – whohasfriends3
    Nov 21 at 22:32












  • If you don't stop in the middle of the array, you'll reverse it twice and end up where you started.
    – Weather Vane
    Nov 21 at 22:34










  • How can I stop in the middle of the array please
    – whohasfriends3
    Nov 21 at 22:36










  • pre-decrement end2 cos at first it points to invalid data
    – Jean-François Fabre
    Nov 21 at 22:36


















  • What output do you get?
    – Ajay Brahmakshatriya
    Nov 21 at 22:32










  • Yes i know this, but then why here: stackoverflow.com/questions/53420928/c-array-sum-using-pointers we do p ++ it's the same ?
    – whohasfriends3
    Nov 21 at 22:32












  • If you don't stop in the middle of the array, you'll reverse it twice and end up where you started.
    – Weather Vane
    Nov 21 at 22:34










  • How can I stop in the middle of the array please
    – whohasfriends3
    Nov 21 at 22:36










  • pre-decrement end2 cos at first it points to invalid data
    – Jean-François Fabre
    Nov 21 at 22:36
















What output do you get?
– Ajay Brahmakshatriya
Nov 21 at 22:32




What output do you get?
– Ajay Brahmakshatriya
Nov 21 at 22:32












Yes i know this, but then why here: stackoverflow.com/questions/53420928/c-array-sum-using-pointers we do p ++ it's the same ?
– whohasfriends3
Nov 21 at 22:32






Yes i know this, but then why here: stackoverflow.com/questions/53420928/c-array-sum-using-pointers we do p ++ it's the same ?
– whohasfriends3
Nov 21 at 22:32














If you don't stop in the middle of the array, you'll reverse it twice and end up where you started.
– Weather Vane
Nov 21 at 22:34




If you don't stop in the middle of the array, you'll reverse it twice and end up where you started.
– Weather Vane
Nov 21 at 22:34












How can I stop in the middle of the array please
– whohasfriends3
Nov 21 at 22:36




How can I stop in the middle of the array please
– whohasfriends3
Nov 21 at 22:36












pre-decrement end2 cos at first it points to invalid data
– Jean-François Fabre
Nov 21 at 22:36




pre-decrement end2 cos at first it points to invalid data
– Jean-François Fabre
Nov 21 at 22:36












3 Answers
3






active

oldest

votes

















up vote
4
down vote



accepted










The issue is with the for loop



void array_reverse(int *begin, int *end)
{
int *end2 = end;
int *q = 0;
for (q = begin; q < end; q += 1)
{
swap(q, end2);
end2 -= 1;
}
}


You must change end to end2 in order to stop when you reach the middle
You must also decrement end2 before you call swap so you are pointing at the right value



void array_reverse(int *begin, int *end)
{
int *end2 = end;
int *q = 0;
for (q = begin; q < end2; q += 1)
{
end2 -= 1;
swap(q, end2);

}
}


The function call would then look something like this



int test[10] = {1,2,3,4,5,6,7,8,9,10};
array_reverse(test, test + 10);





share|improve this answer























  • thanks it works
    – whohasfriends3
    Nov 21 at 22:41










  • yes sorry there was an error
    – whohasfriends3
    Nov 21 at 23:11


















up vote
0
down vote













There were two problems. In the for loop, end should have been end2.



for (q = begin; q < end2; q += 1) {
swap(q, end2);
end2 -= 1; }


The other issue was the call. It should have been array_reverse (a, a+9); because array indexes start at 0. Giving a+10 for the second argument with an array of length 10 passes a pointer to nonsense outside the array bounds.



I must express some appreciation for the question, it got me researching the fundamental difference between "swapping pointer addresses around" and swapping the "data to which the pointers point.



Something else worth noting is that, in C, function arguments are by-value copies. We could rewrite array_reverse like this with no adverse consequences. Why does this work?



void array_reverse(int *begin, int *end)
for ( ;begin < end; ) swap(begin++, end--)


The function body receives local copies of arguments to work on. Hence, there is nothing wrong with modifying their values. It is guaranteed that the function can't modify the initial values of its arguments outside the function without simulating a pass by reference through some form of indirection. There is a powerful simplicity to grasping the concept.






share|improve this answer






























    up vote
    -4
    down vote













    Sometimes a complete rewrite helps identify problems in the original. It also reduces the urge to plagiarize, or copy and paste. Here is another way of writing the loop using while. (corrected, thanks).



    void array_reverse(int *first, int *last)
    {
    int *f = first;
    int *l = last;
    while (f < l)
    {
    swap(f, l);
    f++, l--;
    }
    }





    share|improve this answer























    • no, it reads one byte too much. and it doesn't work
      – Jean-François Fabre
      Nov 21 at 22:46












    • corrected, thanks
      – hellork
      Nov 22 at 23:35











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53421320%2fc-reverse-array-using-pointers%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    4
    down vote



    accepted










    The issue is with the for loop



    void array_reverse(int *begin, int *end)
    {
    int *end2 = end;
    int *q = 0;
    for (q = begin; q < end; q += 1)
    {
    swap(q, end2);
    end2 -= 1;
    }
    }


    You must change end to end2 in order to stop when you reach the middle
    You must also decrement end2 before you call swap so you are pointing at the right value



    void array_reverse(int *begin, int *end)
    {
    int *end2 = end;
    int *q = 0;
    for (q = begin; q < end2; q += 1)
    {
    end2 -= 1;
    swap(q, end2);

    }
    }


    The function call would then look something like this



    int test[10] = {1,2,3,4,5,6,7,8,9,10};
    array_reverse(test, test + 10);





    share|improve this answer























    • thanks it works
      – whohasfriends3
      Nov 21 at 22:41










    • yes sorry there was an error
      – whohasfriends3
      Nov 21 at 23:11















    up vote
    4
    down vote



    accepted










    The issue is with the for loop



    void array_reverse(int *begin, int *end)
    {
    int *end2 = end;
    int *q = 0;
    for (q = begin; q < end; q += 1)
    {
    swap(q, end2);
    end2 -= 1;
    }
    }


    You must change end to end2 in order to stop when you reach the middle
    You must also decrement end2 before you call swap so you are pointing at the right value



    void array_reverse(int *begin, int *end)
    {
    int *end2 = end;
    int *q = 0;
    for (q = begin; q < end2; q += 1)
    {
    end2 -= 1;
    swap(q, end2);

    }
    }


    The function call would then look something like this



    int test[10] = {1,2,3,4,5,6,7,8,9,10};
    array_reverse(test, test + 10);





    share|improve this answer























    • thanks it works
      – whohasfriends3
      Nov 21 at 22:41










    • yes sorry there was an error
      – whohasfriends3
      Nov 21 at 23:11













    up vote
    4
    down vote



    accepted







    up vote
    4
    down vote



    accepted






    The issue is with the for loop



    void array_reverse(int *begin, int *end)
    {
    int *end2 = end;
    int *q = 0;
    for (q = begin; q < end; q += 1)
    {
    swap(q, end2);
    end2 -= 1;
    }
    }


    You must change end to end2 in order to stop when you reach the middle
    You must also decrement end2 before you call swap so you are pointing at the right value



    void array_reverse(int *begin, int *end)
    {
    int *end2 = end;
    int *q = 0;
    for (q = begin; q < end2; q += 1)
    {
    end2 -= 1;
    swap(q, end2);

    }
    }


    The function call would then look something like this



    int test[10] = {1,2,3,4,5,6,7,8,9,10};
    array_reverse(test, test + 10);





    share|improve this answer














    The issue is with the for loop



    void array_reverse(int *begin, int *end)
    {
    int *end2 = end;
    int *q = 0;
    for (q = begin; q < end; q += 1)
    {
    swap(q, end2);
    end2 -= 1;
    }
    }


    You must change end to end2 in order to stop when you reach the middle
    You must also decrement end2 before you call swap so you are pointing at the right value



    void array_reverse(int *begin, int *end)
    {
    int *end2 = end;
    int *q = 0;
    for (q = begin; q < end2; q += 1)
    {
    end2 -= 1;
    swap(q, end2);

    }
    }


    The function call would then look something like this



    int test[10] = {1,2,3,4,5,6,7,8,9,10};
    array_reverse(test, test + 10);






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 21 at 22:41

























    answered Nov 21 at 22:40









    Mitchel Paulin

    1,529417




    1,529417












    • thanks it works
      – whohasfriends3
      Nov 21 at 22:41










    • yes sorry there was an error
      – whohasfriends3
      Nov 21 at 23:11


















    • thanks it works
      – whohasfriends3
      Nov 21 at 22:41










    • yes sorry there was an error
      – whohasfriends3
      Nov 21 at 23:11
















    thanks it works
    – whohasfriends3
    Nov 21 at 22:41




    thanks it works
    – whohasfriends3
    Nov 21 at 22:41












    yes sorry there was an error
    – whohasfriends3
    Nov 21 at 23:11




    yes sorry there was an error
    – whohasfriends3
    Nov 21 at 23:11












    up vote
    0
    down vote













    There were two problems. In the for loop, end should have been end2.



    for (q = begin; q < end2; q += 1) {
    swap(q, end2);
    end2 -= 1; }


    The other issue was the call. It should have been array_reverse (a, a+9); because array indexes start at 0. Giving a+10 for the second argument with an array of length 10 passes a pointer to nonsense outside the array bounds.



    I must express some appreciation for the question, it got me researching the fundamental difference between "swapping pointer addresses around" and swapping the "data to which the pointers point.



    Something else worth noting is that, in C, function arguments are by-value copies. We could rewrite array_reverse like this with no adverse consequences. Why does this work?



    void array_reverse(int *begin, int *end)
    for ( ;begin < end; ) swap(begin++, end--)


    The function body receives local copies of arguments to work on. Hence, there is nothing wrong with modifying their values. It is guaranteed that the function can't modify the initial values of its arguments outside the function without simulating a pass by reference through some form of indirection. There is a powerful simplicity to grasping the concept.






    share|improve this answer



























      up vote
      0
      down vote













      There were two problems. In the for loop, end should have been end2.



      for (q = begin; q < end2; q += 1) {
      swap(q, end2);
      end2 -= 1; }


      The other issue was the call. It should have been array_reverse (a, a+9); because array indexes start at 0. Giving a+10 for the second argument with an array of length 10 passes a pointer to nonsense outside the array bounds.



      I must express some appreciation for the question, it got me researching the fundamental difference between "swapping pointer addresses around" and swapping the "data to which the pointers point.



      Something else worth noting is that, in C, function arguments are by-value copies. We could rewrite array_reverse like this with no adverse consequences. Why does this work?



      void array_reverse(int *begin, int *end)
      for ( ;begin < end; ) swap(begin++, end--)


      The function body receives local copies of arguments to work on. Hence, there is nothing wrong with modifying their values. It is guaranteed that the function can't modify the initial values of its arguments outside the function without simulating a pass by reference through some form of indirection. There is a powerful simplicity to grasping the concept.






      share|improve this answer

























        up vote
        0
        down vote










        up vote
        0
        down vote









        There were two problems. In the for loop, end should have been end2.



        for (q = begin; q < end2; q += 1) {
        swap(q, end2);
        end2 -= 1; }


        The other issue was the call. It should have been array_reverse (a, a+9); because array indexes start at 0. Giving a+10 for the second argument with an array of length 10 passes a pointer to nonsense outside the array bounds.



        I must express some appreciation for the question, it got me researching the fundamental difference between "swapping pointer addresses around" and swapping the "data to which the pointers point.



        Something else worth noting is that, in C, function arguments are by-value copies. We could rewrite array_reverse like this with no adverse consequences. Why does this work?



        void array_reverse(int *begin, int *end)
        for ( ;begin < end; ) swap(begin++, end--)


        The function body receives local copies of arguments to work on. Hence, there is nothing wrong with modifying their values. It is guaranteed that the function can't modify the initial values of its arguments outside the function without simulating a pass by reference through some form of indirection. There is a powerful simplicity to grasping the concept.






        share|improve this answer














        There were two problems. In the for loop, end should have been end2.



        for (q = begin; q < end2; q += 1) {
        swap(q, end2);
        end2 -= 1; }


        The other issue was the call. It should have been array_reverse (a, a+9); because array indexes start at 0. Giving a+10 for the second argument with an array of length 10 passes a pointer to nonsense outside the array bounds.



        I must express some appreciation for the question, it got me researching the fundamental difference between "swapping pointer addresses around" and swapping the "data to which the pointers point.



        Something else worth noting is that, in C, function arguments are by-value copies. We could rewrite array_reverse like this with no adverse consequences. Why does this work?



        void array_reverse(int *begin, int *end)
        for ( ;begin < end; ) swap(begin++, end--)


        The function body receives local copies of arguments to work on. Hence, there is nothing wrong with modifying their values. It is guaranteed that the function can't modify the initial values of its arguments outside the function without simulating a pass by reference through some form of indirection. There is a powerful simplicity to grasping the concept.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 23 at 1:29

























        answered Nov 23 at 1:11









        hellork

        1035




        1035






















            up vote
            -4
            down vote













            Sometimes a complete rewrite helps identify problems in the original. It also reduces the urge to plagiarize, or copy and paste. Here is another way of writing the loop using while. (corrected, thanks).



            void array_reverse(int *first, int *last)
            {
            int *f = first;
            int *l = last;
            while (f < l)
            {
            swap(f, l);
            f++, l--;
            }
            }





            share|improve this answer























            • no, it reads one byte too much. and it doesn't work
              – Jean-François Fabre
              Nov 21 at 22:46












            • corrected, thanks
              – hellork
              Nov 22 at 23:35















            up vote
            -4
            down vote













            Sometimes a complete rewrite helps identify problems in the original. It also reduces the urge to plagiarize, or copy and paste. Here is another way of writing the loop using while. (corrected, thanks).



            void array_reverse(int *first, int *last)
            {
            int *f = first;
            int *l = last;
            while (f < l)
            {
            swap(f, l);
            f++, l--;
            }
            }





            share|improve this answer























            • no, it reads one byte too much. and it doesn't work
              – Jean-François Fabre
              Nov 21 at 22:46












            • corrected, thanks
              – hellork
              Nov 22 at 23:35













            up vote
            -4
            down vote










            up vote
            -4
            down vote









            Sometimes a complete rewrite helps identify problems in the original. It also reduces the urge to plagiarize, or copy and paste. Here is another way of writing the loop using while. (corrected, thanks).



            void array_reverse(int *first, int *last)
            {
            int *f = first;
            int *l = last;
            while (f < l)
            {
            swap(f, l);
            f++, l--;
            }
            }





            share|improve this answer














            Sometimes a complete rewrite helps identify problems in the original. It also reduces the urge to plagiarize, or copy and paste. Here is another way of writing the loop using while. (corrected, thanks).



            void array_reverse(int *first, int *last)
            {
            int *f = first;
            int *l = last;
            while (f < l)
            {
            swap(f, l);
            f++, l--;
            }
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 22 at 23:35

























            answered Nov 21 at 22:46









            hellork

            1035




            1035












            • no, it reads one byte too much. and it doesn't work
              – Jean-François Fabre
              Nov 21 at 22:46












            • corrected, thanks
              – hellork
              Nov 22 at 23:35


















            • no, it reads one byte too much. and it doesn't work
              – Jean-François Fabre
              Nov 21 at 22:46












            • corrected, thanks
              – hellork
              Nov 22 at 23:35
















            no, it reads one byte too much. and it doesn't work
            – Jean-François Fabre
            Nov 21 at 22:46






            no, it reads one byte too much. and it doesn't work
            – Jean-François Fabre
            Nov 21 at 22:46














            corrected, thanks
            – hellork
            Nov 22 at 23:35




            corrected, thanks
            – hellork
            Nov 22 at 23:35


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53421320%2fc-reverse-array-using-pointers%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Berounka

            Different font size/position of beamer's navigation symbols template's content depending on regular/plain...

            Sphinx de Gizeh