Tag: dynamic memory allocation

为什么我不能动态分配这个结构字符串的内存?

比方说,我有一个结构: typedef struct person { int id; char *name; } Person; 为什么我不能做以下事情: void function(const char *new_name) { Person *human; human->name = malloc(strlen(new_name) + 1); }

如何在C中动态分配2D数组?

所以我有一个带结构的程序 typedef struct s_struct { int rows; int cols; char* two_d; //This is supposed to be the 2D array } *GRID; 我想创建一个敲击并动态分配内存,然后填充2D数组,但我不知道如何。 这是我对create(int prows,int pcols)函数的作用: GRID grid = malloc(sizeof(struct s_struct)); grid ->rows = prows; grid ->cols = pcols; grid ->two_d = malloc(sizeof(char) * (rows*cols)); 我不明白这是如何创建一个2D数组,如果它甚至如此,以及如何填充数组。

将Struct复制到函数C中的指针数组

我在C中分配内存有一个很大的问题 我有这个结构 typedef struct{ int x; int y; }T; 我想创建一个动态添加结构到指针的函数。 就像是: int main() { T* t; f(&t); free(t); } 到目前为止,我认为一切都很好,现在function是我迷路的地方 void f(T** t) { T t1; T t2; T t3; //first i malloc *t=malloc(sizeof(T)*T_MAX_SIZE);//i want another function to make the array bigger, but this is not as important as the problem t1.x=11; t1.y=12; t2.x=21; t2.y=22; […]

如何在C中找到动态分配的数组的大小?

我创建了一个由循环动态分配的数组。 然后是一个循环,从数组中读取数字,但我需要知道数组的大小。 该数组正确且完全正常,并且其中包含正确的值。 我像这样定义了数组: int *array; 现在当我想使用它时它不会工作因为我使用指针: int size = sizeof(array)/sizeof(array[0]); 我如何修复它,以便它与我的指针一起工作?

正确使用realloc()

从man realloc:realloc()函数返回一个指向新分配的内存的指针,该内存适用于任何类型的变量, 可能与ptr不同,如果请求失败,则返回NULL。 所以在这段代码中: ptr = (int *) malloc(sizeof(int)); ptr1 = (int *) realloc(ptr, count * sizeof(int)); if(ptr1 == NULL){ //reallocated pointer ptr1 printf(“Exiting!!\n”); free(ptr); exit(0); }else{ free(ptr); //to deallocate the previous memory block pointed by ptr so as not to leave orphaned blocks of memory when ptr=ptr1 executes and ptr moves on to another […]