Passing strings through and array to a struct in C - arrays

I'm pretty new to C and I'm not sure what I'm doing. Im trying to create a simple function to create a book. I want to pass two strings in as parameters but I don't know the proper way to access them in C. I have tried many things here is where I am at. Thanks for any help!
#include <stdio.h>
struct book {
char title[50];
char author[50];
};
struct book createBook(char title[50], char author[50]) {
struct book x = { title, author };
return x;
}

You won't be able to initialize the members this way since they're strings.
Use strncpy from string.h:
#include <string.h>
strncpy(x.title, title, 50);
strncpy(x.author, author, 50);
And your declaration would just become:
struct book x;

Use can't initialize variable or members using this way struct book
x = { title, author };
use strcpy() or strncpy() for initializing member variables
strncpy_s(x.title, "Kite Book",sizeof(x.title));
strncpy_s(x.author, "Andre",sizeof(x.author));
or
strcpy(x.title, "Kite Book");
strcpy(x.author, "Andre");
#include <stdio.h>
#include<string.h>
struct book {
char title[50];
char author[50];
};
struct book createBook(char title[50], char author[50]) {
struct book x;
strncpy_s(x.title, "Kite Book",sizeof(x.title));
strncpy_s(x.author, "Andre",sizeof(x.author));
return x;
}
int main()
{
char title[] = { "Kite" };
char author[] = { "Andre" };
createBook(title, author);
return 0;
}

Related

How to nest structures?

typedef struct{
char name_cake[10];
char code_cake[10];
int stock_cake;
char about_cake[10];
char cake_taste[10];
}order;
typedef struct{
char name_cake[10];
char code_cake[10];
int stock_cake;
char about_cake[10];
char cake_taste[10];
}cake;
how to the contents of typedef struct become one? and I can invoke the command with
information.order.name_cake
information.cake.name_cake
for simply and not waste of words, thank
I would recommend to use the same struct for cake and order, there is no polymorphism in c
To access them in the way you like:
#include <stdio.h>
typedef struct{
char name_cake[10];
char code_cake[10];
int stock_cake;
char about_cake[10];
char cake_taste[10];
}order;
typedef struct{
char name_cake[10];
char code_cake[10];
int stock_cake;
char about_cake[10];
char cake_taste[10];
}cake;
typedef struct {
union {
order the_order;
cake the_cake;
}; // anonymous union
}information;
int main() {
order an_order = {"cakename", "code", 0, "about", "taste"};
information info = *((information*)&an_order);
printf("From order: %s\n", info.the_order.name_cake);
printf("From cake: %s\n", info.the_cake.name_cake);
return 0;
}
$ gcc -Wall ordercake.c
$ ./a.out
From order: cakename
From cake: cakename
$
In general you want to do object-oriented programming in C. Therefore, take a look at: How can I simulate OO-style polymorphism in C? (There is even a free book as pdf linked on how to do it.)
And now an example for a struct in a struct:
#include <stdio.h>
typedef struct{
char name_cake[10];
char code_cake[10];
}cake;
typedef struct{
cake the_cake; // the common part
char cake_extension[10]; // the new part, order is important
}extended_cake;
int main() {
extended_cake an_extended_cake = {{"cakename", "code"}, "extension"};
// now treat it as a cake
cake *a_normal_cake = (cake *)&an_extended_cake;
printf("From cake: %s\n", a_normal_cake->name_cake);
return 0;
}
$ gcc -Wall ordercake.c
$ ./a.out
From cake: cakename
$
Not sure what you're going to do, but you can simply nest structures like this:
struct foo {
order order;
cake cake;
}
If you want the contents of order and cake occupy the same memory space, you should use an anonymous union, as written above.
#include<stdio.h>
#include<string.h>
struct sports
{
char name[40];
int age;
/*nested structure*/
struct medicaltests
{
char isFit[1];
} med;/*nested object*/
};
int
main ()
{
struct sports sportobj;/*Declare object*/
strcpy (sportobj.name, "venkateshwar krishnan");
sportobj.age = 40;
strcpy (sportobj.med.isFit, "Y");
printf ("name of sportsman%s\n", sportobj.name);
printf ("IsFit %s", sportobj.med.isFit);
return 0;
}

calling a function need struct with substruct

I don't know if my title is really clear (I don't really know how to named it) but nevermind. I've got a function with a substruct in parameter. I used the struct in the main, but not in the function because of the useless data inside for this function. My program is like that :
typedef struct vidinfo_s {
vidframe_s sVid;
int id;
[...]
};
typedef struct vidframe_s {
int phyAddr[3];
char *virAddr[3];
[...]
};
int function (vidframe_s *pVid)
My question is : I need to call a function like int callVidInfo(vidinfo_s *pVid) but I don't really know how to do it with the substruct (as I named vidframe_s) so is there a way to do that or must I call my main struct in function?
Yes, there is a way. You posted very little code, but probably you are searching for smth called offsetof or containerof:
#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>
#include <assert.h>
struct vidframe_s {
int unused;
};
struct vidinfo_s {
struct vidframe_s sVid;
int id;
};
int callVidInfo(struct vidinfo_s * vidinfo) {
assert(vidinfo->id == 5);
return 0;
}
int function(struct vidframe_s *pVid) {
const size_t offsetofsVid = offsetof(struct vidinfo_s, sVid);
struct vidinfo_s * const vidinfo = (struct vidinfo_s*)((char *)pVid - offsetofsVid);
return callVidInfo(vidinfo);
}
int main() {
struct vidinfo_s var = { .id = 5 };
return function(&var.sVid);
}
See what i did there? I took the offset between struct vidinfo_s and it's member called sVid. Then i subtracted the offset from pVid pointer (which should point inside a struct vidinfo_s structure), thus i was left with the pointer to struct vidinfo_s.

accessing the array inside array of structures

I have a structure as follows
struct a
{
char* ap;
char* inputs[10];
int e;
};
then I have created an array of this structure like struct a list [100];
now i want to fille the array inputs[10] and for that I am using the syntax to access the first location :
ip=0;
inp=0;
list[ip].inputs[inp]
but I am gettin the error "error C2107: illegal index, indirection not allowed" on compiling the code
please suggest how to access the array location inside array of structure.
regards
priya
Here you use array of character pointer in your structure. So Initially you allocate memory for you structure by creation list of 100. I think you didn't create memory for you array of character pointer. You have to create memory for each of character pointer. So I suggest example code.
#include <stdio.h>
struct a
{
char* ap;
char* inputs[10];
int e;
};
int main()
{
int ip=0;
int inp=0;
struct a list[100];
list[ip].inputs[inp]= (char*)malloc(25);
scanf("%s",list[ip].inputs[inp]);//Or other copy function to fill string
printf("output %s",list[ip].inputs[inp]);
}
Working fine on my pc.. here is my code..
#include <stdio.h>
struct a
{
char* ap;
char* inputs[10];
int e;
};
int main()
{
int ip=0;
int inp=0;
struct a list[100];
list[ip].inputs[inp] = 'A';
printf("This: %c", list[ip].inputs[ip]);
return 0;
}
OUTPUT= This: A
let me know whether it helped or not..
The struct themselves do not have data. You need to create objects of the struct type and set the objects ...
struct a
{
char* ap;
char* inputs[10];
int e;
};
/* I like to separate the type definition from the object creation */
struct a list [3];
list [0].inputs[0] = "Choclate";
list [0].inputs[1] = "Almond";
list [0].inputs[2] = "Rasberry";
Hope it ll usefull. Also refer this article

How to use a function pointer in a C struct?

I want to learn more about using function pointers in C structs as a way to emulate objects-oriented programming, but in my search, I've just found questions like this where the answer is simply to use a function pointer without describing how that would work.
My best guess is something like this
#include <stdio.h>
#include <stdlib.h>
struct my_struct
{
int data;
struct my_struct* (*set_data) (int);
};
struct my_struct* my_struct_set_data(struct my_struct* m, int new_data)
{
m->data = new_data;
return m;
}
struct my_struct* my_struct_create() {
struct my_struct* result = malloc((sizeof(struct my_struct)));
result->data = 0;
result->set_data = my_struct_set_data;
return result;
}
int main(int argc, const char* argv[])
{
struct my_struct* thing = my_struct_create();
thing->set_data(1);
printf("%d\n", thing->data);
free(thing);
return 0;
}
But that give me compiler warnings warning: assignment from incompatible pointer type, so obviously I'm doing something wrong. Could someone please provide a small but complete example of how to use a function pointer in a C struct correctly?
My class taught in C does not even mention these. It makes me wonder whether these are actually used by C programmers. What are the advantages and disadvantages of using function pointers in C structs?
The answer given by Andy Stow Away fixes my compiler warning, but doesn't answer my second question. The comments to that answer given by eddieantonio and Niklas R answer my second question, but don't fix my compiler warning. So I'm pooling them together into one answer.
C is not object-oriented and attempting to emulate object-oriented design in C usually results in bad style. Duplicating methods called on structs so that they can be called using a pointer to the struct as I have in my example is no exception. (And frankly, it violates DRY.) Function pointers in structs are more useful for polymorphism. For example, if I had a struct vector that represented a generic container for a linear sequence of elements, it might be useful to store a comparison_func member that was a function pointer to allow sorting and searching through the vector. Each instance of the vector could use a different comparison function. However, in the case of a function that operates on the struct itself, it is better style to have a single separate function that is not duplicated in the struct.
This makes the answer to what is correct more complicated. Is what is correct how to make my above example compile? Is it how to reformat my above example so that it has good style? Or is it what is an example of a struct that uses a function pointer the way C programmer would do it? In formulating my question, I did not anticipate the answer being that my question was wrong. For completeness, I will provide an example of each answer to the question.
Fixing the Compiler Warning
#include <stdio.h>
#include <stdlib.h>
struct my_struct
{
int data;
struct my_struct* (*set_data) (struct my_struct*, int);
};
struct my_struct* my_struct_set_data(struct my_struct* m, int new_data)
{
m->data = new_data;
return m;
}
struct my_struct* my_struct_create()
{
struct my_struct* result = malloc((sizeof(struct my_struct)));
result->data = 0;
result->set_data = my_struct_set_data;
return result;
}
int main(int argc, const char* argv[])
{
struct my_struct* thing = my_struct_create();
thing->set_data(thing, 1);
printf("%d\n", thing->data);
free(thing);
return 0;
}
Reformatting the Style
#include <stdio.h>
#include <stdlib.h>
struct my_struct
{
int data;
};
void my_struct_set_data(struct my_struct* m, int new_data)
{
m->data = new_data;
}
struct my_struct* my_struct_create()
{
struct my_struct* result = malloc((sizeof(struct my_struct)));
result->data = 0;
return result;
}
int main(int argc, const char* argv[])
{
struct my_struct* thing = my_struct_create();
my_struct_set_data(thing, 1);
printf("%d\n", thing->data);
free(thing);
return 0;
}
Demonstrating a Use for Function Pointer in Structs
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct my_struct
{
void* data;
int (*compare_func)(const void*, const void*);
};
int my_struct_compare_to_data(struct my_struct* m, const void* comparable)
{
return m->compare_func(m->data, comparable);
}
struct my_struct* my_struct_create(void* initial_data,
int (*compare_func)(const void*, const void*))
{
struct my_struct* result = malloc((sizeof(struct my_struct)));
result->data = initial_data;
result->compare_func = compare_func;
return result;
}
int int_compare(const void* a_pointer, const void* b_pointer)
{
return *(int*)a_pointer - *(int*) b_pointer;
}
int string_compare(const void* a_pointer, const void* b_pointer)
{
return strcmp(*(char**)a_pointer, *(char**)b_pointer);
}
int main(int argc, const char* argv[])
{
int int_data = 42;
struct my_struct* int_comparator =
my_struct_create(&int_data, int_compare);
char* string_data = "Hello world";
struct my_struct* string_comparator =
my_struct_create(&string_data, string_compare);
int int_comparable = 42;
if (my_struct_compare_to_data(int_comparator, &int_comparable) == 0)
{
printf("The two ints are equal.\n");
}
char* string_comparable = "Goodbye world";
if (my_struct_compare_to_data(string_comparator,
&string_comparable) > 0)
{
printf("The first string comes after the second.\n");
}
free(int_comparator);
free(string_comparator);
return 0;
}
In your struct definition, change it to
struct my_struct
{
int data;
struct my_struct* (*set_data) (struct my_struct*,int);
};
and now use the above function pointer in main as
thing->set_data(thing,1);

initializing structures and nesting structures

gcc
I am just getting back into c programming and I am just practicing with structures. However, I have a nested structure that I want to fill from another initialized structure. However, I don't think my technique is correct way to do this.
Any advice would be most helpfull,
#include <stdio.h>
typedef struct
{
char name[20];
int age;
} NAME_AGE_STRUCT;
typedef struct
{
int ID;
NAME_AGE_STRUCT info[];
} DETAILS_STRUCT;
int main(void)
{
DETAILS_STRUCT details;
NAME_AGE_STRUCT extra_details [] = {
{ "john", 34 },
{ "peter", 44 },
};
printf("=== Start program\n");
details.ID = 2;
details.info = extra_details;
return 0;
}
You need to specify a length of the array in the DETAILS_STRUCT; otherwise there's no memory to assign into. If you want to have an arbitrary array there, declare it as a pointer instead:
typedef struct
{
int ID;
NAME_AGE_STRUCT *info;
} DETAILS_STRUCT;

Resources