Help for Lab mid-term

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kefuci
    New Member
    • Dec 2007
    • 5

    #1

    Help for Lab mid-term

    Hi guys.This week on friday, I'm gonna have the final exam for C lab.Most probably, the final will be about arrays and pointers.Theref ore, i need a quality source to study those topics.If you know one, could you please let me know?And there is a question i would like to ask;

    void f(int a)
    { a++;}
    int main ()
    { int x[]={3,5,8};
    f(x[1]);
    printf ("%d",x[1]);


    the answer is 5, however; i dont understand the point.If we change the code like ++a;
    , we still get the same value.Why is this?
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    The argument of the function f is an int. That means the compiler makes a copy of the int used to call f. The ++a just changes the copy. The int in the calling function is not involved.

    Comment

    • Laharl
      Recognized Expert Contributor
      • Sep 2007
      • 849

      #3
      The answer is the same because parameters in C are passed into the function and then a local copy is created. Unless you pass parameters as pointers or references, when the function ends, the local copies are destroyed and any changes to them are lost.

      Comment

      • Kefuci
        New Member
        • Dec 2007
        • 5

        #4
        Yeah i get it know.You mean that to increase the array that i wrote i have to modify my function in terms of the array.Because the function depends on what type of variable we call.Please correct me if am wrong.Thank you by the way.
        here is the programme:

        [code=c]
        void f(int a[], int n)
        {
        int i;
        for(i=0;i<n;i++ )
        a[i]++;
        }

        int main()
        {
        int x[]={1,3,8};
        f(x,3);
        printf("%d",x[1]);
        return 0;
        }[/code]
        Last edited by sicarie; Dec 27 '07, 02:44 AM. Reason: Code tags, and seriously, format your code, this is a mess

        Comment

        • manjuks
          New Member
          • Dec 2007
          • 72

          #5
          Instead pass address of x[1] to function f() and write a function f() to take pointer to int as parameter and increment it.

          Comment

          • sicarie
            Recognized Expert Specialist
            • Nov 2006
            • 4677

            #6
            Kefuci-

            You should also research "scope". Your code above should not work (and even if it does, if you make it any larger it probably won't) as your function f() is only modifying the local variable and returning nothing.

            Comment

            Working...