Lecture 3 | Programming Paradigms (Stanford)

Stanford · 291K views · 2008 · 52:49

Open on YouTube

University lectures & coursesC, C++, Rust, Go & systems languageslecture

Why Stack Overflow recommends it

Stack Overflow users link it when asking or answering questions about the int-to-short array casting example the professor demonstrates, which many learners try to reproduce and find confusing.

Recommended by 1 people across 1 different months, 2012 to 2017.

What it is

Lecture 3 of Stanford's CS107 Programming Paradigms, taught by Professor Jerry Cain. It covers C programming, including string duplication, string copy, and memory diagrams, with a demonstration of casting between int and short arrays.

What people said

Recommends Manan Mehta · 2017-03 · Stack Overflow · on “Why is this c code not changing the value of arr[3]?”

@kaylum Nope, that's not true.. When I cast it to a short array, it seemingly becomes an array of 10 short elements. When I change the 6 one, I am changing only half of arr[3]. Check out [this video] at 27.50 to see what I mean.

Recommends Manan Mehta · 2017-03 · Stack Overflow · on “Why is this c code not changing the value of arr[3]?”

Nope, this doesn't solve it. When I cast it to a short array, it seemingly becomes an array of 10 short elements. When I change the 6 one, I am changing only half of arr[3]. Check out [this video] at 27.50 to see what I mean.

Cites Bryce Thomas · 2012-01 · Stack Overflow · on “When casting an int array to a short*, why does assigning a value to an element overwrite the entire integer?”

I am watching Jerry Cain's Programming Paradigms Lecture 3 video [this video] where the effect of an element assignment after casting between an int array and short array is demonstrated. Essentially the argument is that if you were to assign an int array element arr[3] = 128 , then temporarily cast the int array to a short* and assign arr[6] = 2 , then arr[3] should become 128 + 512 = 640 because the 2 would be interpreted as being in the 2^9th position. Code to demonstrate: #include <stdio.h> int main() { printf("sizeof(int) is %lu\n", sizeof(int)); printf("sizeof(short) is %lu\n", sizeof(short)); int arr[5]; arr[3] = 128; ((short*)arr)[6] = 2; printf("arr[3] is equal to %d\n", arr[3]); //expec

Cites runners3431 · 2015-11 · Stack Overflow · on “Why doesn't this piece of code cast down and change the array value?”

I'm learning about c on c paradigms with stanford. [this video] The professor shows this piece of code and says it will change the bit pattern of the array. Shorts are 2 Bytes and Ints are 4 bytes. #include <iostream> int main() { int arr[5]; arr[3] = 128; // 0000 0000 1000 0000 ((short*)arr)[6] = 2; // 0000 0010 std::cout << arr[3]; // my compiler prints out 2, should it be 640? should be 512 + 128???? 1010000000 would be the bit pattern? return 0; }