0

While I was doing cs50 week2.

I found something hard to understand.

#include<stdio.h>


void set_array(int array[4]);
void set_int(int x);

int main(void)
{
    int a = 10;
    int b[4] = {0, 1, 2, 3};
    set_int(a);
    set_array(b);
    printf("%d %d\n", a, b[0]);
}

void set_array(int array[4])
{
    array[0] = 22;
}

void set_int(int x)
{
    x = 22;
}

it prints 10, 22. NOT 10, 0.

so I guessed that set_array function may comes first so not 0 but 22.

.

but this one down here, When I tried to play around...

#include<stdio.h>

void set_array(int array[4]);
void set_int(int x);

int main(void)
{
    int a = 10;
    int b[1];
    set_int(a);
    set_array(b);
    printf("%d %d\n", a, b[0]);
}

void set_array(int array[4])
{
    array[0] = 20;
    array[1] = 21;
    array[2] = 22;
    array[3] = 23;
}

void set_int(int x)
{
    x = 22;
}

This prints 21 20, NOT 10, 20.

Well if I change it to int b[4];, it prints 10, 20 as expected.

Is there something wrong on cs50 IDE? or just I don't understand them yet.

Please let me know anything I am missing...

0

You're passing in arrays of smaller sizes into your function set_array with accepts arrays of size 4. By accessing indexes of an array that is out of its bounds, you have the potential of meddling with other data, which is what's happening here.

For the first example code, you print out b[1] after you change b[0]. Perhaps you meant to print out b[0]? When you make an int array, its initial values aren't set to zero. You would have to do it manually.

1
  • Oops sorry first code was a bit wrong, I corrected. But It was wrong that I put b[2] on second code and that tried to access an array of out bound, correct? – Minsu Apr 2 '20 at 19:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .