c - 全局结构体数组非常规问题
问题描述
我正在为我的大学做一个项目,我遇到了一个大而奇怪的问题。我已经创建了我的结构并试图从中创建一个全局数组,但结果很奇怪。该数组有 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;
}
这就是发生的事情:
- 第一个值总是 0
- 如果我增加 K 数组兑现不会触发分段错误
- 当我使用简单的 int array[X] 时,这种方法也会给我带来问题
这是怎么回事?我没有考虑什么?谢谢你的帮助^^
解决方案
它在全局声明程序崩溃中不起作用,在另一种情况下,如果首先在函数内部初始化它,如果 k = 0 并且唯一的索引为 4,则如果数组类型为 int,则可以存储值,具体取决于数组的类型和该类型的大小.
如果你想真正应用它,那么通过创建单独的链表来实现
推荐阅读
- discord.js - 如何使用 discord.js 记录自定义状态更新?
- visual-studio - 链接器错误:无法打开输入文件“d3dx9.lib”
- mysql - Docker MySQL 容器未正确绑定到本地端口
- python - 允许输入五个学生的分数但如何添加所有学生的分数的代码
- url-rewriting - xarray 追加或重写现有的 nc 文件
- javascript - 使用 cookie 存储客户端的次要细节是否比本地存储更好?
- javascript - 为什么是“|” 不适用于组合薮正正则表达式?
- google-drive-api - 对 Google Drive 嵌入式文件夹中的文件进行排序
- python - 单击其中一个按钮后如何禁用 3 个按钮?
- python - Jupyer 实验室给出错误 500:内部服务器错误