-6

I have this code

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

main()
{
    double b;int a[2],*c; 
    void myfunction();
    c=(int*)(malloc(1));
    b=10.;
    *c=5;
    a[1]=1;a[2]=2;

    printf("before call %f $d $d %d\n",b,a[1],a[2],*c);
    printf("before call %f $d $d %d\n",b,a[1],a[2],*c);
    myfunction(b,a,c);
    printf("after call %f $d $d %d\n",b,a[1],a[2],*c);
}

void myfunction(x,y,d)
     double x;int y[2],*d;
{
    double z;
    x=2*x;
    y[1]=3*y[1];
    y[2]=3*y[2];
    *d =*d+2;
}

when I execute it I receive this

before call 10.000000 $d $d 1
before call 10.000000 $d $d 1
after call 10.000000 $d $d 3

I expect to get 5 in first and second call and 7 in the last call, also a[i] is not shown. could you please advise me why? Thanks

Barmar
  • 741,623
  • 53
  • 500
  • 612
amin bk
  • 194
  • 1
  • 1
  • 12

2 Answers2

1

How your code should look

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
 void myfunction(double x, int y[2], int *d);

int main(int argc, char **argv)
{
   int a[2];
    int *c = malloc(sizeof(int));
    double b=10.0;
    *c = 5;
    a[0]=1;
    a[1]=2;

    printf("before call %f %d %d %d\n",b,a[0],a[1],*c);
    myfunction(b,a,c);
    printf("after call %f %d %d %d\n",b,a[0],a[1],*c);
}

void myfunction(double x, int y[2], int *d)
{
    double z;
    x=2*x;
    y[0]=3*y[0];
    y[1]=3*y[1];
    *d =*d+2;
}

Note, malloc correct size

arrays start at 0

modern declarations of functions

declaring variables at time of first use.

fixed prrintf format (% not $)

pm100
  • 48,078
  • 23
  • 82
  • 145
0

As @OliverCharlesworth states in his comment the problem here is that you use $d instead of %d. As a result of this the format-string only uses the first argument a[1]. Simply replace $dwith %dand your code should work fine.

On another node. C are zero-indexed. You are accessing arrays as if they were one-index. This will cause you problems at some point, as you are accessing unallocated memory. Thus when declaring an array int a[2], should access it using index 0 and 1.(a[0] and a[1])

I have taken the liberty to rewrite your code below:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void myfunction(int x, int* y, int *d);

int main(int argc, char *argv[])
{
    double b;
    int a[2], *c; 


    c  = (int*)(malloc(sizeof(c)));
    b  = 10.;
    *c = 5;
    a[0] = 1;
    a[1] = 2;

    printf("before call %f %d %d %d\n", b, a[0], a[1], *c);
    printf("before call %f %d %d %d\n", b, a[0], a[1], *c);
    myfunction(b,a,c);
    printf("after call %f %d %d %d\n", b, a[0], a[1], *c);
}

void myfunction(int x, int * y, int * d) 
{
    x = 2 * x;
    y[0] = 3 * y[0];
    y[1] = 3 * y[1];
    *d = *d + 2;
}
Jonas
  • 737
  • 1
  • 8
  • 20