在新的char *分配之后验证字符指针数组的位置 [英] Validate locations of character pointer array after new char* allocation

查看:119
本文介绍了在新的char *分配之后验证字符指针数组的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好。



我有以下数组字符指针



Hello all

I have the following array of character pointers

char** test = new char*[256];





现在这个数组被传递给填充部分位置的功能。我的问题是如何检查其他未填充指针的状态?或者这些指针的状态是什么?

例如我有这个:





Now this array is passed to a function that fills "some" of its locations. My questions is how to check the status of other unfilled pointers? Or what is the status of these pointers?
for example I have this:

test[0] = "hello";
test[1] = "world!";





如何查看任何其他254个指针的状态?我测试了它们不是NULL,不是0,不是'\0'。我的问题是我有一个程序有时会访问这些指针然后崩溃,根本没有处理机制。



How to check the status of any of the other 254 pointers? I tested them they are not NULL, not 0, not '\0'. My problem is I have a program that sometimes access these pointers and then crashes, no handling mechanism at all.

推荐答案

只需用0初始化指针数组:

Just initialize the pointer array with 0 like this:
char** test = new char*[256] = {};




char* test[256] = {}



请注意,由于初始化列表为空,因此将自动填充为0。请参见此处 [ ^ ]了解更多信息。



固定的初始化声明 - 遗憾的是它赢了使用堆变量[/ edit]



[edit2]

nv3指出后我尝试使用new初始化数组,它确实适用于MS VisualSTudio 2010.我无法确定对此行为的引用,因此我只能报告适用于此编译器的内容:


Note that since the initialization list is empty, it will be padded with 0 automatically. See here[^] for more info.

[edit]fixed intialization statement - sadly it won't work with heap variables[/edit]

[edit2]
After nv3 pointed it out I tried initializing the array using new, and it does indeed work with MS VisualSTudio 2010. I couldn't pinpoint a reference to this behaviour though, so I can only report what works with this compiler:

char *test[256] = nullptr;
test = new char*[256](); // note the pair of rounded brackets!
assert(test[123] == 0); // works!
delete [] test;
test = new char*[256]; // no brackets this time
assert(test[123] == 0); // will most likely fail! (compiler dependend)



[/ edit2]


[/edit2]


这是一个要测试的示例。如果没有初始化(指向已分配的内存),访问**测试将失败。



Here is a sample to test. Access to **test will fail if not initialised (pointing to allocated memory).

void CTest::Run()
{
char** test = new char*[256];
FILE *f;
fopen_s (&f,"b.txt","w");
fprintf(f,"**test: 0x%x\n",test);
for(int i=0;i<256;i++)
{
fprintf(f,"*test %d=> 0x%x\n",i, *test);
//fprintf(f,"test[i] %d=> 0x%x\n",i, **test);//access violation
test++;
}
fclose(f);
}





输出样本:





Output sample:

**test: 0x6d3f68
*test 0=> 0xcdcdcdcd
*test 1=> 0xcdcdcdcd


大家好:D



我认为它已经处理好了,看来所有其他的在填充数组后,char **测试中的未填充位置被赋予NULL,因此我所要做的就是检查值是否为空。谢谢大家的帮助:D
Hello all :D

I think it's already handled, it appears that all other unfilled locations in the char** test are given NULL after filling the array so all I had to do is to check if the value is null or not. Thanks all for the help :D


这篇关于在新的char *分配之后验证字符指针数组的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆