char **使用new运算符的内存分配 [英] char** memory allocation using new operator

查看:2336
本文介绍了char **使用new运算符的内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  char ** results = new char * [ numRes]; //这是它打破
的地方(int i = 0; i {
results [i] = new char [64]
}

这会导致堆错误的损坏。但肯定它应该工作?我将4个char *分配给字符指针列表,以便我们可以将它们传递给函数等。



我四处张望,但他们似乎都显示malloc和free ...我在课堂上使用它们,所以我想坚持使用c ++新的和删除。



有人可以借给我一只手吗?

解决方案

分配后你要做什么?你只分配了一个字符指针数组,你没有为每个元素(一个指针)分配空间。



例如,如果你想在分配后在结果[0]中存储任何内容,你也需要分配给它。例如:

  results [0] = new char [100]; //在写入结果之前需要分配[0]! 
strcpy(results [0],Test);

您不能仅仅复制到没有分配的结果[0]。这同样适用于结果的任何元素。


I'm truely baffled by this throwing an error....

    char** results = new char*[numRes];  //this is where it breaks
    for(int i = 0; i < numRes; i++)  
    {  
         results[i] = new char[64];  
    }  

It's throwing a corruption of the heap error. but surely it should work? Im assigning 4 char* to a list of character pointers so I can pass them into functions etc.

I looked around everywhere but they all seem to be showing the malloc and free... Im using them in classes so I want to stick to c++ new and delete.

Could someone lend me a hand please?

解决方案

What are you doing after you allocate? You only allocated an array of character pointers, you did not allocate space for each element (a pointer). If you try to store items in the elements, you'll run into problems.

For example, if you wanted to store anything in results[0] after your allocation, you would need to allocate to it as well. For example:

results[0] = new char[100]; // NEED TO ALLOCATE BEFORE WRITING TO results[0]!
strcpy(results[0], "Test");

You cannot just copy to results[0] without the allocation. The same holds for any element of results.

这篇关于char **使用new运算符的内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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