C,C++容易被忽略的问题

1.字符串数组,字符串指针可以直接输出

char s2[30]="I am a student";
cout<<s2<<endl;
char *p="I am a student";
cout<<p<<endl;
cout<<p[2]<<endl;

2.指针变量p分配4个存储单元。

用指针变量处理字符串,要比用数组处理字符串方便。
指针变量用于存放变量地址,而地址通常为4字节,所以指针变量的长度均为4个字节。

#include<stdio.h>

void main()
{
    int c=sizeof(char);//1
    int i=sizeof(int);//4
    int l=sizeof(long);//4
    int d=sizeof(double);//8
    int p=sizeof(int *);//4
    int q=sizeof(char *);//4

    printf("%d	%d
",c,i);
    printf("%d	%d
",l,d);
    printf("%d	%d
",p,q);
}
View Code

3.static关键字定义静态变量时,相当于只执行第一次。下面程序结果为6

#include<stdio.h>
#include<stdlib.h>
c(int i)
{
    static int c=0;
    c+=i;
    printf("%d
",c);
    return c;
}

int main()
{
int j,i;
for(i=0;i<=3;i++)
{
    j=c(i);
}
printf("%d
",j);
}
View Code

4.printf()函数从右往左执行

    int *p;
    int a[]={3,12,9};
    p=&a;
    printf("%d	%d",*p,*p++);//12 3
View Code

5.循环次数不确定时如何设计?

 for (;*p2++=*p1++;); //用指针拷贝字符串
【例7.10】用指针实现字符串拷贝。执行后输出:
  s1= I am a student
  s2= I am a student

#include<iostream>
#include<string.h>
using namespace std;
int main(void)
{
    char *p1="I am a student";
    char s1[30],s2[30];
    strcpy(s1,p1); //用命令拷贝字符串
    char *p2=s2; //将数组s2首地址赋p2
    for (;*p2++=*p1++;); //用指针拷贝字符串
    cout<<"s1="<<s1<<endl;
    cout<<"s2="<<s2;
}
View Code
#include<iostream>
#include<string.h>
using namespace std;
int main(void)
{
    char *p1="I am a student";//14
    char s1[30],s2[30];
    strcpy(s1,p1); //用命令拷贝字符串
    char *p2=s2; //将数组s2首地址赋p2
    int i=1;
    for (;*p1++;i++)cout<<i<<endl; //用指针拷贝字符串
    cout<<"s1="<<s1<<endl;
}
View Code

while(*p1!=' '){...}

6.strlen()求字符串长度

#include<stdio.h>
#include<string.h>//包含该头文件
int main()
{
    char *p="abcbc";
    int a=strlen(p);
    printf("%d",a);//5
}
View Code

-------------------

to be continued…

原文地址:https://www.cnblogs.com/anwcq/p/C_wenti.html