c中的动态内存分配会在一定大小时引发错误
我试图创建一个数组(动态)并用随机数填充它 我在Linux上。程序编译时没有错误。这是C代码:c中的动态内存分配会在一定大小时引发错误,c,dynamic-memory-allocation,C,Dynamic Memory Allocation,我试图创建一个数组(动态)并用随机数填充它 我在Linux上。程序编译时没有错误。这是C代码: #include <stdio.h> #include <stdlib.h> #include <time.h> void create_array(int **, int); void populate_array(int *X, int size, int low, int high); void display_array(int *X, int size)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void create_array(int **, int);
void populate_array(int *X, int size, int low, int high);
void display_array(int *X, int size);
int main()
{
int *A = NULL;
int size = 7;
int low = 10;
int high = 1000;
create_array(&A, size);
populate_array(A, size, low, high);
display_array(A, size);
return 0;
}
void create_array(int **X, int size)
{
*X = (int *)(malloc(size));
}
void populate_array(int *X, int size, int low, int high)
{
srand(time(0));
for (int i = 0; i < size; ++i)
{
*(X + i) = low + rand() % (high + 1 - low);
}
}
void display_array(int *X, int size)
{
for (int i = 0; i < size; ++i)
{
if (i % 10 == 0)
printf("\n");
printf("%d\t", *(X + i));
}
printf("\n");
}
相反,C++中的相同程序(几乎)给了我预期的输出。代码如下:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void create_array(int *&, int);
void populate_array(int *X, int size, int low, int high);
void display_array(int *X, int size);
int main()
{
int *A;
int size = 100;
int low = 10;
int high = 1000;
create_array(A, size);
populate_array(A, size, low, high);
display_array(A, size);
return 0;
}
void create_array(int *&X, int size)
{
X = new int[size];
}
void populate_array(int *X, int size, int low, int high)
{
srand(time(0));
for (int i = 0; i < size; ++i)
{
X[i] = low + rand() % (high + 1 - low);
}
}
void display_array(int *X, int size)
{
for (int i = 0; i < size; ++i)
{
if (i % 10 == 0)
cout << endl;
cout << X[i] << "\t";
}
cout << endl;
}
#包括
#包括
#包括
使用名称空间std;
void创建_数组(int*&,int);
空填充_数组(int*X,int-size,int-low,int-high);
无效显示_数组(int*X,int-size);
int main()
{
int*A;
int size=100;
int低=10;
int高=1000;
创建_数组(A,大小);
填充_数组(A、大小、低、高);
显示_阵列(A,大小);
返回0;
}
void创建数组(int*&X,int size)
{
X=新整数[大小];
}
无效填充数组(int*X、int-size、int-low、int-high)
{
srand(时间(0));
对于(int i=0;i大小
字节数也许您想要的是
*X = malloc(sizeof(int)*size);
注意:malloc将要分配的字节数作为参数。
同样对于c
实现,您可能需要阅读
您正在分配大小
字节数也许您想要的是
*X = malloc(sizeof(int)*size);
注意:malloc将要分配的字节数作为参数。
同样对于c
实现,您可能需要阅读
Ryyk:我用GCC来C++和G++做C++。
*X = malloc(sizeof(int)*size);