简体   繁体   English

C语言在另一个函数中接收struct

[英]C language receive struct in another function

when I try to read the value of t[1].name inside equalname function, it won't work. 当我尝试在equalname函数中读取t[1].name的值时,它将无法工作。 How can I send that value over to another function? 如何将该值发送到另一个函数?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

struct test {
    char name[100];
    char num[100];
};

int equalname(struct test *t, char string[100]) {
    int i;
    t = malloc(sizeof(struct test)*100);
    printf("t[1].name == %s\n", t[1].name); //prints garbage(t[1].name != name)
    for (i = 0; i < 100; i++) //also, is this even right?
    {
        if (t[i].name == string) //should I use 2 for's and set t[i].name[j] == string[j]?
        {
            printf("t[i].name == name!");
            return i;
            break;
        }
    }
    printf("WRONG");
    return 0;
}

int main() {
    struct test *t;
    t = malloc(sizeof(struct test)*100);
    char name[100];
    printf("Name:\n");
    scanf("%s", name);
    strcpy(t[1].name, name);
    printf("t[1].name == %s\n", t[1].name); //this works (t[1].name == name)
    equalname(t[1].name, name);
}

The good news is you are on the right track -- the bad news is there are a couple of rails missing from your track... 好消息是您在正确的轨道上-坏消息是您的轨道上缺少一些障碍...

To begin, when you allocate memory with malloc , the block of memory is reserved, but all bytes within the block remain uninitialized . 首先,当您使用malloc分配内存时,将保留内存块,但该块中的所有字节均保持未初始化状态 Attempting to access anything within an uninitialized memory location is Undefined Behavior -- the operation of your code is no longer defined from that point forward -- it could appear to work or SegFault or anything in between. 尝试访问未初始化的内存位置中的任何内容都是未定义行为 -从那时起不再定义代码的操作-它似乎可以正常工作或出现SegFault或介于两者之间的任何内容。

You have two choices, (1) either loop through each struct and explicitly initialize the values, or (2) use calloc that will allocate and initialize all bytes to zero, eg 您有两种选择:(1)遍历每个结构并显式初始化值,或者(2)使用calloc将所有字节分配并初始化为零,例如

#define MAXN 100    /* if you need a constrant #define 1 (or more) */

struct test {
    char name[MAXN];
    char num[MAXN];
};
...    

int main() {

    int index;
    struct test *t;
    char name[MAXN] = "";
    t = calloc(MAXN, sizeof *t);    /* use calloc, or initialize values */

    if (t == NULL) {                /* validate every allocation */
        perror ("calloc-t");
        return 1;
    }

Do not allocate t again in equalname . 不要在equalname再次分配t While that does not overwrite your original address due to C using pass by value, and t being a copy of t from main -- it also does nothing for you accept create another uninitialized block of memory. 尽管由于C使用传递值,并且由于t是main的t的副本,因此不会由于C覆盖您的原始地址,但是对于您接受的任何操作,它也不会创建另一个未初始化的内存块。 Just pass t from main and use it, eg 只需从main传递t并使用它,例如

int equalname (struct test *t, char *string) 
{
    int i;

    printf("t[1].name == %s\n", t[1].name);

    for (i = 0; i < MAXN; i++)
    {   /* you must use strcmp to compare strings, not == */
        if (strcmp (t[i].name, string) == 0)
        {
            printf ("t[i].name == name!\n");
            return i;
            break;
        }
    }

    printf("WRONG");
    return -1;
}

Next, you cannot compare strings with == . 接下来,您不能将字符串与==进行比较。 You either have to loop over each character and compare -- or just use strcmp (that's what it was written to do), eg 您要么必须遍历每个字符并进行比较-要么仅使用strcmp (这就是编写的目的),例如

        if (strcmp (t[i].name, string) == 0)
        {
            printf ("t[i].name == name!\n");
            return i;
            break;  /* break does nothing here */
        }

Next, you must validate every allocation and every user input -- otherwise you are inviting Undefined Behavior . 接下来,您必须验证每个分配和每个用户输入-否则,您将邀请未定义行为 If you fail to validate allocations and fail to validate input -- you can have no confidence you are actually processing valid data in valid memory within your code. 如果您无法验证分配并且无法验证输入-您将无法确信实际上正在处理代码内有效内存中的有效数据。

Putting it altogether, you could do something like the following: 综上所述,您可以执行以下操作:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

#define MAXN 100    /* if you need a constrant #define 1 (or more) */

struct test {
    char name[MAXN];
    char num[MAXN];
};

int equalname (struct test *t, char *string) 
{
    int i;

    printf("t[1].name == %s\n", t[1].name);

    for (i = 0; i < MAXN; i++)
    {   /* you must use strcmp to compare strings, not == */
        if (strcmp (t[i].name, string) == 0)
        {
            printf ("t[i].name == name!\n");
            return i;
            break;
        }
    }

    printf("WRONG");
    return -1;       /* on error return a value that cannot be a valid index */
}

int main() {

    int index;
    struct test *t;
    char name[MAXN] = "";
    t = calloc(MAXN, sizeof *t);    /* use calloc, or initialize values */

    if (t == NULL) {                /* validate every allocation */
        perror ("calloc-t");
        return 1;
    }

    printf ("Name: ");
    if (scanf ("%s", name) != 1) {  /* validate ALL user input */
        fprintf (stderr, "error: invalid input - name.\n");
        return 1;
    }
    strcpy (t[1].name, name);

    printf ("t[1].name == %s\n", t[1].name);
    index = equalname (t, name);    /* save the return! */

    if (index == -1) {  /* validate the operation of your function */
        fprintf (stderr, "string '%s' not found.\n", name);
        return 1;
    }

    printf ("string found at index '%d'.\n", index);

    return 0;
}

Example Use/Output 使用/输出示例

$ ./bin/struct_find_str
Name: Alfred
t[1].name == Alfred
t[1].name == Alfred
t[i].name == name!
string found at index '1'.

Let me know if you have further questions. 如果您还有其他问题,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM