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\t%d\n",c,i);
    printf("%d\t%d\n",l,d);
    printf("%d\t%d\n",p,q);
}
View Code

3.static關鍵字定義靜態變量時,相當於只執行第一次。下面程序結果為6

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

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

4.printf()函數從右往左執行

    int *p;
    int a[]={3,12,9};
    p=&a;
    printf("%d\t%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!='\n'){...}

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…

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM