One-dimensional pointer traversed 2D array

zhaozj2021-02-12  157

The day before, I saw a post in Tsinghua Programming Technical Edition, saying that there is a code in Thanghaoqiang's book, can't be compiled, the code is as follows:

Main () {Int a [5] [5], * p; p = a; * (* (p 1) 1) = 10;

The problem is obvious, the one-dimensional pointer is used as a two-dimensional pointer, the problem is the end. I thought it was the following point of view: The operation of the pointer is carried out by dimension. And you have learned the data structure, you should know whether it is a single or multi-dimensional, linearly stored, this is the movement of the meaning of the pointer is jumping. Then obviously a one-dimensional pointer is impossible to traverse the multi-dimensional array. So the people who know the people will oppose.

So, I plan to refute it in fact. Write the following code:

#include "stdio.h"

#include "stdlib.h"

int main ()

{

INT I, J;

INT A [2] [3];

For (i = 0; i <2; i)

For (j = 0; j <3; J)

a [i] [j] = 10;

INT * P = a;

For (i = 0; i <2; i)

For (j = 0; j <3; J)

Printf ("% d / n", * ((p i * 3) j));

System ("pause"); return 0;} is not passed under DEV C . Just hi, but found that the compiler is wrong, it is this sentence: int * p = a; P can't point to A [0] [0]? I don't go, and then explicitly call A number of group headers. Modify as follows

#include "stdio.h"

#include "stdlib.h"

int main ()

{

INT I, J;

INT A [2] [3];

For (i = 0; i <2; i)

For (j = 0; j <3; J)

a [i] [j] = 10;

INT * P = & a [0] [0];

For (i = 0; i <2; i)

For (j = 0; j <3; J)

Printf ("% d / n", * ((p i * 3) j));

System ("pause"); return 0;} is actually completely correct! I initially got denied. But at this moment, I have forgotten this, I don't understand:

INT * P = a; int * p = & a [0] [0];

It is completely different, so I have tried all magazine INT * P [2] = A; // does not pass, this reasonable. The argument of the pointer is not initialized, int ** p = a; // does not pass, think about it, when the brain invested.

Later, the name of the file was abx.cpp, so changed to abx.c and try again, int * p = a; through compilation. The outlet is depressed.

Suddenly think of C is a strong type of language, today's justice.

The answer is as follows, p is int *. A is int [2] [3]. Obviously type does not match P is int * [2] or int * [3]? Oh, it is completed.

转载请注明原文地址:https://www.9cbs.com/read-6280.html

New Post(0)