[英]Structs with 2d arrays in C
我還不太擅長C語言,所以我有一些問題。
我有以下兩個結構:
typedef struct line_elems line;
typedef struct cache_handler *cache;
struct line_elems { // we don't care about valid/block bits in our simulator
int tag;
int freq; // for LRU principle
};
struct cache_handler {
int hit;
int miss;
int evict;
line **lines; // 2d array for sets
};
通過以下方式初始化緩存:
cache make_cache(int s, int E) {
int i;
cache new = malloc(sizeof(struct cache_handler));
new->hit = 0;
new->miss = 0;
new->evict = 0;
line **new_line = malloc((1 << s) * sizeof(*new_line));
for(i = 0; i < (1 << s); i++)
new_line[i] = malloc(E * sizeof(struct line_elems));
new->lines = new_line;
return new;
}
現在,我想創建一個系統來搜索2d數組中的一行:
int search_lines(line *lines, int E, int tag, int frequency) {
int i;
for(i = 0; i < E; i++) {
//continue here
}
}
我對應該輸入到search_lines函數中的確切內容有些困惑。 如果我輸入: search_lines(cache->lines[0], E=5, tag=5, frequency=5)
它會做我所期望的嗎? 也就是說,它會在我的二維數組中搜索一行嗎? 我覺得cache->lines[0]
與(line*)
。 cache->lines
和cache->lines[0]
什么區別? 這使我感到困惑,因為->
運算符是否隱式執行一級解引用?
謝謝。
->
運算符不是取消引用lines
,而是取消引用cache
。 這是必需的,因為cache
也是一個指針(由對malloc
的調用創建)。因此,必須在訪問其任何字段之前將其取消引用。
cache->lines
是line **
cache->lines[0]
是line *
"What is the difference between a cache->lines and a cache->lines[0]?"
cache->lines
是struct line_elems**
,它是您的2D數組。 實際上,它是指向2D數組的第一個元素的指針。 使用運算符->
因為cache
是cache_handler*
=您正在使用它訪問struct cache_handler
成員。
cache->lines[0]
是struct line_elems*
,它是1D數組,索引為0 =它也是2D數組第一個元素的指針。
請注意,釋放此內存的順序應與分配的順序相反:
line **new_line = malloc((1 << s) * sizeof(*new_line));
for(i = 0; i < (1 << s); i++)
new_line[i] = malloc(E * sizeof(struct line_elems));
您先釋放每個new_line[i]
,然后再釋放new_line
本身:
for(i = 0; i < (1 << s); i++)
free(new_line[i]);
free(new_line);
是的,對cache-> lines [0]的引用確實返回了指向您分配的“行”數組的指針,因此,是的,您的示例調用實際上是正確的方法。
請記住,cache-> lines是一個分配的指針數組(對malloc
的第二次調用)。 它僅分配足夠的空間用於2^s * the_size_of_a_pointer
下面的其余malloc分配足夠的空間用於E * size_of_a_line
。
因此,當您取消引用緩存指針(使用->
),然后引用行指針(通過使用[0]
)時,最終將得到一個指向E
行的內存指針。
然后在函數中,您可以使用lines[0]
到達第一行,並使用lines[E-1]
到達傳入的任何行指針數組的最后一行(基於[]
運算符到cache->lines
數據指針)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.