问题
I'm trying to assign a value to a char**
variable. In my foo.h
I've defined a couple of variables such as
#define APIOCTET int
#define APILONG long
#define APICHAR char
#define APISTRING char*
Now in my foo.cpp
I'm tryng to use a method where
APILONG apiInitialize(APISTRING filePath, APISTRING* outputString)
{
//open text file to where output will be printed
//do other stuff, etc..
//return result;
}
I'd like to assign a value to my APISTRING* outputString
but I just can't figure out how to do so, I've tried many things which are basically a variation of the following code
APISTRING error = "error";
APISTRING other = "string";
APISTRING charArr[] = { error, other, error };
APISTRING *charArr2[] = { charArr };
errorString = *charArr2;
Also im not 100% clear on what exactly is APISTRING* outputString
. When I try to compile it gives me an error message where it mentions it's a char**
. Is it a 2D array?.. A pointer to an array of chars?.. But most importantly, how would I assign a value for this variable? Thanks in advance.
回答1:
The APISTRING* is a pointer to a pointer to char. It holds an address which holds the address of the first character of the string in memory.
See this question for more info on double pointers in C/C++.
To assign to the string you would need to do *outputString = "string"
回答2:
APISTRING* outputString will be pre-processed and replcaed at compile-time as char** outputstring. Hence, outputString will be double pointer hence, you need to do it like this (below code). I combined both .h and cpp together for simplicity.
#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;
}
I would recommend to use std::string, it'll be easy to tweak with certain behaviors. Hope this helps.
来源:https://stackoverflow.com/questions/31775571/c-set-value-for-a-char