Passing the value of a function structure

#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 the output in a function. When I enter data for the first time, I get a proper display. When I enter the data a second time, it displays a segmentation error. What is wrong with the code? According to my information, I correctly formulated pointers. Please, help.

+3
source share
4 answers

You need an array of structures, for example

struct classifier ptr [4];

+4
source

You have just indicated pointers, but not pointed to anything valid. You need to allocate memory for each structure and save the object's memory cell in an array.

EDIT: This is only true if you really want to dynamically allocate memory. Else use the method suggested by @ckv

+4
source
struct classifier *ptr[4];

ptr ( 4) struct classifier. , ptr[0..3]

mallocing

struct classifier ptr[4];

This ensures that it ptrpoints to valid variables struct classifierallocated on the stack.

+3
source

You have not allocated memory for struct classifier

You either want it

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

then

free(ptr);

or

struct classifier ptr[4];
+3
source

Source: https://habr.com/ru/post/1785899/


All Articles