在C中分配内存 [英] Allocate memory in C

查看:125
本文介绍了在C中分配内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我必须编写2个函数类型的void,它适用于指针的地址。第一个函数保留内存,用于类的对象数组。第二个函数保留内存,用于指向类对象的指针数组。我不知道它应该如何工作,我怎样才能提供和处理指针的地址。



我尝试了什么: < br $> b $ b

Hello,
I have to write 2 functions type of void which works on address of pointers. First function reserve memory for array of objects of class. Second function reserve memory for array of pointers to object of class. I don't know how it should work and how can I deliver and work on adress of pointer.

What I have tried:

#include <stdlib.h>
#include <stdio.h>

class my_class {
	int i;
};

void FAlocate(my_class ***Tab, int amount) {
	Tab = (my_class**)malloc(sizeof(my_class*)*amount);
	for (int i = 0; i < amount; i++) {
		Tab = (my_class*)malloc(sizeof(my_class));
	}
}

void FAlocate(my_class **Tab, int amount) {
	*Tab = (my_class*)malloc(sizeof(my_class)*amount);
}

int main(void)
{
	int N = 10;
	my_class **Tab=NULL;
	my_class *Tab1 = NULL;
	FAlocate(&*Tab, N);
	FAlocate(&Tab1, N);
}

推荐答案

首先,这不是C,这是C ++(你有一个类!),其次,因为这是C ++,为什么你可以轻松地使用其他方法做同样的事情 - 为什么指针到指针指针?也许你在函数中混淆了指针 - 数组声明,

First thing, this is not C, this is C++ (you have a class in it!), secondly, since this is C++, why involve too much of a pointer stuff, when you can easily use other methods to do the same thing—why pointer-to-pointer-to-pointer? Maybe you are confusing the pointers-are-arrays statement a bit much, in your function,
void FAlocate(my_class ***Tab, int amount) {
	Tab = (my_class**)malloc(sizeof(my_class*)*amount); // my_class** to my_class***? 
	for (int i = 0; i < amount; i++) {
		Tab = (my_class*)malloc(sizeof(my_class)); // my_class* to my_class***
	}
}

为指针指向内存,然后继续用循环内的指针值更新指针。相反,您正在尝试使编译器构建一个程序,其中语言构造和类型安全性不受尊重。难道你不认为应该这样吗?

You allocate the memory for pointer-to-pointer, and then keep updating that with a pointer value inside the loop. Instead what you are doing is, that you are trying to make the compiler build a program where the language constructs and type safety are not being respected. Don't you think it should be, this?

void FAlocate(my_class ***Tab, int amount) {
	Tab = (my_class**)malloc(sizeof(my_class*)*amount);
	for (int i = 0; i < amount; i++) {
		Tab[i] = (my_class*)malloc(sizeof(my_class)); // I know the cast is "still" incorrect
	}
}

这应该为列表项分配内存。我故意忽略了这里的三维数组概念,因为代码本身没有多大意义。



我将以此结束,在C ++中,使用 new delete !有一个原因,它们是在C标准库中提供的 malloc 免费函数之上的语言中创建的。



c ++ - new / delete和malloc / free有什么区别? - 堆栈溢出 [ ^ ]

This should allocate the memory for the list items. I am ignoring the 3-dimensional array concept here, on purpose, because the code itself does not make much sense.

I will end this with this, in C++, use new and delete! There is a reason they are created in the language on top of malloc and free functions provided in C standard library.

c++ - What is the difference between new/delete and malloc/free? - Stack Overflow[^]


这篇关于在C中分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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