一种成功输出的方式:
//C语言的二维动态数组
#include<cstdio>
#include<string.h>
#include<malloc.h>
int main(){
char ** strs=(char **)malloc(sizeof(char*)*3);
int (*p)[20];
for(int i=0;i<3;i++){
strs[i]=(char *)malloc(sizeof(char) *20);
}
for(int i=0;i<3;i++){
scanf("%s",strs[i]);
}
printf("\n");
for(int i=0;i<3;i++){//输出整体字符串数组
printf("%s\n", *(strs+i) );
}
for(int i=0;i<3;i++){
free(strs[i]);
}
return 0;
}
另一种成功的输出方式:
#include<cstdio>
#include<string.h>
#include<malloc.h>
int main(){
char ** strs=(char **)malloc(sizeof(char*)*3);
int (*p)[20];
for(int i=0;i<3;i++){
strs[i]=(char *)malloc(sizeof(char) *20);
}
for(int i=0;i<3;i++){
scanf("%s",strs[i]);
}
printf("\n") ;
for(int i=0;i<3;i++){
printf("%s\n", (void *) strs[i]);
}
for(int i=0;i<3;i++){
free(strs[i]);
}
return 0;
}
效果一样
提出疑问:
strs[i]是char[20]的指针类型,
这样输出就会报错,
而直接用c++的cout<<strs[i]<<endl;就返回值。
找到解决的案例:
#include<iostream>
using namespace std;
int main(){
char *p="hello world";
//输出字符串首地址 方法1
cout<<(void *)p<<endl;
//输出字符串首地址 方法2
printf("%p\n",p);
//输出字符串
cout<<p<<endl;
//输出指针变量的地址,而非字符串地址
cout<<&p<<endl;
}
查找到的答案:
在C++中,为什么char *p=“hello world”; cout<<p<<endl;打印出来的是字符串,而不是地址?
回答:
指针p指向字符串常量"hello word",即p中存放该字符串的首地址,c++为了兼容c语言,当cout输出常量字符串的首地址时实际输出该字符串(对cout的<<运算符进行了重载,cout<<p被翻译为输出p指向的字符串值)。
cout<<(void *)p;则为p的内容,即字符串的地址,而cout<<&p;为指针变量的地址,而非上述字符串的地址。
上述解释,来自https://www.baidu.com/link?url=KHwtiLDV1vgg6SV3d5rwqf8LuBHQc_UPlYoncx9IJG7PwxXW_1T1mVparrzt0XocN8E1hFS4sURb1chQ_inG_q&wd=&eqid=84607ab50031e3e8000000065e57dff3