【问题标题】:Passing one element of a struct into a function in C [closed]将结构的一个元素传递给C中的函数[关闭]
【发布时间】:2019-06-20 09:45:50
【问题描述】:

我知道以前有人问过几个与我类似的问题,我也看过很多,但我似乎找不到一个能准确回答我的问题的问题。下面是我的代码的一个最小示例。它不太有效,我为此道歉。我真的不熟悉堆栈溢出和一般的编码。我正在尝试执行以下操作:

  1. 创建结构
  2. 创建结构的向量实例
  3. 将该向量结构的一个元素传递给函数。

但是,当我这样做时,它不会编译。它给出了以下错误:

make: *** [~~~~] Error 1

symbol(s) not found for architecture x86_64

“~~~~”是我的程序的名称。我觉得我的问题很简单,例如必须取消引用指针或其他东西,但无论我尝试什么,它都不起作用。任何帮助,将不胜感激。

typedef struct precinct {
    int geoID; 
    long int neighbors[21]; 
    double nhblength[21]; 
    double perim; 
    double area; 
    int county; 
    int startdist; 
    int dist; 
    int pop; 
    int moe; 
    int nhbindex[21]; 
} Prec;

//prototypes
int checkAdjacency(Prec P);

int main(void) 
{
    Prec *SCPrec = malloc(2233 * sizeof(Prec));

    /* In this space, I load in data for each precinct. For the sake of this MWE, I'll just show some of the data loaded for the first precinct */

    SCPrec[0].geoID = 40351;
    SCPrec[0].dist = 3;
    SCPrec[0].pop = 781;

    int value;
    value = checkAdjacency(SCPrec[0]);
    printf("%d\n",value);
    return 0;
}

int checkAdjancency(Prec P)
{
    if(P.dist==5)
    {
        return 1;
    }
    else return 0;
}

【问题讨论】:

  • 围绕“symbol(s) not found for architecture x86_64”的消息是否也说“undefined symbols for architecture x86_64:”和““_checkAdjacency”,引用自:”?
  • 我没有看到任何与我的错误相关的消息。
  • checkAdjacencyint checkAdjancency(Prec P) - 仔细查看它们,你会发现一个错字。
  • 这很奇怪。通常链接器会列出未定义的符号。你应该试着弄清楚为什么你没有看到所有的输出。同时,请注意您的main 例程调用checkAdjacency,但您的代码定义了checkAdjancency。这些是不同的。
  • 旁注:指针传递给struct通常效率更高。正如你所拥有的,你的struct 的整个 contents 必须被推入堆栈(即sizeof(Prec) 字节),而不仅仅是指针。考虑[在编写过多代码之前]:在函数体中使用P->distint checkAdjacency(Prec P) 更改为int checkAdjancency(Prec *P)

标签: c function struct


【解决方案1】:

你拼错了checkAdjacency

出于这个和其他原因,我宁愿避免前向声明,除非它们是必要的。

int checkAdjancency(Prec P)
{
    ...
}

int main(void) 
{
    ...
    value = checkAdjacency(SCPrec[0]);
    ...
}

这会给出更清晰的错误消息。

test.c:38:13: warning: implicit declaration of function 'checkAdjacency' is invalid in C99
      [-Wimplicit-function-declaration]
    value = checkAdjacency(SCPrec[0]);
            ^
1 warning generated.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 2015-01-03
    • 2020-06-29
    相关资源
    最近更新 更多