今天寫了一個C小程序,可是怎麼編譯都有錯誤,不論是在GCC中還是VC還是eclipse,都有莫民奇妙的錯誤,仔細看後才發現,原來我使用了bool值,而在C語言中根本就沒有這個值,所以會出錯,解決辦法是加上有關bool的宏定義即可:
#include <stdio.h>
#include <stdlib.h>
#define BOOL int
#define TRUE 1
#define FALSE 0
struct array
{
int count;
int size;
char *pBase;
};
void init_arr (struct array *pArr,int number);
void show_arr (const struct array *pArr);
BOOL is_empty (const struct array *pArr);
int main (void)
{
struct array arr;
init_arr (&arr,10);
show_arr (&arr);
return 0;
}
void init_arr (struct array *pArr,int number)
{
pArr->pBase = (char *)malloc(sizeof(char)*number);
if (NULL == pArr->pBase)
{
printf ("Memory allocation failed!\a\n");
exit(EXIT_FAILURE);
}
else
{
pArr->size = number;
pArr->count = 0;
}
return;
}
void show_arr (const struct array *pArr)
{
int i;
if ( is_empty(pArr) )
printf ("Array is empty!\a\n");
else
{
for (i=0;i<(pArr->count);i++)
printf ("%c ",pArr->pBase[i]);
printf ("\n");
}
return;
}
BOOL is_empty (const struct array *pArr)
{
if (pArr->count == 0)
return TRUE;
else
return FALSE;
}
而此前的代碼在C++中運行完好,這是因為C++中定義了bool值,故而可以使用:
#include <stdio.h>
#include <stdlib.h>
struct array
{
int count;
int size;
char *pBase;
};
void init_arr (struct array *pArr,int number);
void show_arr (const struct array *pArr);
bool is_empty (const struct array *pArr);
int main (void)
{
struct array arr;
init_arr (&arr,10);
show_arr (&arr);
return 0;
}
void init_arr (struct array *pArr,int number)
{
pArr->pBase = (char *)malloc(sizeof(char)*number);
if (NULL == pArr->pBase)
{
printf ("Memory allocation failed!\a\n");
exit(EXIT_FAILURE);
}
else
{
pArr->size = number;
pArr->count = 0;
}
return;
}
void show_arr (const struct array *pArr)
{
int i;
if ( is_empty(pArr) )
printf ("Array is empty!\a\n");
else
{
for (i=0;i<(pArr->count);i++)
printf ("%c ",pArr->pBase[i]);
printf ("\n");
}
return;
}
bool is_empty (const struct array *pArr)
{
if (pArr->count == 0)
return true;
else
return false;
}