字符串string 字符數組與指向字符串的指針pchar的區別與聯繫

  這3者的基本概念相同,但有一些非常細微的差別,在編程時稍不注意就會出錯,需高度重視。
  1、使用指向字符串的指針,如果不是以0結尾,運行時就會出現錯誤。爲了避免這種錯誤,需要在字符串結尾人工加入0 即char(0),或用strpcopy函數在字符串結尾自動加0。
  例1: 指向字符串的指針,如果不是以0結尾,運行時會出現錯誤(pchar是以0#結尾,而string不是):
  {s[0]=3 s[1]='n' s[2]='e' s[3]='w'}
  var
     s:string;
           p:pchar;
  begin
     s:='new';
       label1.caption:=s; {new}
       label2.caption:=intTostr(integer(s[0]));{3是字符串的長度}
     p:=@s[1];{不是以0結尾,莫用pchar型指針}
     label3.caption:=strpas(p); {運行時出現錯誤}
  end;

  例2:在字符串結尾人工加入0即char(0),可使用指向字符串的指針。
  {s[0]=4 s[1]='n' s[2]='e' s[3]='w' s[4]=0;}
  {p-->'new'}
  var
            s:string;
            p:pchar;
  begin
     p:=@s[1];
     s:='new'+char(0); {以0結尾,可用pchar型指針}
     label1.caption:=strpas(p); {new}
     label2.caption:=s; {new}
     label3.caption:=intTostr(integer(s[0])); {4是字符串長度}
  end;

  例3: 用strpcopy函數賦值會在字符串s結尾自動加0。
  {s[0]=4 s[1]='n' s[2]='e' s[3]='w' s[4]=0;}
  {p-->'new'}
  var
           s:string;
           p:pchar;
  begin
    p:=@s[1];
      strpcopy(p,'new');{strpcopy函數在字符串結尾自動加0}
    label1.caption:=strpas(p);{new}
   label2.caption:=s;{new}
    label3.caption:=intTostr(integer(s[0]));{4}
  end;

  2、下標爲0的字符串標識符存放的是字符串長度,字符型數組基本相當於字符串,但不能存放字符串長度。字符串可以用s:='a string'的形式賦值,但是字符型數組a[ ]不可直接用a:='array'的形式賦值,用此種形式會出現類型不匹配錯誤,可選用strpcopy函數賦值。

  例4: 字符型數組s[ ]相當於字符串,但沒有存放字符串長度的位置。
  {s[1]='n' s[2]='e' s[3]='w' s[4]=0;}
  {p-->'new'}
  var
          s:array[1..10] of char;
          p:pchar;
  begin
     {s:='new'+char(0); error}{錯誤}
     p:=@s[1];
    {p:=@s; is not correct}
    strpcopy(p,'new');
    label1.caption:=strpas(p);{new}
    label2.caption:=s;{new}
   {label3.caption:=intTostr(integer(s[0]));}{不會出現4, 下標超出錯誤}
  end;

  例5:下標從0開始的字符數組s,s相當於@s[0]。
  { s[0]='n' s[1]='e' s[2]='w' s[3]=0;}{p-->'new'}
  var
          s:array[1..10] of char;
          p:pchar;
  begin
    {s:='new'+char(0); error}{錯誤}
      p:=s;
    {p:=@s[0] is also correct}
    strpcopy(p,'new');
    label1.caption:=strpas(p);{new}
    label2.caption:=s;{new}
    label3.caption:=s[0];{n}
    end;

  3、下標從0開始和從1開始的字符數組地址的表示方法也有細微不同:

  例6:下標從1開始的數組a 與下標從0開始的數組b 的比較。
  var
          a:array[1..10]of char;
          b:array[0..10]of char;
    {a:='1..10';}{type mismatch}
    {b:='0..10';}{type mismatch}
      begin
    strpcopy( b, 'from 0 to 10'); {正確 因爲b即是@b[0] }
    strpcopy(@b[0], 'from 0 to 10'); {正確 與上個表達式結果相同}
    strpcopy(@a[1], 'from 1 to 10'); {正確 }
    strpcopy( a, 'from 1 to 10'); {類型匹配錯誤 因爲a即是@a[0]}
    end;
  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章