Write the following program running results:
#include<stdio.h>#include<string.h>int main(){int a[2000];char *p = (char*)a;for( int i = 0; i < 2000; i++)a[i] = -1 - i;printf( "%d\n", strlen(p));return 0;}
Please do not run it. I will use a draft to calculate it. Can it be calculated?
This is the first question in the online fast technology 2011 campus recruitment pen exam. I have a very good quality in mind, but I did not know this question when I saw it. Someone did write code like this, so I didn't do it at the time, I did not understand it after running it. I suddenly understood it when I was just eating it. I would like to record and share it with you. The running result is:
1020
Resolution:
First, you must understand the storage method of negative numbers in the memory, and also know the number of digits each of int and char (all are the most basic ). It is easy to know here:
A [0] =-1 memory should be: 11111111 11111111 11111111 11111111
A [1] =-2 memory should be: 11111111 11111111 11111111 11111110
A [2] =-3 memory should be: 11111111 11111111 11111111 11111101
......
A [255] =-256 memory should be: 11111111 11111111 1111111100000000
When the program calculates strlen (P), it stops when it encounters 8 zeros, so it is 255*4 + 3 = 1023.
Why the result is 1020? (PS: My CPU is intel, and Intel's CPU is usually small-end storage) This involves memory storage issues.
As we all know, memory storage is divided into big-end and small-end storage. Big-end storage is what we humans understand. High-end storage is written in front, and its position is written in the back, while small-end storage is the opposite, so the expression of a [255] =-256 in the memory is: 00000000 11111111 11111111 11111111, which is why the answer is 1020. Of course, different machines may be different. It would be better if you make a note during the test.
Code for judging large-end and small-end:
#include<stdio.h>int check(){union check{int i;char ch;}c;printf("%d\n" , &c.i);printf("%d\n", &c.ch);c.i =1;return (c.ch == 1);}int main(){int ret;ret = check();if(ret == 1){printf("little\n");}else{printf("Big\n");}return 0;}