I really do not understand if and when do I need to declare a pointer to my data struct.
I have two programs and both works the same, but I cant figure out where should I need a pointer or not.
Here are the programs:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct data
{
char *ptr;
};
void printStruct( struct data pers );
int main (void)
{
struct data pers; // Here pers is not a POINTER
pers.ptr = malloc(sizeof (char) * 256);
strcpy(pers.ptr, "Hello World");
printStruct(pers);
free(pers.ptr);
}
void printStruct( struct data pers ){
printf("PTR = %s\n", pers.ptr);
}
When do I exactly need a pointer?
As you can see, here struct data pers; I declared a variable and in the next example I am using a pointer:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct data
{
char *ptr;
};
void printStruct( struct data *pers );
void printStruct( struct data *pers ){
printf("PTR = %s\n", pers->ptr);
}
int main (void)
{
struct data *pers; // Here pers is a POINTER
pers = malloc(sizeof(*pers));
pers->ptr = malloc(sizeof (char) * 256);
strcpy(pers->ptr, "Hello World");
printStruct(pers);
free(pers->ptr);
free(pers);
}