-4

我需要为指针分配一个 int 值,我该怎么做?

下面是我想要的一个小例子。

struct {
  int a;
} name;
int temp = 3;
struct name *obj = NULL;

现在,我需要将此值“3”分配给结构的“a”。

4

6 回答 6

4

struct {
   int a;
}name;

您已经定义了一个为结构分配内存的结构变量(例如,当它是函数内部的局部变量时,在堆栈上)。然后,使用int temp = 3;,分配给结构成员就足够了

name.a = temp;

如果你只想声明一个结构类型,那么使用

struct name {
   int a;
};

然后你可以根据这个类型定义任意数量的结构变量,比如

struct name theName;

并对theName成员进行与上述相同的分配:

theName.a = temp;

或者,您可以定义一个指向结构的指针,然后必须自己分配内存:

struct name *namePtr;
namePtr = malloc(sizeof(struct name));
namePtr->a = temp;

另请注意,您已经使用Cand标记了您的问题C++- 特别是对于结构,您应该决定采用哪种语言 - 请参阅C 和 C++ 中的结构之间的差异

于 2013-08-08T05:52:54.350 回答
2

声明一个指向结构的指针不会为它保留内存,所以首先你必须这样做。例如:

obj = malloc(sizeof(*obj));

现在您可以分配值:

obj->a = temp;

请注意,目前的程序没有定义“结构名称”,它定义了一个名为“名称”的变量,其中包含一个结构。这可能不是您想要的。

于 2013-08-08T05:39:05.237 回答
1

代码的基本问题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;
}
于 2013-08-08T06:06:08.530 回答
0

这是您的代码的另一个带注释的版本。在 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("%d\n", *obj.a);

}
于 2013-08-08T06:16:45.847 回答
0

编辑(感谢安德烈亚斯):

正确地,你的结构应该这样声明:

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
}
于 2013-08-08T05:38:37.123 回答
-1
obj->a = temp;

试一试!

于 2013-08-08T07:40:58.720 回答