这是我在学习期间发现的:
#include<iostream>
using namespace std;
int dis(char a[1])
{
int length = strlen(a);
char c = a[2];
return length;
}
int main()
{
char b[4] = "abc";
int c = dis(b);
cout << c;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
所以在变量中int dis(char a[1]),[1]似乎什么都不做,根本不起作用
,因为我可以使用a[2].就像int a[]或char *a.我知道数组名称是一个指针,以及如何传达一个数组,所以我的谜题不是这个部分.
我想知道的是为什么编译器允许这种行为(int a[1]).或者它有其他我不知道的含义?
新学员; 关于指针的一些难题;
当我从书本中学习时,在使用指针之前必须对其进行初始化,因此我们通常会这样使用
int a = 12;
int * p = &a;
Run Code Online (Sandbox Code Playgroud)
所以我明白为什么int* p = 12 是错的,因为它没有地址;
然后我在编码的时候找到了一些东西,就是这样:
char * months[12] = {"Jan", "Feb", "Mar", "April", "May" , "Jun", "Jul"
,"Aug","Sep","Oct","Nov","Dec"};
Run Code Online (Sandbox Code Playgroud)
然后又出现了另一个常用的情况,那就是:
char *p = "string"; (this is ok , why int * a = 12 can't be allowed ?)
Run Code Online (Sandbox Code Playgroud)
我很困惑.什么时候初始化,如何?为什么int * a = 12不能自动初始化?也许是关于记忆的安排.
我不知道这个问题属于什么,请花点时间阅读.它涉及C和C++的差异以及编写代码的习惯; 代码如下:我把它分成3个文件; main.c
#include"myh.h"
unit_t *paa;
int main()
{
paa=(unit_t*)malloc(sizeof(unit_t));
if(paa==NULL){
printf("out of memory\n");
exit(1);
}
fuzhi(paa);
printf("hello !%d",paa->number);
free(paa->msg);
free(paa);
paa=NULL;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
anohter c:ke.c
#include"myh.h"
void fuzhi(unit_t* pa)
{
pa->number=3;
pa->msg=(char *)malloc(20);
printf("fuzhi !");
}
Run Code Online (Sandbox Code Playgroud)
h文件:myh.h
#ifndef P_H
#define P_H
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct{
int number;
char *msg;
}unit_t;
void fuzhi(unit_t* pa);
int a;
#endif
Run Code Online (Sandbox Code Playgroud)
所以问题是当我使用C运行代码时它没有问题,但当我将其保存为cpp时,错误是'a'的多个定义; 为什么?第二个问题是我不知道我安排代码是好还是不好的习惯.有人给我一些好建议吗?当代码很大时,我通常把声明放在h文件中并使用ac/cpp编写函数的定义.然后使用主c/cpp来满足主要功能.有人可以给我一些关于编写代码的好建议,我是一个新的学习者.谢谢.
这是我发现但当我使用"cout <时我无法理解一个地址
#include<iostream>
using namespace std;
int main()
{
char a[2]={'a','b'};
char b[3]="ab";
cout<<&a<<endl;
cout<<&b<<endl;
cout<<sizeof(a)<<endl<<cout<<sizeof(b);//the result of this I am puzzled
return 0;
}
Run Code Online (Sandbox Code Playgroud)
结果是:
0x28ff2e
0x28ff10
2
0x4453c43
Run Code Online (Sandbox Code Playgroud)