用栈声明的时候很明显,都是连续的。
在堆上的时候,由于是分批次分配内存(首先new出或malloc多少行,然后每一行再分别new),因此其存放是平行的几条连续存储,每一行是连续的,行与行之间并不连续。为此,我们尝试创建一个2X4的二维矩阵如下
A B C D
E F G H
打印其地址来证明。代码如下,为了直观,略去了一些安全检查。
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
#ifdef __cplusplus
extern "C" {
#endif
void C_stack();
void C_malloc();
void CXX_stack();
void CXX_new();
#ifdef __cplusplus
};
#endif
void C_stack(){
printf("====== C stack ======\n");
char str[2][4] = { {65,66,67,68}, {69,70,71,72} };
for(int i = 0; i < 2; i++){
for(int j = 0; j < 4; j++){
printf("[%c]%p\t", str[i][j], &str[i][j]);
}
printf("\n");
}
printf("=====================\n\n");
}
void C_malloc(){
printf("====== C malloc ======\n");
char **str = (char **)malloc(2*sizeof(char *));
for (int i = 0; i < 2; i++)
str[i] = (char*)malloc(4*sizeof(char));
char s = 'A';
for (int i = 0; i < 2; i++){
for(int j = 0; j < 4; j++){
str[i][j] = s++;
printf("[%c]%p\t", str[i][j], &str[i][j]);
}
printf("\n");
}
for (int i = 0; i < 2; i++)
free(str[i]);
free(str);
printf("====================\n\n");
}
void CXX_stack(){
cout<<"====== Cpp stack ======"<<endl;
char str[2][4] = { {65,66,67,68}, {69,70,71,72} };
for(int i = 0; i < 2; i++){
for(int j = 0; j < 4; j++){
cout<<"["<<str[i][j]<<"]"<<(void *)&str[i][j]<<"\t";
}
cout<<endl;
}
cout<<"======================"<<endl<<endl;
}
void CXX_new(){
cout<<"====== Cpp new ======"<<endl;
char **str = new char *[2];
for (int i = 0; i < 2; i++)
str[i] = new char [4];
char s = 'A';
for (int i = 0; i < 2; i++){
for(int j = 0; j < 4; j++){
str[i][j] = s++;
cout<<"["<<str[i][j]<<"]"<<(void *)&str[i][j]<<"\t";
}
cout<<endl;
}
for (int i = 0; i < 2; i++)
delete []str[i];
delete str;
cout<<"===================="<<endl;
}
int main(){
C_stack();
C_malloc();
CXX_stack();
CXX_new();
return 0;
}
编译运行:
admin@ubuntu: ~ $ g++ new.cpp -o app
admin@ubuntu: ~ $ ./app
====== C stack ======
[A]0x7fffa8e11cb0 [B]0x7fffa8e11cb1 [C]0x7fffa8e11cb2 [D]0x7fffa8e11cb3
[E]0x7fffa8e11cb4 [F]0x7fffa8e11cb5 [G]0x7fffa8e11cb6 [H]0x7fffa8e11cb7
=====================
====== C malloc ======
[A]0xec6030 [B]0xec6031 [C]0xec6032 [D]0xec6033
[E]0xec6050 [F]0xec6051 [G]0xec6052 [H]0xec6053
======================
====== Cpp stack ======
[A]0x7fffa8e11ca0 [B]0x7fffa8e11ca1 [C]0x7fffa8e11ca2 [D]0x7fffa8e11ca3
[E]0x7fffa8e11ca4 [F]0x7fffa8e11ca5 [G]0x7fffa8e11ca6 [H]0x7fffa8e11ca7
=======================
====== Cpp new ======
[A]0xec6050 [B]0xec6051 [C]0xec6052 [D]0xec6053
[E]0xec6030 [F]0xec6031 [G]0xec6032 [H]0xec6033
=====================