[英]C++ Set value for a char**
我正在嘗試為char**
變量分配一個值。 在foo.h
我定義了幾個變量,例如
#define APIOCTET int
#define APILONG long
#define APICHAR char
#define APISTRING char*
現在在我的foo.cpp
嘗試使用一種方法
APILONG apiInitialize(APISTRING filePath, APISTRING* outputString)
{
//open text file to where output will be printed
//do other stuff, etc..
//return result;
}
我想為我的APISTRING* outputString
分配一個值,但我只是不知道該怎么做,我嘗試了很多事情,這些事情基本上是以下代碼的變體
APISTRING error = "error";
APISTRING other = "string";
APISTRING charArr[] = { error, other, error };
APISTRING *charArr2[] = { charArr };
errorString = *charArr2;
我也不是100%清楚APISTRING* outputString
到底是什么。 當我嘗試編譯時,它給我一個錯誤消息,提示它是char**
。 它是2D數組嗎?。指向字符數組的指針嗎?..但是最重要的是,如何為該變量分配值? 提前致謝。
APISTRING *是指向char的指針。 它包含一個地址,該地址保存內存中字符串的第一個字符的地址。
有關C / C ++中雙指針的更多信息,請參見此問題 。
要分配給字符串,您需要執行*outputString = "string"
將對APISTRING * outputString進行預處理,並在編譯時將其替換為char ** outputstring。 因此,outputString將是雙指針,因此,您需要這樣做(下面的代碼)。 為了簡單起見,我將.h和cpp結合在一起。
#include<iostream>
using namespace std;
#define APIOCTET int
#define APILONG long
#define APICHAR char
#define APISTRING char*
APILONG apiInitialize(APISTRING filePath, APISTRING* outputString)
{
APISTRING getIt = *outputString;
cout<<" "<<getIt<<endl;
}
int main()
{
APISTRING str = "hello";
APISTRING* outputString = &str;
APILONG val = apiInitialize("world", outputString );
system("PAUSE");
return 0;
}
我建議使用std :: string,通過某些行為進行調整很容易。 希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.