我想知道如果我有这样的东西,结构会被分配到内存中的什么地方。
typedef struct {
int c;
} A;
A * a = (A)* malloc(sizeof(A));
a -> c = 2;
C将被分配到堆区域,对吗?此外,如果我用以下命令释放内存
free(a);
C占用的内存区域发生了什么变化?
根据我对C的理解,在尝试初始化时,似乎应该使用malloc( size ),例如,一个数组的大小直到运行时才知道。
但是,我想知道为什么函数malloc()返回指向变量位置的指针,以及为什么需要这样做。
基本上,为什么C不把它全部隐藏起来,这样每当你做这样的事情:
// 'n' gets stdin'ed from the user
...
int someArray[n];
for(int i = 0; i < n; i++)
someArray[i] = 5;
您可以不需要调用malloc()或其他函数就可以这
这实际上是一个普遍的问题,但现在我正在使用Go和C#。假设我们希望在Go中从用户的输入中赋值一个变量:
func main() {
var input float64
fmt.Scan(&input)
}
很明显,为什么我们需要一个内存位置来放置我们的新值。但是,为什么在像Java或C#这样的语言中,我们没有遵循相同的逻辑:
var input = Convert.ToInt32(Console.ReadLine());
// and not &input ...
我编写了一个基类类和一个派生的类,其中包含了相应的数据成员,如下面的代码所示。现在,在main函数中,我创建了新的基类对象,这些对象由派生的类指针指向,并使用了static_cast。
#include <iostream>
#include <vector>
class Base {
public:
int b;
Base() : b(2){};
int get_b() const;
};
class Derived : public Base {
public:
int d;
Derived() : d(4){};
int get_d()
我对C++中的垃圾收集器很好奇。我可以理解他们可以通过使用他们的分配方法来控制内存分配。就像Boehm
#include "gc.h"
#include <assert.h>
#include <stdio.h>
int main()
{
int i;
GC_INIT(); /* Optional on Linux/X86; see below. */
for (i = 0; i < 10000000; ++i)
{
int **p = (int **) GC_MALLOC(sizeof(int *));
考虑一下c代码:
void mycode() {
MyType* p = malloc(sizeof(MyType));
/* set the values for p and do some stuff with it */
cleanup(p);
}
void cleanup(MyType* pointer) {
free(pointer);
pointer = NULL;
}
我认为在调用cleanup(p);之后,p的内容现在应该是空的,这是错误的吗?cleanup(MyType* pointer)会正确释放内存分配吗?
我正在对我的大学作业进行编码,并且发现调
我真的对多态指针感到困惑。我有两个从接口派生出来的类,如下所示。
#include <iostream>
using namespace std;
class Base {
public:
virtual ~Base() { }
virtual void addTest() = 0;
};
class B: public Base {
public:
B(){}
~B(){}
void addTest(){
cout << "Add test B\n";
}
};
class