Copy Struct to Array of Structs Received as Pointer Argument in Function - c

I've got a function that takes as an argument a pointer to an array of structs:
void foo (int *StructArrayAddress)
Within the function, I then build a new struct that looks like this
struct
{
int a;
int b;
char c[10];
}myStruct;
What I would then like to do is copy that struct to my array of structs based on the pointer to that array that I received as an argument. Not having any luck with the syntax, or I'm missing something. Can anyone advise?
Thanks!
EDIT: I'm not sure I explained myself correctly, as I don't think the solution posted here is what I want to do. To clarify: there is some array of structs outside my function here. I receive the address of the correct struct element in an array of structs as an argument to my function. Assume the caller already took care of passing me the correct address; I don't have to index it up at all.
I then locally build a struct from some other data. I now want to copy this struct that I built locally to the struct at the location in the array that I received as an argument.
void foo (int *StructArrayAddress)
{
struct
{
int a;
int b;
char c[10];
}myStruct;
a = 5;
b = 10;
c = {1,2,3,4,5,6,7,8,9,10};
//Copy local struct myStruct to location StructArrayAddress here
StructArrayAddress = myStruct; //Something like this but I have the syntax wrong
}
I hope that makes more sense.
EDIT2: I may have just realized something that you guys have been trying to convey to me that I was missing: is a reference to my local struct needed in the argument somehow so that the format of the structure as I pass it back is known?

Your function definition should be like
void foo (myStruct *StructArrayAddress, int index)
{
myStruct x;
x.a = 1;
x.b = 2;
strncpy(x.c, "Test", 9);
/* Now copy this struct to the array of structs at index specified by second argument */
memcpy((StructArrayAddress + index), &x, sizeof(myStruct));
}

Related

Accessing the nested Structural Elements

#include<stdio.h>
struct a
{
float n;
int e;
};
struct b
{
struct a *c;
}h;
int main()
{
h.c->n=4;
printf("%f",h.c->n);
return 0;
}
Yes it is small code but I have been trying to access the element e which is instruct a through the struct b. The code is compiled without any error but in the output screen, it is blank.
Please suggest me a good way to access the element in the struct a.
Please note that the struct a has been declared inside the struct b as a pointer.
This would crash because your pointer c was never allocated.
h.c->n=4; // pointer `c` has not been pointing to anything valid
To make it work, you need something like this:
struct a aa; // must allocate an item of struct `a` first
aa.n = 4;
aa.e = 0;
h.c = &aa; // then make pointer `c` to point that that item
printf("%f",h.c->n); // before trying to access that pointer

Get the same field from different structures using the same function in C

I want to have two structures in C, for example:
A:
typedef struct a
{
char *text;
int something;
}A;
and B:
typedef struct b
{
char *text;
float something_else;
}B;
Now, as far as I know, it is not possible to have a function which takes a void * parameter to get the text element from both structures. Am I wrong, is this possible in standard C?
Yes you can, using casting and the fact that the text element is the first element of both structures:
void f(void *t)
{
printf("%s\n", *((char **)t));
}
int main()
{
struct a AA = {"hello",3};
struct b BB = {"world",4.0};
f(&AA);
f(&BB);
return 0;
}
Note: Passing the address of the struct means it points to the address of text. This must then still be dereferenced one more time to get at the adress of the text itself, which is then passed to printf.
Edit: a cast to (void *) in the calls to f are not necessary (casts removed).

Understanding pointer structs in C

I am trying to understand an assignment I have before I have to take a final. I am trying to understand what exactly I am declaring.
So in a given file the typedef struct's are declared as so:
(Struct Declaration)
/** The following two structs must be defined in your <gamename>.c file **/
typedef struct game_position_t *game_position;
/* move struct must code enough information to reverse the move, given the resulting position */
typedef struct move_t *move;
I have then built the structs out as so (yes this has to be separated just because it is interfaced programming):
(Struct Definition)
/** The following two structs must be defined in your <gamename>.c file **/
struct game_position_t {
int mathy;
int numrows;
int *sizes;
};
/* move struct must code enough information to reverse the move, given the resulting position */
struct move_t {
int rownum;
int move_size;
};
Then an example of a functions and declaration of game_position for example is:
(Example Function)
/* return the starting position, NULL if error */
game_position starting_position(int me_first, int argc, char **argv) {
if (argc < 3) {
printf("\n\nToo few arguments, see help below\n\n");
game_help(argv[0]);
return NULL;
}
int mathy;
if (strcmp(argv[2],"search")==0)
mathy = 0;
else if (strcmp(argv[2],"mathy")==0)
mathy = 1;
else {
printf("\n\nSecond argument must be \"search\" or \"mathy\", see help below\n\n");
game_help(argv[0]);
return NULL;
}
int play_default = (argc==3);
if (play_default) printf("\n\nOK, we will play the default game of 7 5 3 1\n\n");
int defaultgame[4] = {7,5,3,1};
game_position result = malloc(sizeof(struct game_position_t)*1);
result->mathy = mathy;
if (result) {
result->numrows = (play_default ? 4 : argc-3);
result->sizes = malloc(sizeof(int)*(result->numrows));
int row;
for (row=0; row<(result->numrows); row++)
(result->sizes)[row] = (play_default ? defaultgame[row] : strlen(argv[row+2]));
}
return result;
}
So my main misunderstanding is when using a struct declaration in this manner, specifically putting the * before the name like this, typedef struct move_t *move;. Is that previous line saying move it a struct pointer or dereferencing move? Continuing from that. When defining them I just use the struct name such as struct move_t. I don't fully understand how they are linking together and in what matter. Then inside the function I just declare game_position, but still need to use a derefencer, 'p->`, to access it fields. So if someone could explain to me when these struct variables are points to structs and when they are the actual struct.
An example of my misunderstanding is that in the Example Function after result was declared. I first thought to use the . operator to access and set it's fields. I then changed it due to compiler errors, but now I want to understand my misunderstanding. And why did I I have to malloc game_position_t and not game_position?
typedef defines a type, so typedef struct move_t *move defines a new type named move, which is a pointer type, pointing to struct move_t. So after this if you define a variable with move ptr, ptr will have a pointer type so that you should use the syntax of accessing members through a pointer. When allocating memory for it, of course you have to specify the exact size of the structure other than the size of a pointer, that's sizeof(struct move_t)

Kind of polymorphism in C

I'm writing a C program in which I define two types:
typedef struct {
uint8_t array[32];
/* struct A's members */
...
} A;
typedef struct {
uint8_t array[32];
/* struct B's members, different from A's */
...
} B;
Now I would like to build a data structure which is capable of managing both types without having to write one for type A and one for type B, assuming that both have a uint8_t [32] as their first member.
I read how to implement a sort of polymorphism in C here and I also read here that the order of struct members is guaranteed to be kept by the compiler as written by the programmer.
I came up with the following idea, what if I define the following structure:
typedef struct {
uint8_t array[32];
} Element;
and define a data structure which only deals with data that have type Element? Would it be safe to do something like:
void f(Element * e){
int i;
for(i = 0; i < 32; i++) do_something(e->array[i]);
}
...
A a;
B b;
...
f(((Element *)&a));
...
f(((Element *)&b));
At a first glance it looks unclean, but I was wondering whether there are any guarantees that it will not break?
If array is always the first in your struct, you can simply access it by casting pointers. There is no need for a struct Element. You data structure can store void pointers.
typedef struct {
char array[32];
} A;
typedef struct {
void* elements;
size_t elementSize;
size_t num;
} Vector;
char* getArrayPtr(Vector* v, int i) {
return (char*)(v->elements) + v->elementSize*i;
}
int main()
{
A* pa = malloc(10*sizeof(A));
pa[3].array[0] = 's';
Vector v;
v.elements = pa;
v.num = 10;
v.elementSize = sizeof(A);
printf("%s\n", getArrayPtr(&v, 3));
}
but why not have a function that works with the array directly
void f(uint8_t array[32]){
int i;
for(i = 0; i < 32; i++) do_something(array[i]);
}
and call it like this
f(a.array)
f(b.array)
polymorphism makes sense when you want to kepp
a and b in a container of some sorts
and you want to iterate over them but you dont want to care that they are different types.
This should work fine if you, you know, don't make any mistakes. A pointer to the A struct can be cast to a pointer to the element struct, and so long as they have a common prefix, access to the common members will work just fine.
A pointer to the A struct, which is then cast to a pointer to the element struct can also be cast back to a pointer to the A struct without any problems. If element struct was not originally an A struct, then casting the pointer back to A will be undefined behavior. And this you will need to manage manually.
One gotcha (that I've run into) is, gcc will also allow you to cast the struct back and forth (not just pointer to struct) and this is not supported by the C standard. It will appear to work fine until your (my) friend tries to port the code to a different compiler (suncc) at which point it will break. Or rather, it won't even compile.

New to C and C Structures -- How to take a struct as a parameter in a function

New to StackOverflow and new to C. I'm trying to take a struct as a parameter in a function 'add_fields', which adds the first two int fields 'a' and 'b' and puts the result in int field 'c'. Not getting anything from the compiler, so obviously I'm doing something wrong. I just don't know what. Any help would be appreciated.
#include <stdio.h>
struct add{
int a;
int b;
int c;
}
void add_fields(struct add *d){
d->c = a + b;
}
main(){
struct add data;
data.a = 1;
data.b = 2;
data.c = 0;
add_fields(data);
printf("%d + %d = %d", data.a, data.b, data.c);
}
You're very close, but variables a and b don't exist in that context, rather you need to access the fields via the pointer to struct d:
d->c = d->a + d->b;
Second, you need to pass a reference to the struct (since add_fields expects a pointer) when you call add_fields:
add_fields(&data);
The & indicates that you're going to pass the address of the variable data rather than the value.
Here is your corrected code:
#include <stdio.h>
struct add{
int a;
int b;
int c;
};
void add_fields(struct add *d){
d->c = d->a + d->b;
}
int main(){
struct add data;
data.a = 1;
data.b = 2;
data.c = 0;
add_fields(&data);
printf("%d + %d = %d", data.a, data.b, data.c);
return 0;
}
You forgot a semicolon after the struct definition.
I had to fix your add_fields function. You didn't use your struct for a and b.
You needed to pass a pointer into add_fields (hence the &) in the function call. By passing a pointer in, your changes in add_fields were reflected on the outside calling struct.
main always returns an int.
There are several issues:
In main, data is of type struct add. When you call add_field, you need to pass it a struct add* (that is, a pointer to a struct add). To get a pointer to data in main, you need to use the & operator:
add_fields(&data);
In add_fields, you need to use the "member access syntax" (the ->) to access a and b.
Two other minor issues: main should have a return type of int:
int main() { ...
and you need to place a semicolon after the closing } of a struct definition.
C is call by value language. When you pass data, you are passing a copy of the object of type struct add. In your add_fields field, you are accepting a pointer to the struct. Since you want to change the fields of the struct, you should pass the address of the data struct (and accept a pointer to it in add_fields). To do this,
add_fields(&data);
Also, in add_fields, you aren't have undefined variables (a and b). I assume they should be from the struct, as well?
You should be passing the memory address of the struct to the add_fields function.
add_fields(&data)
** Wow I was really slow on this one :P

Resources