使用malloc的方式的区别
1和2之间有什么区别?
int *p; p = malloc(2 * sizeof(int));
int * p = malloc(2 * sizeof(int));
我第一次了解到它的方式是第一,但是我已经看到有人做了2号。 数字1和2是同一件事吗?我假设是,但是 我很困惑,因为我不明白为什么2号不是
int *p = malloc(2 * sizeof(int));
他
int p = malloc(2 * sizeof(int));
使用的方式。在代码的后期,他使用P来节省一些所需的值。
像这样。
p[0] = i;
p[1] = j;
What's the difference between 1 and 2?
int *p; p = malloc(2 * sizeof(int));
int *p = malloc(2 * sizeof(int));
The way I first learned it is number 1, but I've seen someone do it number 2.
Is number 1 and 2 the same thing? I'm assuming it is, but
I'm confused because I don't understand why number 2 is
int *p = malloc(2 * sizeof(int));
not
int p = malloc(2 * sizeof(int));
The way he used it was for array. Later in the code, he used p to save some desired values.
Like this.
p[0] = i;
p[1] = j;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(1)和(2)相同,用于用内存分配初始化指针。
我认为您对初始化指针的方法感到困惑,而不是如何使用
malloc()
。查看一些有关“初始化指针”的文章%20to%20 initialize%20A,地址%20of%20%20Variaible%20Number%20。 rel =“ nofollow noreferrer”>这个。这样,声明指针是不正确的,在这种情况下,
p
只是整数变量,而不是指向整数变量的指针。(1) and (2) are the same which are used to initialize pointer with memory allocation.
I think you're confused with the way to initialize pointer, not how to use
malloc()
. Take a look on some articles about "Initialize pointer" like this one.This way is not correct to declare a pointer, in this case,
p
is just an integer variable, not a pointer that points to an integer variable.1和2做同样的事情。编译器应产生完全相同的代码。他们都是声明类型
p
int *
的p ,然后初始化p
with with p 指针从malloc
返回。它是
int *p = ...
,因为int *
是类型。该变量为p
。它将变量p
声明为类型int *
,然后分配给p
。区别在于2在单个语句中做到这一点。这是优选的,因为它可以确保变量是初始化的,并且可以更轻松地看到该变量是初始化的。非初始化的变量包含垃圾,是常见的错误来源。即使是
0
或null
,也可以立即初始化每个变量。您经常会看到代码分别声明和初始化变量;有时,所有变量都在每个函数的顶部声明。这是一种旧样式,从C要求您在功能开始时声明所有变量时。这不再是问题。您现在可以根据需要声明变量。
1 and 2 do the same thing. The compiler should produce exactly the same code. They both declare a variable
p
of typeint *
and then initializep
with the pointer returned frommalloc
.It's
int *p = ...
becauseint *
is the type. The variable isp
. It is declaring the variablep
as the typeint *
and then assigning top
.The difference is that 2 does it in a single statement. This is preferable because it ensures the variable is initialized, and it makes it easier to see that the variable is initialized. Uninitialized variables contain garbage and are a common source of errors. It's usually a good idea to initialize every variable immediately, even if it's to
0
orNULL
.You will often see code which declares and initializes variables separately; sometimes all the variables are declared at the top of each function. This is an old style from way back when C required you to declare all your variables at the start of a function. This is no longer an issue. You can declare variables as needed now.