英文:
2D memory allocation
问题
我正在尝试修改我的程序,
我遇到的问题实际上是字符串数组的分配。
尝试运行以下程序时,我遇到了以下错误 -
#include <iostream>
#include <cstdlib>
using namespace std;
void function_manipulate(unsigned int **arr_str, unsigned int *arr_len)
{
*arr_len = 3;
int len = *arr_len;
// *arr_str = (unsigned char *)malloc(sizeof(unsigned char *)*(*arr_len));
*arr_str = new unsigned int *[len];
for (int i = 0; i < len; i++)
{
cout << (*arr_str)[i] << '\n';
}
}
int main()
{
unsigned int *array_string = NULL;
unsigned int array_length = 0;
function_manipulate(&array_string, &array_length);
}
输出结果如下:
0
0
0
英文:
I am trying to modify my program,
The prblem I am running into is actually the array of string allocation.
When trying to run the below program, I am getting the below error -
#include <iostream>
#include <cstdlib>
using namespace std;
void function_manipulate(unsigned int **arr_str, unsigned int *arr_len)
{
*arr_len = 3;
int len = *arr_len;
// *arr_str = (unsigned char *)malloc(sizeof(unsigned char *)*(*arr_len));
arr_str = new unsigned int *[len];
for (int i = 0; i < len; i++)
{
cout << arr_str[i] <<'\n';
}
}
int main()
{
unsigned int *array_string = NULL;
unsigned int array_length = 0;
function_manipulate(&array_string, &array_length);
}
The output looks like:
0
0
0
答案1
得分: 0
我认为这是您试图做的事情。
#include <iostream>
#include <cstdlib>
using namespace std;
void function_manipulate(unsigned int **arr_str, unsigned int& arr_len)
{
arr_len = 3;
int len = arr_len;
*arr_str = new unsigned int [len];
for (int i = 0; i < len; i++)
{
(*arr_str)[i] = 1234;
}
}
int main()
{
unsigned int *array_string = NULL;
unsigned int array_length = 0;
function_manipulate(&array_string, array_length);
if (array_string != NULL){
cout << "array_length now is " << array_length << endl;
for (int i = 0; i < array_length; i++)
{
cout << array_string[i] << '\n';
}
delete[] array_string;
}
return 0;
}
请注意,这段代码相当丑陋,我不建议这样做,但是它确实可以工作。
英文:
I think this is what you are trying to do.
#include <iostream>
#include <cstdlib>
using namespace std;
void function_manipulate(unsigned int **arr_str, unsigned int& arr_len)
{
arr_len = 3;
int len = arr_len;
// *arr_str = (unsigned char *)malloc(sizeof(unsigned char *)*(*arr_len));
*arr_str = new unsigned int [len];
for (int i = 0; i < len; i++)
{
(*arr_str)[i] = 1234;
//cout << arr_str[i] <<'\n';
}
}
int main()
{
unsigned int *array_string = NULL;
unsigned int array_length = 0;
function_manipulate(&array_string, array_length);
if (array_string != NULL){
cout << "array_length now is " << array_length << endl;
for (int i = 0; i < array_length; i++)
{
cout << array_string[i] <<'\n';
}
delete[] array_string;
}
return 0;
}
Note that this is pretty ugly and I would not recommend it. But it can be done.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论