2009年6月28日 星期日

取得浮點數(float)的最大值

其他資料型態應該也可以這樣做...
因為不同平台的資料型態的位元數可能不太一樣,用這個方法比較保險

  1. include float.h
  2. use FLT_MAX

2009年6月27日 星期六

計算程式碼行數

wc -l *.c *.h | grep total

wc: 計算行數、字數及字元數
  • -l 計算行數(line)
  • -w 計算字數(word)
  • -c 計算字元數(character)

2009年6月25日 星期四

C陣列長度取得(用malloc的方法)

當使用動態記憶體配置時

無法使用sizeof的技巧來取得陣列長度

不過可以寫一個自己的malloc和free來計算並維護各個動態分配的長度!!


  1. 寫mymalloc在malloc時記錄下這塊記憶體的陣列元素個數
  2. 寫myfree在free時把記錄下來的對應刪掉

#include
#include
#include

typedef struct arr_sz_t{

void * pointer;
int length;

struct arr_sz_t *next;

}arr_sz;

static arr_sz *sz_mapping;

void* mymalloc(int length, int size);
void myfree(void *p);
void add_sz_entry(void* p, int length);
int arr_length(void* p);

//input 1.array length 2.unit size
void* mymalloc(int length, int size){


void* ret = malloc(length*size);

add_sz_entry(ret, length);

return ret;
}

//free with mapping table
void myfree(void *p){

free(p);

if(sz_mapping != NULL){
arr_sz * t;
t = sz_mapping;

if(t->pointer == p){
sz_mapping = t->next;
free(t);
return;
}

while(t->next != NULL){
arr_sz *next;
next = t->next;
if(next->pointer == p){
t->next = next->next;
free(next);
return;
}

t = t->next;
}
}

}

void add_sz_entry(void* p, int length){
arr_sz* t = (arr_sz *)malloc(sizeof(arr_sz));

t->next = NULL;
t->pointer = p;
t->length = length;

//no sz_mapping
if(sz_mapping == NULL){
sz_mapping = t;
}
//insert
else{
t->next = sz_mapping;
sz_mapping = t;
}
}



//if no mach in mapping table, size is 0
int arr_length(void* p){
//no mapping data
if(sz_mapping == NULL){
return 0;
}

arr_sz* t;
t = sz_mapping;

while(t != NULL){
if(t->pointer == p){
return t->length;
}
t = t->next;
}

return 0;
}


int main(void){
srand(time(0));

int *data[50];

int i;

for(i=0;i<50;i++){
data[i] = (int *)mymalloc(random()%50, sizeof(int));
printf("size of data[%d]: %d\n", i, arr_length(data[i]));
myfree(data[i]);
}

return 0;

}