在您的代码片段中,结构声明是错误的。我认为您的意思是结构的 typedef,而不是声明结构的对象。
例如
typedef struct Student
^^^^^^^
{
char *name;
int age;
Courses *list; //First course (node)
struct Student *friends[]; //Flexible array memeber stores other student pointers
^^^^^^^^^^^^^^
} Student;
malloc的这个调用也是错误的
Student *oneCopy = malloc(sizeof(one) + 20*sizeof(Student*));
应该有
Student *oneCopy = malloc(sizeof( *one ) + 20*sizeof(Student*));
^^^^^
这是一个演示程序,显示了如何编写函数
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef struct Student
{
char *name;
int age;
// Courses *list; //First course (node)
struct Student *friends[]; //Flexible array memeber stores other student pointers
} Student;
Student * shallowCopy( const Student *one, size_t friends )
{
Student *oneCopy = malloc( sizeof( Student ) + friends * sizeof( Student * ) );
*oneCopy = *one;
memcpy( oneCopy->friends, one->friends, friends * sizeof( Student * ) );
return oneCopy;
}
int main( void )
{
Student *one = malloc( sizeof( Student ) + sizeof( Student * ) );
one->friends[0] = malloc( sizeof( Student ) );
one->friends[0]->age = 20;
Student *oneCopy = shallowCopy( one, 1 );
printf( "Age = %d\n", oneCopy->friends[0]->age );
free( one->friends[0] );
free( one );
free( oneCopy );
}
它的输出是
Age = 20
考虑到结构还包含一个数据成员,该数据成员将存储灵活数组中的元素数量。:)