0

私は長い間 C を扱っていなかったので、C がどのように機能するかについて恥ずかしいほど忘れていました。プロトタイプ関数を定義するヘッダー「arrayUtils.h」と対応する「arrayUtils.c」を作成しようとしています。次に、2 番目の .c ファイルでこれらの関数の 1 つを呼び出そうとしています。

ヘッダーの内容:

#define _OUT_OF_RANGE_ = NAN

#ifndef INT_ALLOCATE_H
#define INT_ALLOCATE_H
int * allocIntArray(const int size);
#endif

#ifndef INT_ACCESS_H
#define INT_ACCESS_H
int accessIntArray(const int index, const int * array, const bool checked);
#endif

#ifndef INT_FREE_H
#define INT_FREE_H
int freeIntArray(int * array);
#endif

ヘッダーのソース:

/* Allocates an array of integers equal to length size
 * Args: int size: length of the array
 * Return: Allocated array
 */
int * allocIntArray(const int size){
    /*Assert that size of array is greater than zero*/
    if(size <= 0){
        return(-1);
    }
    else{
        return((int*)malloc(size*sizeof(int)));
    }
}
/* Returns the value of the array 
 * Args: int    index:   position in the array to access
 *       int  * array:   array to access
 *       bool   checked: if the access should be checked or not
 * Returns: integer at position index
 */
int accessIntArray(const int index, const int * array, const bool checked){
    /*unchecked access*/
    if(!checked){
        return(array[index]);
    }
    /*checked access*/
    else{
        if(index <= 0){
            return(_OUT_OF_RANGE_)
        }
        double size = (double)sizeof(array)/(double)sizeof(int)
        if(index => (int)size){
            return(_OUT_OF_RANGE_)
        }
        else{
            return(array[index])
        }
    }
}

/* Frees the allocated array 
 * Args: int * array: the array to free
 * Returns: 0 on successful completion
 */
int freeIntArray(int * array){
    free(array);
    return(0);
}

次に、2 番目のソース ファイルを呼び出します。

#include "arrayUtil.h"
int main(){
    int * array = allocIntArray(20);
    return(0);
}

私がコンパイルすると:

gcc utilTest.c

次のエラーが表示されます。

arrayUtils.h:10: エラー: 「チェック」前の構文エラー

最初は accessIntArray で「bool checked」を使用していましたが、同じエラーが発生しましたが、checked ではなく bool が使用されていました。

これが特定の質問ではない場合は申し訳ありませんが、私はここでかなり迷っています。

4

2 に答える 2

5

boolは C の標準型ではありません。C99 言語標準では、ブール データ型の新しい型と、 、 、および をそれぞれ 、、およびにマップするように定義_Boolするヘッダー ファイルが追加されました。<stdbool.h>booltruefalse_Bool(_Bool)1(_Bool)0

C99 コンパイラを使用してコンパイルする場合は、キーワード#include <stdbool.h>を使用する前に必ず確認してください。boolそうでない場合は、自分で定義してください。

typedef unsigned char bool;  // or 'int', whichever you prefer
#define true ((bool)1)
#define false ((bool)0)
于 2012-10-10T19:41:24.340 に答える
2

C には「bool」がありません。おそらく int を使用したいだけでしょう。または、ブール型を持つ C++。

于 2012-10-10T19:41:00.903 に答える