我试图返回一个指向结构的指针,但是我一直收到这个奇怪的错误bboard.c:35: error: Expecte expression before 'BBoard'是否有人知道是什么导致了这个错误。我是c语言的新手,所以我对这件事的道歉是个微不足道的问题。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "bboard.h"

struct BBoard {
int create[MAX_ROWS][MAX_COLS];
};


BBoard * bb_create(int nrows, int ncols){
int i,j;
srand(time(NULL));
struct BBoard Bboard;
for (i = 0; i < nrows; i++){
    for (j = 0; j < ncols; j++){
        int r = rand() % 4;
        //printf("%d",r);

        if( r == 0){
        Bboard.create[i][j] = 1;}
        if(r == 1){
        Bboard.create[i][j] = 2;}
        if(r == 2){
        Bboard.create[i][j] = 3;}
        if(r == 3){
        Bboard.create[i][j] = 4;}
        printf(" %d ",Bboard.create[i][j]);
            }
        printf("\n");
        }
struct BBoard *boardPtr = malloc(sizeof(struct BBoard));
if (boardPtr != NULL){
//printf("%d",boardPtr->create[1][1]);
return BBoard *boardPtr;
}
else{
printf("Error");
}
}

/**extern void bb_display(BBoard *b){
int i,j;
BBoard Bboard = b;
for (i = 0; i < 5; i++){
    for (j = 0; j < 5; j++){
        printf("%d",Bboard.create[i][j]);
        }
    }
}**/


int main(){
BBoard *bptr;
bptr = bb_create(5,5);
//printf("%d",bptr->create[0][1]);
}

最佳答案

在C语言中,您需要使用struct BBoard,直到您使用:

typedef struct BBoard BBoard;

在C++中,不需要创建TyPulf。
你能详细说明一下吗?我不明白。
你有:
struct BBoard
{
    int create[MAX_ROWS][MAX_COLS];
};


BBoard * bb_create(int nrows, int ncols)
{
    …

结构定义创建一个类型struct BBoard。它不创建类型BBoard;它只创建struct BBoard。所以,当您下次编写BBoard *bb_create时,没有类型BBoard,所以编译器会抱怨。
如果你写了其中一个序列-或者:
typedef struct BBoard
{
    int create[MAX_ROWS][MAX_COLS];
} BBoard;

或:
typedef struct BBoard BBoard;
struct BBoard
{
    int create[MAX_ROWS][MAX_COLS];
};

或:
struct BBoard
{
    int create[MAX_ROWS][MAX_COLS];
};
typedef struct BBoard BBoard;

然后定义类型struct BBoard和类型BBoard的别名,然后编译代码。
在C++中,简单定义一个structclass定义了一个类型,它可以在没有structclass前缀的情况下使用。
如果您的代码在函数定义开始之前编译,那么(a)您没有使用标准的C编译器,并且(b)您的代码在以下位置有问题:
return BBoard *boardPtr;

因为这是:
    struct BBoard *boardPtr = malloc(sizeof(struct BBoard));
    if (boardPtr != NULL){
        //printf("%d",boardPtr->create[1][1]);
        return BBoard *boardPtr;
    }
    else{
        printf("Error");
    }
}

实际上根本不需要强制转换返回类型,但如果您认为需要,则应使用正确的强制转换表示法(这两种方法之一,最好是第一种):
        return boardPtr;
        return (BBoard *)boardPtr;

else子句中的错误消息应更具信息性,应以新行结尾,应写入标准错误,并应后跟return 0;或等效错误。

关于c - 错误:结构之前的预期表达式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26749227/

10-12 15:01