首页 > 解决方案 > 全局结构体数组非常规问题

问题描述

我正在为我的大学做一个项目,我遇到了一个大而奇怪的问题。我已经创建了我的结构并试图从中创建一个全局数组,但结果很奇怪。该数组有 6 个单元格,但是当我尝试在主中打印结构的字段时,似乎有比 6 个更多的单元格。这些是结构和全局数组:

#include "config.h" //K, P and T are defined in this header 
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <time.h>

typedef struct infocash{
 int fixed_time;
 int service_time;
 int cash_products;
 int full;
 QueuePtr customers;
 pthread_cond_t cashqueue;
}InfoCash;

typedef struct infoshop{
 int time;
 int customer_products;
}InfoShop;

typedef struct queue{
 InfoShop cust_info;
 struct queue* next;
}Queue;
typedef Queue* QueuePtr;

InfoCash cashes[K];

InfoShop init_shop_info();
void init_cash_info(int i);

void custfun(){
  InfoShop infoshop = init_shop_info();
}

void cashfun(void* arg){
  int* i = arg;
  init_cash_info(*i);
}

这是主要的:

int main(){
  srand(time(NULL));
  pthread_t tid_cust[C];
  pthread_t tid_cash[K];
  for(int i = 0; i < C; i++) pthread_create(&tid_cust[i], NULL, (void*)custfun, NULL);
  for(int i = 0; i < K; i++) pthread_create(&tid_cash[i], NULL, (void*)cashfun, &i);
  for(int i = 0; i < C; i++) pthread_join(tid_cust[i], NULL);
  for(int i = 0; i < K; i++) pthread_join(tid_cash[i], NULL);
  for(int i = 0; i < K; i++) printf("%d\n", cashes[i].fixed_time);
}

InfoShop init_shop_info(){
  InfoShop info;
  unsigned int seed = rand();
  info.time = 10 + rand_r(&seed)%T-10+1;
  info.customer_products = rand_r(&seed)%P+1;
  return info;
}

void init_cash_info(int i){
  unsigned int seed = rand();
  cashes[i].fixed_time = 20 + rand_r(&seed)%80-20+1;
  cashes[i].service_time = 0;
  cashes[i].cash_products = 0;
  cashes[i].customers = NULL;
  cashes[i].full = 0;
  pthread_cond_init(&cashes[i].cashqueue, NULL);
  return;
}

这就是发生的事情:

  1. 第一个值总是 0
  2. 如果我增加 K 数组兑现不会触发分段错误
  3. 当我使用简单的 int array[X] 时,这种方法也会给我带来问题

这是怎么回事?我没有考虑什么?谢谢你的帮助^^

标签: c

解决方案


它在全局声明程序崩溃中不起作用,在另一种情况下,如果首先在函数内部初始化它,如果 k = 0 并且唯一的索引为 4,则如果数组类型为 int,则可以存储值,具体取决于数组的类型和该类型的大小.

如果你想真正应用它,那么通过创建单独的链表来实现


推荐阅读