[英]How to declare an 3D array with different Datatypes and different sizes in C?
我需要聲明一個數組(在c中),其中包含兩個2D數組和一個具有不同大小和不同類型的1D數組。
不幸的是我的谷歌搜索並沒有真正的幫助...
int ram [128][64];
int chk_ram [128][64];
char arr_block[8];
是否可以將這些陣列打包成一個大陣列?
@unwind:這是我的函數,它原本是Python函數,但是因為它變慢了,所以我現在嘗試用C處理這些數組,因為我希望它快得多。 該函數應該像黑匣子一樣工作,我將3個數組放入其中,然后出現3個數組,這些數組將返回到Python。
這是C函數(我認為其中存在一些錯誤):
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int test(int **ram,int n_ram,int **chk_ram, int n_chk_ram,int **arr_block,int n_arr_block){
int i,j,k;
int yDog,p,x,d,y,z;
int *args_arr = (int*)malloc(size*sizeOf(int));
int *dog = (int*)malloc(size*sizeOf(int));
for (yDog=0;yDog<=8;yDog++){
p=yDog*8;
line='' ?? /* ?? */
for (x=0;x<=128;x++){
d=0;
if (chk_ram[(int)(x/16),yDog] == 1){
if (x%16 == 0){
arr_block[(int)(x/16),yDog] = ''; /* ?? */
}
for (y=0;y<=8;y++){
z = pow(2,y)
d += ram[x,p+y]*z;
}
arr_block[(int)(x/16),yDog] += chr(d); /* ?? */
if ((x+1)%16 == 0 && x){
chk_ram[(int)(x/16),yDog] = 0;
line += arr_block[(int)(x/16),yDog]; /* ?? */
}
}
else{
if ((x+1)%16 == 0 && x){
chk_ram[(int)(x/16),yDog] = 0;
line += arr_block[(int)(x/16),yDog];
x += 1;
}
else{
x+=15;
}
}
}
}
dog[yDog] = line; /* ?? */
args_arr = {ram, chk_ram, arr_block)
return args_arr;
}
如果有人知道我會使用Ctypes :)
為什么可以使用結構時使用數組?
struct foobar {
int ram [128][64];
int chk_ram [128][64];
char arr_block[8];
}
或者,使用typedef:
typedef struct {
int ram [128][64];
int chk_ram [128][64];
char arr_block[8];
} Foobar;
以我對您問題的理解,您正在嘗試混合使用各種類型和長度容易出錯的數組(至少在C語言中如此)。
如果您需要從函數返回該結構,則可以執行以下操作:
struct foobar myFunction(int c) { /* or Foobar */
struct foobar val;
/* stuff with val */
return val;
}
要么:
void myFunction(struct foobar *val, int c) { /* or Foobar */
val->ram[0][0] = c;
}
int main(void) {
struct foobar val;
myFunction(&val, c);
}
我肯定會使用指針(帶有struct foobar*
第二個函數),因為否則您將復制整個結構,並且它會比指針版本慢。
而且,如果您的函數需要初始化您的結構,並且您要對其進行更多工作,那么最好使用malloc
/ free
來避免不需要的副本。
是否可以將這些陣列打包成一個大陣列?
不,您不能,因為數組的所有元素都具有相同的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.