Tag: malloc

如何在C中的结构中初始化const(使用malloc)

我试过了; void *malloc(unsigned int); struct deneme { const int a = 15; const int b = 16; }; int main(int argc, const char *argv[]) { struct deneme *mydeneme = malloc(sizeof(struct deneme)); return 0; } 这是编译器的错误: gereksiz.c:3:17: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token 而且,这也是; void *malloc(unsigned int); struct deneme { const […]

malloc如何运作?

可能重复: free和malloc如何在C中工作? 考虑一种情况,我必须通过malloc分配大约20个字节的内存。 对于malloc()的函数调用是否成功,20个字节是否应该在内存中连续可用或者是否可以分散? 例如,在上面的例子中,如果有4个或5个块,每个10个字节,malloc会工作吗? 或者这是特定于操作系统还是特定于编译器?

嵌入式系统上的malloc行为

我目前正在开发一个嵌入式项目(STM32F103RB,CooCox CoIDE v.1.7.6 with arm-none-eabi-gcc 4.8 2013q4),我正在尝试理解当RAM满时malloc()在纯C上的行为。 我的STM32有20kB = 0x5000Bytes的RAM,0x200用于堆栈。 #include #include “stm32f10x.h” struct list_el { char weight[1024]; }; typedef struct list_el item; int main(void) { item * curr; // allocate until RAM is full do { curr = (item *)malloc(sizeof(item)); } while (curr != NULL); // I know, free() is missing. Program is supposed […]

为什么要输入一个void指针?

作为C的新手,我从void指针中获得的唯一实际用法是用于在给定指针中存储不同数据类型的多function函数。 因此,在进行内存分配时,我没有输入指针。 我见过一些有时使用void指针的代码示例,但是它们是类型转换的。 为什么这有用? 为什么不直接创建所需类型的指针而不是void?

malloc一个struct指针数组

我有以下结构: typedef struct _chess { int **array; int size; struct _chess *parent; } chess; 我有: typedef struct _chess *Chess; 现在,我想创建一个动态长度数组来存储指向struct结构的指针,所以我做了以下内容: Chess array [] = malloc(size * sizeof(Chess)); 这给了我一个错误:初始化程序无效。 如果我放弃[]并执行此操作: Chess array = malloc(size * sizeof(Chess)); 它编译没有错误,但当我尝试通过执行以下操作将此数组的元素设置为NULL: array[i]=NULL; 我收到一个错误:从类型’void *’分配类型’struct _chess’时出现不兼容的类型 知道我做错了什么吗? 谢谢。

没有malloc的C中的链接列表

#include typedef struct node { int i; struct node *next; }node; node getnode(int a) { struct node n; ni=a; n.next=NULL; return n; } main() { int i; node newtemp,root,temp; scanf(“%d”,&i); root=getnode(i); temp=root; while(i–) { newtemp=getnode(i); temp.next=&newtemp; if(root.next==NULL) { root=temp; } temp=*(temp.next); } temp=root; while( temp.next != NULL ) { printf(” %d “,temp.i); temp=*(temp.next); } } […]

为什么我不应该对未由malloc()分配的变量调用free()?

我在某处读到使用free来摆脱一个不是通过调用malloc创建的对象是灾难性的,这是真的吗? 为什么?

C中的malloc()有哪些有用的例子?

我只是在C中阅读有关malloc()的内容。 维基百科的文章提供了一个例子 ,但是与int array[10]相比,它只为10个整数的数组分配了足够的内存。 不是很有用。 你何时决定使用malloc()不是C为你处理内存?

malloc – 从void *到double *的无效转换

我想编写一个使用指针创建双数组副本的函数。 到目前为止这是我的代码: #include #include double* copy (double *array, int size) { double *v=malloc(sizeof(double)*size); for (int i=0; i<size; i++) *(v+i)=*(array+i); return v; } int main () { //double array[]; int size; printf ("size= "); scanf ("%i",&size); double *array=malloc(sizeof(double)*size); for (int i=0; i<size; i++) scanf("%f",&array[i]); copy(array,size); free(array); } 我有2个编译错误,我无法摆脱。 我明白了 无效转换从void *到double * 当我尝试使用malloc分配内存但我无法理解我做错了什么。

在C中为结构分配内存

我的任务是创建一个为结构动态分配内存的程序。 通常我们会用 x=malloc(sizeof(int)*y); 但是,我对结构变量使用了什么? 我认为不可能这样做 struct st x = malloc(sizeof(struct)); 有人可以帮帮我吗? 谢谢!