0

I made some code to compare temperature of the week.

I made two functions, one to write to the array, other one is to calculate average temp. It compiles without errors. As soon as I enter my first number the app crashes and I get this error in the stdio.h lib :

Exception thrown at 0x533C742E (ucrtbased.dll) in 7.3.exe: 0xC0000005: Access violation writing location 0xCCCCCCCC.

I made a similar exercise without functions and it was working perfect. Hope you guys can help me out. Here is my code

#include <stdio.h>
#define MAX 7
#define _NO_CRT_STDIO_INLINE
void read(int);
float gem(int);

int main(void)
{
    float x = 0;
    int temp[MAX];
    read(temp[MAX]);
    x = gem(temp[MAX]);
    printf("%f", x);
}

void read(int k[MAX])
{
    for (int i = 1; i < 8; i++)
    {
        printf("geef de temp voor dag %d ", i);
        scanf_s("%d%*c", &k[i-1]);
    }
}

float gem(int y[MAX])
{
    int som = 0;
    float gem = 0;
    for (int i = 0; i < 8; i++)
    {
        som += y[i - 1];
        gem = som / 7;
        return gem;
    }
}
3
  • 2
    y[i - 1]; access y[-1] if i == 0 Commented Oct 25, 2017 at 10:14
  • 1
    How and why did you think void read(int) would be equal to void read(int k[MAX])? Perhaps you should take a few steps back, and read a couple of good beginners books. Commented Oct 25, 2017 at 10:14
  • unrelated : gem = som / 7; return gem; --> gem = som / 7.; return gem; (or gem = (double)som / MAX; return gem;) and move after for-loop. Commented Oct 25, 2017 at 10:21

2 Answers 2

2

When in doubt, check the data type!!

In your code, the function call

  read(temp[MAX]);   //trying to pass an int type 

is wrong. The function accepts an int *.

You need to pass the pointer to the beginning of the array, like

  read(temp);

That said, temp[MAX] is already off-by-one, causing undefined behavior.

Also, your loop controller variable usage is bit odd. You can simply use like

  for (int i = 0; i < MAX; i++)

and then, use i as the iterator (indexing).

Sign up to request clarification or add additional context in comments.

Comments

0

Generally,Parameters are always passed by value in C. Therefore, in the above code, value of read(temp[MAX]); is not modified using the function. So how do we modify the value of a local variable of a function inside another function. Pointer is the solution to such problems. Using pointers, we can modify a local variable of a function inside another function. We only get the effect of pass by reference using pointers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.