you can allocate the the pointer inside the struct as the other primary variable (int, float,etc).
For example you have print_struct function:
void print_struct(struct Payload * pl) {
printf("filename: %s\n", pl->filename);
printf("content: %s\n", pl->content);
}
Before this function, you have to allocate for content and filename.
struct Payload pl1;
struct Payload *pl2 = malloc(sizeof(struct Payload)); // use pointer.
if(!pl2) {
// handle the error
}
pl1.content = malloc (sizeof(char)*30); // max length of content is 29 in this case.
if(!pl1.content) {
// handle the error
}
pl1.filename = malloc (sizeof(char)*30); // max length of filename is 29 in this case.
if(!pl1.filename) {
// handle the error
}
pl2->content = malloc (sizeof(char)*30); // max length of content is 29 in this case.
if(!pl2->content) {
// handle the error
}
pl2->filename = malloc (sizeof(char)*30); // max length of filename is 29 in this case.
if(!pl2->filename) {
// handle the error
}
Then when you call the print_struct function:
print_struct(&pl1) // pass by reference
print_struct(pl2) // pass by pointer
Do not forget to free memory to avoid memory-leaks.
free(pl1.content);
free(pl1.filename);
free(pl2->content);
free(pl2->filename);
free(pl2);
Short program for testing:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Payload
{
int id;
int nameLength;
char *filename;
int filesize;
char *content;
};
void print_struct(struct Payload * pl) {
printf("filename: %s\n", pl->filename);
printf("content: %s\n", pl->content);
}
int main()
{
struct Payload pl1;
struct Payload *pl2 = malloc(sizeof(struct Payload)); // use pointer.
if(!pl2) {
return 0;
}
pl1.content = malloc (sizeof(char)*30); // max length of content is 29 in this case.
if(!pl1.content) {
return 0;
}
strcpy(pl1.content,"pl1.content");
pl1.filename = malloc (sizeof(char)*30); // max length of filename is 29 in this case.
if(!pl1.filename) {
return 0;
}
strcpy(pl1.filename,"pl1.filename");
pl2->content = malloc (sizeof(char)*30); // max length of content is 29 in this case.
if(!pl2->content) {
return 0;
}
strcpy(pl2->content,"pl2->content");
pl2->filename = malloc (sizeof(char)*30); // max length of filename is 29 in this case.
if(!pl2->filename) {
return 0;
}
strcpy(pl2->filename,"pl2->filename");
print_struct(&pl1); // pass by reference
print_struct(pl2); // pass by pointer
free(pl1.content);
free(pl1.filename);
free(pl2->content);
free(pl2->filename);
free(pl2);
return 0;
}
the output:
filename: pl1.filename
content: pl1.content
filename: pl2->filename
content: pl2->content