我正在创建一个维度为 [10][10] 的矩阵,它存储一个结构 Contentor,我无法更改矩阵内的值也无法存储它们。
我尝试使用 for 循环检查是否有任何数据,但看不到里面的内容。
当我将数据存储在矩阵内时,我尝试为每个矩阵创建一个线程来处理数据,但我真的不知道该怎么做......
我尝试过使用 malloc 和 calloc,我以基本形式创建了矩阵,但似乎没有任何效果...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
struct Contentor {
char nSerie[36];
char porto[4];
};
void* direcionaParaDestino(void* arg) {
struct Contentor *arg_struct = (struct Contentor*) arg;
char destino[4] = arg_struct->porto;
if(strcmp(destino, "ANR")) {
} else if (strcmp(destino, "BUS")) {
} else if (strcmp(destino, "DXB")) {
} else if (strcmp(destino, "GUA")) {
} else if (strcmp(destino, "HAM")) {
} else if (strcmp(destino, "HKG")) {
} else if (strcmp(destino, "LAX")) {
} else if (strcmp(destino, "RTM")) {
} else if (strcmp(destino, "SHA")) {
} else if (strcmp(destino, "SIN")) {
}
pthread_exit(0);
}
int main() {
struct Contentor parque[10][10] = malloc(100*sizeof(struct Contentor));
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
parque[i][j].nSerie = "";
parque[i][j].porto = "";
}
}
pthread_t tids[10][10];
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
if(strcmp(parque[i][j].nSerie,"")) {
printf("Lugar [%d][%d] encontra-se Livre\n", i, j);
//Criar Thread que espera ate 5 segundos
short randomNumber = rand() % 5
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&tids[i][j], &attr, direcionaParaDestino, 1 );
sleep(randomNumber);
} else {
printf("Lugar [%d][%d] encontra-se Ocupado\n", i, j);
}
}
}
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
pthread_join(tids[i][j],NULL);
}
}
}
我希望它成为该结构的矩阵,检查每个点中是否有任何数据,然后存储它并为存储的每个变量创建一个线程,该线程在处理信息之前最多等待 5 秒。
最佳答案
您不能从其他数组或指针初始化数组。而且你也不能分配给数组。
所以
char destino[4] = arg_struct->porto;
无效。
有两种方法可以为您解决这个问题:
依赖于这样一个事实:数组自然衰减为指向其第一个元素的指针。也就是说,如果需要一个指针,则
arg_struct->porto
等于&arg_struct->porto[0]
。这意味着你可以这样做char *destino = arg_struct->porto;
根本没有任何
destino
变量,并将arg_struct->porto
直接传递给您的strcmp
调用:if (strcmp(arg_struct->porto, "BUS") == 0) ...
另请注意 strcmp
如果两个字符串相等,则返回零。这就是上面与零进行相等比较的原因。
无法分配给数组也是为什么像这样的语句
parque[i][j].nSerie = "";
将会失败。
如果您希望数组像空字符串一样,您所需要做的就是将第一个元素设置为空终止符:
parque[i][j].nSerie[0] = '\0'; // Make string "empty"
如果要清除数组的所有字节,需要使用memset
功能:
memset(parque[i][j].nSerie, 0, sizeof parque[i][j].nSerie); // "Clear" array
关于c - 如何创建一个仅具有结构的矩阵,然后为矩阵中存储的每个数据创建一个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54266778/