简体   繁体   English

将结构值传递给函数

[英]Passing the structure value to a function

#include<stdio.h>

struct classifier
{
    char src_address[15];
    char dst_address[15];
    int src_port;
    int  dst_port;
};

void display(struct classifier *ptr)
{
    printf("\n%s", ptr->src_address );
    printf("\n%s", ptr->dst_address );
    printf("\n%d", ptr->src_port);
    printf("\n%d", ptr->dst_port );
}

main()
{
    int i;
    struct classifier *ptr[4];
    for(i=0;i<2;i++)
    {
        scanf("%s",ptr[i]->src_address);
        scanf("%s",ptr[i]->dst_address);
        scanf("%d",&ptr[i]->src_port);
        scanf("%d",&ptr[i]->dst_port);
        display(ptr[i]);
    }
    return 0;
}

I want to display output in a function. 我想在函数中显示输出。 When I enter the data for the first time, I get proper display. 当我第一次输入数据时,我得到了正确的显示。 When I enter data for the second time, it displays segmentation fault. 当我第二次输入数据时,它会显示分段错误。 What is wrong in the code? 代码有什么问题? According to my knowledge, I have declared the pointers properly. 根据我的知识,我已经正确地宣布了指针。 Please help. 请帮忙。

You need an array of structures like 你需要一系列结构

struct classifier ptr[4]; struct classifier ptr [4];

You have just declared the pointers but they not pointing to anything valid. 你刚刚声明了指针,但它们没有指向任何有效的指针。 You need to allocate memory for every struct and store the memory location of the object in the array. 您需要为每个结构分配内存并将对象的内存位置存储在数组中。

EDIT: This is valid only if you really want to allocate memory dynamically. 编辑:仅当您真的想动态分配内存时才有效。 Else use the method suggested by @ckv 否则使用@ckv建议的方法

struct classifier *ptr[4];

In the above definition ptr is an array(of size 4) to pointers of type struct classifier. 在上面的定义中, ptr是一个类型为struct classifier的指针的数组(大小为4)。 You have not allocated memory for these pointers and the pointer variable ptr[0..3] are pointing to junk 您没有为这些指针分配内存,指针变量ptr[0..3]指向垃圾

Instead either you should be mallocing memory or using 相反,无论是你应该mallocing存储或使用

struct classifier ptr[4];

This will ensure ptr points to valid struct classifier variables allocated on stack 这将确保ptr指向在堆栈上分配的有效struct classifier变量

You haven't allocated the memory for struct classifier 您尚未为struct classifier分配内存

You either want this, 你想要这个,

struct classifier *ptr = (classifier*)malloc(4)

followed by, 其次是,

free(ptr);

or 要么

struct classifier ptr[4];

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

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