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...

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Minsu
  • 5
  • 3
  • 4
    You wrote past the end of the array. That results in [undefined behavior](https://stackoverflow.com/questions/2397984). C doesn't do any bounds checking on array access. It's up to you to make sure that your code stays within the bounds of the array. – user3386109 Mar 31 '20 at 03:17
  • Thanks guys, sorry the first code was incorrect, 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 02 '20 at 18:59

0 Answers0