code.club

 找回密碼
 立即註冊
搜索
查看: 6789|回復: 3

有關字元陣列大小宣告的問題

[複製鏈接]
發表於 2016-3-31 02:18:59 | 顯示全部樓層 |閱讀模式
#include <iostream>
#include <stdio.h>
#include <cstdlib>
using namespace std;



class test{
        public:
       
        int x;
        char *s;//這裡沒有先指定字串大小
       
        test(int y, char *str):x(y),s(str)
        {}
       
               
        void show(){
                cout<<x<<" "<<s<<endl;
        }
        };
       
int main(){
       
        test t1(123,"qwertyuiopasdfghjklzx");//為何可以隨意填入多少字呢?       
        t1.show();
       
        return 0;
}
回復

使用道具 舉報

 樓主| 發表於 2016-3-31 02:22:56 | 顯示全部樓層
#include <stdio.h>
#include <stdlib.h>

void test(char *s) //這裡也不用先給大小
{
        printf("%s",s);
       
}


int main(void){
       
        test("this is a good book for us, please buy it now!"); //這麼長也可以
       
        return 0;
}
回復 支持 反對

使用道具 舉報

 樓主| 發表於 2016-4-4 22:50:22 | 顯示全部樓層
未先指定字元陣列的大小的例子:

void test(char* s){
   最直接是一行程式碼:cout<<s;
   第二種是:
      char*str;
      str=(char*)malloc(sizeof(s));
      str = s;
      cout<<str;
第三種可能要有標頭檔,但C++部份該用哪個呢?
    char*str;
   str=new char[(strlen(s)+1];
   str=s;
   或strcpy(str,s);
  cout<<str;
}


int main(){

  test("this is a book!");

return 0;
}
回復 支持 反對

使用道具 舉報

 樓主| 發表於 2016-4-6 01:52:50 | 顯示全部樓層
#include <iostream>
#include <string.h>
using namespace std;

void test1(char*s){
        char*str;
        str=s;
        cout<<str<<endl;
}

void test2(char*s){
        char*str;
        str=new char[strlen(s)+1];
        strcpy(str,s);
        cout<<str<<endl;
        delete [] str;
}

void test3(char*s){
        char*str;
        str=(char*)malloc(sizeof(s));
        strcpy(str,s);
        cout<<str<<endl;
        delete[] str;
}

void test4(char*s){
        char*str;
        str=(char*)malloc(sizeof(s));
        str=s;
        cout<<str<<endl;
        delete[] str;
}

int main(){
       
        test1("this is 1");
        test2("this is 2");
        test3("this is 3");
        test4("this is 4");//這一項雖會得出執行結果,但最終卻會出現錯誤訊息。       
       
       
                return 0;
}
回復 支持 反對

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

小黑屋|手機版|Archiver|code.club  

GMT+8, 2024-3-29 07:23 , Processed in 0.095544 second(s), 19 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表