0
#include <stdio.h>
#include <stdlib.h>
#define VEL 2
typedef struct
{
    char ime[15];
    char prezime[15];
    int dob;
    int staz;
} employee;
void upis(employee *);
void ispis(employee *);
int main(int argc, char **argv)
{
    employee radnik[VEL];

    upis(&radnik[VEL]);
    ispis(&radnik[VEL]);
    return 0;
}

void upis(employee * r)
{
    int i;

    printf("Upis podataka:\n==============\n");
    for (i = 0; i < VEL; i++)
    {
        printf("Upisite ime i prezime %d. radnika:\n", i + 1);
        scanf(" %15[^\n]", (r + i * sizeof(employee))->ime);
        scanf(" %15[^\n]", (r + i * sizeof(employee))->prezime);
        printf("Upisite dob i staz %d. radnika:\n", i + 1);
        scanf("%d", &(r + i * sizeof(employee))->dob);
        scanf("%d", &(r + i * sizeof(employee))->staz);
    }
}

void ispis(employee * r)
{
    int i;

    for (i = 0; i < VEL; i++)
    {
        printf("Ime:%s\nPrezime:%s\n", (r + i * sizeof(employee))->ime,
               (r + i * sizeof(employee))->prezime);
        printf("Dob:%d\nStaz:%d\n\n", (r + i * sizeof(employee))->dob,
               (r + i * sizeof(employee))->staz);
    }
}

The code actually works but in the end always returns segmentation fault. I'm guessing I did something wrong with pointers and addressing struct elements. Please help and thanks in advance!!

EDIT: Thanks everyone each answer was helpful!

krsnik93
  • 186
  • 1
  • 11

2 Answers2

4

Error is expressions like:

(r + i*sizeof(employee))->ime;

Correct it as:

(r + i)->ime;

Read Pointer to structure To learn how to use pointer to struct.

Note pointer arithmetic is different then integer arithmetic. When you add 1 to a pointer resulting address point to next location (you do not need to bother to calculate value). Accordingly in your code if r point to nth employee in an array of employee then r + 1 points to (n + 1)th employee.
To understand read 10.2 Pointers and Arrays; Pointer Arithmetic and Pointer Arithmetic.

Edit:

As @Jens Gustedt Notice correct your main code also as follows:

upis(radnik);
ispis(radnik);

If you wants to pass array to function (or first element's address).

Additionally avoid scanf to read line instead use fgets() read Reading a line using scanf() not good?.

Community
  • 1
  • 1
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
  • Along with this, it would be good to explain for the OP that, in C, when you add an integer to a pointer, the pointer is incremented by an amount equal to that integer times size of the type pointed to by the pointer. – lurker Oct 08 '13 at 11:25
2

This code is fundamentally flawed:

employee radnik[VEL];

upis(&radnik[VEL]);
ispis(&radnik[VEL]);

Arrays in C are indexed from 0 on to VEL-1 in your case. You are taking the address of of an element beyond the array and use it afterwards. This has no defined behavior, so anything can happen.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177