C 定义一个结构,其文件范围可由多个函数访问

C 定义一个结构,其文件范围可由多个函数访问,c,function,data-structures,struct,scope,C,Function,Data Structures,Struct,Scope,我有两个功能。 1.根据输入定义数据结构。 2.使用定义的结构 // Suggestion #1 struct myStruct { int a; int b; int c; } * myArray; void initialize( int size ) { myArray = malloc( size * sizeof * myArray ); } void operations( ) { myArray[1].a = 7; } // Sug

我有两个功能。 1.根据输入定义数据结构。 2.使用定义的结构

// Suggestion #1

struct myStruct {
    int a;
    int b;
    int c;
} * myArray;

void initialize( int size ) {
    myArray = malloc( size * sizeof * myArray );
}

void operations( ) {
    myArray[1].a = 7;
}


// Suggestion #2
// DO NOT USE THEM BOTH TOGETHER

struct myStruct {
    int a;
    int b;
    int c;
};

struct myStruct * initialize( int size ) {
    return malloc( size * sizeof( struct myStruct ) );
}

void operations( struct myStruct * myArray ) {
    myArray[1].a = 7;
}
如何在一个函数中定义结构,并在以后的另一个函数中使用它

 struct myStruct{
        int a;
        int b;
        int c;
     };

 void initialize(int size){
     struct myStruct myArray[size];
 }

 void operations(){
      myArray[1].a = 7;
 }
这些是在外部文件中定义的,输入和输出是设置的,不应更改。有没有一种方法可以让我的结构数组稍后由另一个函数访问

编辑:尝试将其分配给指针

struct myStruct{
        int a;
        int b;
        int c;
     };
 struct cache_entry *p;
 void initialize(int size){
     struct myStruct myArray[size];
     *p = &myArray;
 }

 void operations(){
      myArray[1].a = 7;
 }

好的,接下来是你的最后一次编辑,这里有一个建议你可以利用,希望:

或者声明一个全局指针,即为您的结构数组保存动态分配的内存位置的地址;或者最好使用局部变量,方法是使
initialize
函数返回动态分配内存的地址,同时使
operations
函数接收结构的指针

// Suggestion #1

struct myStruct {
    int a;
    int b;
    int c;
} * myArray;

void initialize( int size ) {
    myArray = malloc( size * sizeof * myArray );
}

void operations( ) {
    myArray[1].a = 7;
}


// Suggestion #2
// DO NOT USE THEM BOTH TOGETHER

struct myStruct {
    int a;
    int b;
    int c;
};

struct myStruct * initialize( int size ) {
    return malloc( size * sizeof( struct myStruct ) );
}

void operations( struct myStruct * myArray ) {
    myArray[1].a = 7;
}

好了,像这样的。我希望我没有犯错误。

你不能。在函数外部定义结构类型。我尝试使用在函数外部定义的指针。例如:struct myStruct*p;然后在initialize内部,我尝试将myArray分配给它,但它不起作用。@OliCharlesworth-这是不可取的。输入是在运行时定义的,保持初始化分离是最干净的,这没有意义。如果要在多个位置使用类型,则需要在多个位置都可以看到的位置定义该类型。那个地方不在功能范围内。@BrandonSmith不,你也不能这么做。。。作为一个局部变量,
myArray
在声明后到达该
}
时,它将消失。感谢您的最新编辑,但是…应该是myArray=malloc(size*sizeof(struct myStruct))?@BrandonSmith,因为
myArray
定义为
struct myStruct*myArray,以下为真:
sizeof(struct myStruct)==sizeof*myArray