Reputation: 533
I have to help one of my friends, but I have forgotten a bit C. :\ Whats the problem with that code? there must be some pointer error. It gives me an Access violating reading memory. What could be the problem? The main task is to: 2 unlimited arrays, and have to count an avarge.
Edited version: the reading is ok, but can pass literaly fine. As I remember I shouldn't return a pointer, Could I return a counter to count how many numbers attached to A and B array?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
double *bekerdezo1(double *a){
char line[64];
double value = 0;
int n = 0;
while ((fgets(line, sizeof line, stdin) != NULL) && (line[0] != '\n')){
if (sscanf(line, "%lf", &value) == 1){
a =(double*)malloc(sizeof(*a) *(n+1));
a[n] = value;
printf("%lf",a[n]);
n = n++;
}
else {
break;
}
}
return a;
}
double *bekerdezo2(double *b){
double value = 0;
char line[64];
int n = 0;
while ((fgets(line, sizeof line, stdin) != NULL) && (line[0] != '\n')){
if (sscanf(line, "%lf", &value) == 1){
b = (double*)malloc(sizeof(*b) *(n+1));
b[n] = value;
printf("%lf",b[n]);
n = n++;
} else {
break;
}
}
return b;
}
int main(void)
{
double reszq = 0,vegosszeg=0, tarolo = 0;
int i = 0;
size_t *n = 0;
double *a=NULL, *b = NULL;
bekerdezo1(a);
bekerdezo2(b);
for(i=0;i<100; i++)
{
reszq = 0;
tarolo = (a[i])*(b[i]);
reszq = tarolo/a[i];
vegosszeg = vegosszeg + reszq;
}
printf("vegosszeg=", vegosszeg);
return 0;
}
Upvotes: 0
Views: 77
Reputation: 7277
In main() you access the global variable a & b. These are pointers which have not been properly allocated. The memory allocated in bekerdezo1() & bekerdezo2() is allocated to local variables, not the global ones.
bekerdezo2() then returns the local variable back to main but is never assigned to the global variable b. bekerdezo1() on the other hand returns the global variable b (I assume this is a an error where it really should be returning the local variable a).
Yet another error exists in the access of the pointer n in bekerdezo2(). This pointer haven't been properly initialized / allocated either.
Also the for loop in main() doesn't check how many elements were really entered, but tries to read from all 100.
You also want to verify that a & b contains the same amount of elements. Or at least only loop until the smallest nr read by one of them.
I'd suggest removing all the global variables and making them local variables of main() that will help you (and the compiler) find errors like this.
Upvotes: 2