1

Write a function int set_array(int *v, int i, int j, int k) that sets the elements i to j to a specific value k among the elements of the int array v of size n (<= 100). This is the given problem.

When I input 10 0 9 -1, to set all the elements it comes out normally as -1.

However, when 5 2 2 0 is input, to set only element [2], all output values ​​come out as 0.

I am using eclipse and no error came out. Which part is wrong?

#include <stdio.h>

int set_array(int* v, int i, int j, int k)
{
    int t;
    for (t = i; t <= j; t++)
    {
        v[t] = k;
    }
    return 0;
}

int main()
{
    int t;
    int size, value;
    int start, end;

    scanf("%d %d %d %d", &size, &start, &end, &value);

    int array[size];

    for (t = 0; t < size; t++)
    {
        scanf("%d", &array[t]);
    }

    set_array(array, start, end, value);

    for (t = 0; t < size; t++)
    {
        printf("%d\n", array[t]);
    }

    return 0;
}
5
  • Aside: you know what int n, i, j, k, t; are for, but we don't. Code is easier to follow when meaningful identifier names are used. Commented Nov 26, 2020 at 14:25
  • 1
    It is not wrong. You did not explicitly set elements [0], [1], [3] and [4], and they happened to be 0. Commented Nov 26, 2020 at 14:31
  • 1
    @WeatherVane Okay! I'll fix it Commented Nov 26, 2020 at 14:33
  • Which ones should I close? Commented Nov 26, 2020 at 14:43
  • 2
    Now that the typos are fixed, I cannot reproduce the problem. So, the close reason is still valid. Commented Nov 26, 2020 at 14:50

2 Answers 2

2

The initialization of the array is incorrect. In scanf and printf the i should be replaced by the letter t.

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

Comments

1

You are mixing t and i as the for loops indexes:

for (t = 0; t < n; t++)
{
    scanf("%d", &ary[i]);
}

In this case you only scan i position, not the t running the for loop Be careful using many one letters variables...

4 Comments

I guess it needs clarification
I'm not sure why it's 0. I entered 5 2 2 0 and 1 2 3 4 5 and they all changed to 0. And which ones weren't scanned?
A uninitiated array has undefined behavior (sorta), if you try and read it before any value is added it can show any value, in your case a bunch of zeroes. change your scan loop to for (t = 0; t < n; t++){scanf("%d", &ary[t]);} and you'll read the t'th element on every iteration
I missed the original typo.

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.