I started learning C and I wrote a short program implementing structures. For now, it only has a structure and a short function that is supposed to fill one of the structures (several are stored in an array). Program gets all the values (currently only for one structure to help me see what's going on) and the problem starts in main, in
printf("%s", tablica[0].nazwa);
Because program stops responding (no errors or warnings before).
If I put:
printf("%d", tablica[0].x);
It will print the value I put as x, so I know there is some problem with string in printf (but I can't figure out why). It's probably easy, but I'm just a beginner.
#include <stdio.h>
#include <string.h>
struct struktura
{
char *nazwa;
double x, y, z;
};
int wczytaj(struct struktura tab[])
{
int i;
for ( i = 0; i<1; i++)
{
printf("Podaj nazwe: ");
scanf("%s", &tab[i].nazwa);
printf("Podaj x: ");
scanf("%i", &tab[i].x);
printf("Podaj y: ");
scanf("%i", &tab[i].y);
printf("Podaj z: ");
scanf("%i", &tab[i].z);
};
return 0;
}
int main(struct struktura* a)
{ int i;
struct struktura tablica[6];
int wyniki[6][6];
wczytaj(tablica);
printf("%s", tablica[0].nazwa);
}
Sorry for some names being in Polish, I can correct that, but I hope it doesn't blur the program).
nazwais achar *,&tab[i].nazwais achar **. Since you passscanfthe address you want it to store something in, you are asking it to store a string in the space of a pointer to a character. What if the string takes up more space than a pointer to a character takes? (Which it likely does.) Somewhere you have to allocate enough space to hold the string.malloc, but define it statically likechar nazwa[30]int main(struct struktura* a)that isn't the proper signature formain().