c++中如何赋值给char *数组[]
how to assign value to char * array[] in C++
我想将字符串赋值给char数组
这里是代码-
char *resultArray[100];
int cnt = 0;
void MySAX2Handler::startElement(const XMLCh* const uri, const XMLCh* const localname,
const XMLCh* const qname, const Attributes& attrs)
{
char* message = XMLString::transcode(localname);
resultArray[cnt] = message;
cnt++;
for (int idx = 0; idx < attrs.getLength(); idx++)
{
char* attrName = XMLString::transcode(attrs.getLocalName(idx));
char* attrValue = XMLString::transcode(attrs.getValue(idx));
resultArray[cnt] = attrName;
cnt++;
resultArray[cnt] = attrValue;
cnt++;
}
XMLString::release(&message);
}
在遍历resultArray之后,它打印一些垃圾值
attrName
和attrValue
都是指针,而char
是一种整数类型,因此赋值操作符将简单地复制指针的值(地址),而不是内容。
循环遍历字符串或使用strcpy()
的某个版本,或者实际上使用c++字符串库之一。
首先,当你声明数组时,你应该使用
char *resultArray = new ResultArray[100];
和
char *resultArray[100];
接下来,在不知道循环的极限的情况下,不应该使用循环来填充有界数组。您将溢出您的数组,并导致段错误。当然,除非你知道你的长度不会接近100。(仍然是一个坏主意,但迅速拼凑起来,我不会抱怨)
没有更多的信息,我不能告诉你为什么你得到垃圾。你是怎么打印出来的?这些"转码"功能做什么?数据从何而来?
PS -记住你可以使用
resultArray[cnt++] = attrName;
resultArray[cnt++] = attrValue;