0

嗨我有这个结构

typedef struct STUDENT
{
    char studName[20];
    int timeEnter;
    int timeUpdate;
}STUDENT;

以及指向结构数组的本地指针

STUDENT *studArr[100];

我试图通过读取文件的第一行来为结构分配内存,然后使用它为结构分配内存。

fscanf(fp, "%s", &first);
**studArr = (STUDENT**) malloc(sizeof(STUDENT*)*first);

我收到一条错误消息,指出没有运算符“=”与分配行上的这些操作数匹配

为什么我得到错误,我在这里做错了什么?

预先感谢

4

5 回答 5

3

I think you're confusing things, it looks like you're declaring an array of pointers, when all you need is a single pointer. Note that as long as you're indexing properly, a pointer to "one" struct is the same as a pointer to a hundred.

You should probably have:

STUDENT *studArr;

then, once you know how many you need (I'm assuming first is the number of students to allocate room for):

studArr = malloc(first * sizeof *studArr);

Also note that no casting is needed.

于 2013-04-25T07:05:15.407 回答
1

如果你想分配一个包含 100 个学生的数组,你有两个选择:

struct STUDENT
{
    char studName[20];
    int timeEnter;
    int timeUpdate;
};


struct STUDENT studArr1[100];

... OR ...

struct STUDENT *studArr2 = (struct STUDENT *)malloc (sizeof (struct STUDENT) * 100);

如果你只想要一个指针,你可以说:

  struct STUDENT *p = studArr1;

PS:

我故意留下了“typedef”的东西,以免混淆基本问题(结构与结构数组与指向结构数组的指针)。

于 2013-04-25T07:03:23.220 回答
0

You have defined an array of pointers to struct, not a pointer to an array of struct. The memory for the array is already allocated, as a global array.

The type of **studArr is STUDENT, and hence is not compatible with the expression to the right of the assignment operator, which is casted to (STUDENT**).

You probably meant:

STUDENT **studArr;

[...]

fscanf(fp, "%s", &first);
studArr = (STUDENT**) malloc(sizeof(STUDENT*)*first);
于 2013-04-25T07:04:48.090 回答
0

As you are using STUDENT *studArr[100]; then it means you have allocated the memory for 100 pointers for STUDENT structure type.

so for allocating the memory you should try.

studArr =malloc(sizeof(struct STUDENT)*first);

then you can access all the allocated members as studArr[i] ....so on.

于 2013-04-25T07:05:56.963 回答
0

You're not exactly clear on what your overall goal is.

First of all, you want to use %d if you want to read in an integer:

int count;
if (fscanf(fp, "%d", &count) != 1) { // error... }

Next, don't use STUDENT as both the struct name and the typdef. Just leave the struct name out:

typedef struct
{
    char studName[20];
    int timeEnter;
    int timeUpdate;
} student_t;

Now, you're going to want just a pointer to an array of student_ts:

student_t* student_array = NULL;

Finally, allocate that array:

student_array = malloc(count * sizeof(student_t));

Now you can use it, like:

strncpy(student_array[0].studName, "Bobby", 20);

Or get a pointer to an individual student:

student_t* bob = &student_array[1];
bob->timeEnter = 42;
于 2013-04-25T07:06:16.230 回答