将int值赋给指针

Assign int value to a pointer

本文关键字:指针 int      更新时间:2023-10-16

我需要给指针分配一个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;

还要注意的是,您已经用CC++标记了您的问题,尤其是用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;

试试看!