something is wrong with this program

i tried to see the mean and variance of the set. mean is calculated correctly and i am facing the problem in variance' part. please help me.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include<stdio.h>
#include<math.h>
float *ptr;
void gettheset(int b)
{
    float st[b];
    int i;
    printf("\nEnter the elements of the set\n");
    for(i=0;i<b;i++)
    {
        scanf("%f",&st[i]);

    }
    for(i=0;i<b;i++)
    {
        printf("\t%f\t",st[i]);

    }
    ptr=st;
    printf("\nthe address of the pointer ptr is %p",ptr );
}
float mean(int d)
{
    float m=0;
    int j;
    for(j=0;j<d;j++)
    {
        m=m+(*(ptr+j));
    }
    m=m/d;

    return m;

}
void variance(int e, float sd)
{
    int k;
     printf("\nthe address of the pointer ptr(var1) is %p",ptr );
    for(k=0;k<e;k++)
    {
        *(ptr+k)=sd-*(ptr+k);
        *(ptr+k)=(*(ptr+k))*(*(ptr+k));
    }

     printf("\nthe address of the pointer ptr(var2) is %p",ptr );
    float v=0;
    for(k=0;k<e;k++)
    {
        v=v+(*(ptr+k));
    }
    v=(v/e);
    printf("The variance of the set is %f",v);
     printf("\nthe address of the pointer ptr(var3) is %p",ptr );
}

main()
{
    int a,check;
    char c;
    printf("Give the size to the array/set   ");

    while(1)
    {
check=scanf("%d",&a);
    c=getchar();
        if(check!=1||c!='\n')
        {
            printf("Invalid size of the array. Type again\n");
            while((c=getchar())!='\n');
        }
        else
        {
            break;
        }
    }
    gettheset(a);
    float mn;
    mn=mean(a);
    printf("\nThe mean of the set if %f\n",mn);
    variance(a,mn);


}
Last edited on
1
2
3
4
5
6
7
8
9
float *ptr;
void gettheset(int b)
{
    float st[b]; //local variable
//...
    ptr=st; //pointing to local variable
    printf("\nthe address of the pointer ptr is %p",ptr );
}//`st' dies
//ptr is pointing to garbage 
how to solve this problem if i have to do it with globally declared pointer?
C: `malloc()'
c++: `std::vector'
Good post and the nice information


http://www.arm2teeth.com
Last edited on
Topic archived. No new replies allowed.