将int值赋给指针
Assign int value to a pointer
我需要给指针分配一个int值,我该怎么做?
下面是我想要的一个小例子。
struct {
int a;
} name;
int temp = 3;
struct name *obj = NULL;
现在,我需要将这个值"3"赋值给结构的"a"。
使用
struct {
int a;
}name;
您已经定义了一个结构变量,它为结构分配内存(例如,当它是函数内部的局部变量时,在堆栈上)。然后,使用int temp = 3;
,将其分配给类似的结构成员就足够了
name.a = temp;
如果只想声明类型的结构,则使用
struct name {
int a;
};
然后,您可以基于这种类型定义任意数量的结构变量,如
struct name theName;
并对CCD_ 2成员执行与上述相同的分配:
theName.a = temp;
或者,您可以定义一个指向结构的指针,然后必须自己分配内存:
struct name *namePtr;
namePtr = malloc(sizeof(struct name));
namePtr->a = temp;
还要注意的是,您已经用C
和C++
标记了您的问题,尤其是用structs,您应该决定使用哪种语言——请参阅C和C++中structs之间的差异。
声明指向结构的指针不会为其保留内存,因此首先必须这样做。例如:
obj = malloc(sizeof(*obj));
现在您可以分配值:
obj->a = temp;
请注意,目前的程序并没有定义"结构名称",而是定义了一个名为"名称"的变量,该变量包含一个结构。这可能不是你想要的。
代码的基本问题是name
不是结构的名称,而是您已经定义了名称的对象或结构的变量。
如果你不想给结构命名,即使这样,它仍然需要分配内存。
struct
{
int a;
}name, *obj;
int temp = 3;
int main()
{
obj=&name; // 'obj' is pointing to memory area of 'name' : Keep this in mind throughout the code
obj->a=temp;
printf("%d %u %d",temp,&temp,obj->a);
return 0;
}
最好的选择是将一个名称放入结构中,然后在分配内存后使用其指针
typedef struct
{
int a;
}name;
int temp = 3;
name *obj = NULL;
int main()
{
obj = (name *)malloc(sizeof(name));
obj->a=temp;
printf("%d %u %d",temp,&temp,obj->a);
return 0;
}
EDIT(感谢Andreas):
正确地说,你的结构应该这样声明:
struct name {
int a;
};
void foo() {
struct name n; // allocate space for 'struct name' and call it n
struct name *obj; // a pointer to a 'struct name'
int temp = 3;
obj = &n; // make obj point to n
n.a = temp; // direct assignment to a
obj->a = temp; // assignment to a via pointer dereference
// a is now 3 in any case
}
这是代码的另一个带注释的版本。在Eclipse/Microsoft C编译器上运行了这个,这不是C++代码。
#include <stdio.h>
main()
{
// define a structure as a data type
typedef struct
{
int *a;
} name;
// allocate storage for an integer and set it to 3
int temp = 3;
// allocate storage for the name structure
name obj;
// set the value of a in name to point to an integer
obj.a = &temp;
// dereference the integer pointer in the name structure
printf("%dn", *obj.a);
}
obj->a = temp;
试试看!
相关文章:
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 指针问题:从不兼容的类型"int"分配给"int *"
- 运行时错误:引用绑定到类型为"int"的空指针
- C++:将值 int(例如:0x00AAFAD8)转换为指针(指针本身也是 0x00AAFAD8 值)
- 如何将 int 指针转换为浮点指针
- 使用 int 指针的浮点数的位表示形式
- C++:使用没有位移位的指针将无符号字符转换为无符号 int
- 从类指针到 int 的转换无效
- f 是指向函数的指针,该函数采用 int,并返回指向不带任何内容并返回双精度的函数的指针
- 如何使用静态多态性在 int 和指针类型之间进行转换?
- 为什么当我尝试将char输入到int时,文件指针会卡住
- 类型别名允许分配任意指针,尽管 int* 是必需的
- 为什么 fdump-class-hierarchy 为虚函数提供了两个指针 int vtable
- 双指针 (int**) 和双括号,用于从 2D 数组中获取值
- (C++)通过指针递增,或者:为什么这不起作用?指针->int = 指针->int+1;
- (c++)将int转换为char指针(int是int形式的字符)
- 如何使用指针到指针 (int **) 分配一维数组
- 删除地图中的指针<int,A*>
- 如何将字符串内存地址(如 "7fefe05a8")存储在 C++ 中的指针/int 变量中,以便我可以对其进行位屏蔽?
- 指向包含向量问题的实例类的指针<int>