commit fdbbc27 code中文原文

A Simple Question About C++ Arrays

Author
Yujia Lin
Date
Reading time
1 min read

Translated from Chinese by Claude. Read the original

Yesterday I actually got stumped by a dead-simple C++ question. Here it is. The question:

1
2
设有下定义的语句: [c]int a3={10,20,30,40,50,60}; int b3={10,20,30,40,50,60};[/c] 则a1*b2的结果为() 
A)2000        B)1200      C)2400        D)3000

As it turned out, I just couldn’t work it out. I mixed up the declared size with the index (something like that, anyway)~ Let me explain. For example: a[x][y]={}; x and y only tell the computer how much memory to allocate. They aren’t addresses, and they don’t count from 0, whereas the positions of the data are counted by address. For example, if you fill in numbers for a[2][3]={}, the addresses are a[0][0]    a[0][1]    a[0][2] a[1][0]    a[1][1]    a[1][2] and not a[1][1]    a[1][2]    a[1][3] a[2][1]    a[2][2]    a[2][3] Remember that the computer counts from 0 in memory, and that’s basically true across the whole C family. So the index and the allocated size are counted differently. Here’s a screenshot of me checking it in VC++ Screenshot of the check The answer is C) 2400. Here’s the code I used to check it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

// 数组测试.cpp

//

#include "stdafx.h";

#include "iostream";

using namespace std;

void main()

{

int a[3][2]={10,20,30,40,50,60};
int b[3][2]={10,20,30,40,50,60};
cout<<a[1][1]*b[2][1];
}

If anything here is wrong, please point it out~

Esc

Keyboard shortcuts

Ctrl K /
Search and commands
j k
Next or previous post in a list
Enter
Open the selected post
h l
Older or newer post (on a post)
g h
Go to the log
g a
Go to the archive
g t
Go to tags
g s
Go to stats
t
Switch light or dark theme
r
Random post
?
Show this help