I have an assignment. I have the entire code but the snippet I am stuck on is the following.
The user must choose between the following projectiles.
Each projectile has a blast radius and this is the code I have so far (for this section):
userProjectileChoice = myProjectiles[3];
myProjectiles[0].projectileName = "cannonBall";
myProjectiles[0].blastRadius = 10;
myProjectiles[1].projectileName = "highExplosiveShell";
myProjectiles[1].blastRadius = 1;
myProjectiles[2].projectileName = "mortarBomb";
myProjectiles[2].blastRadius = 1000;
I need to use the struct as it is required.
Error message is: incompatible types when assigning to type int from type struct
The following has been included so you can see what the above code is referring to.
Projectile name has not been declared, am I declaring it in the above coding?
struct Projectile
{
char name[40];
float blastRadius;
};
float blastRadius;
double cannonBall = 0;
double highExplosiveShell = 1;
double mortarBomb = 2;
struct Projectile myProjectiles[3] = {{"cannonBall",0},{"highExplosiveShell", 1},{"mortarBomb", 2}};
Any assistance would be appreciated, but please keep it simple for me to understand as I said before I am new to this.
I'm not sure what type userProjectileChoice is, so I'm going to assume that it is the same type of the myProjectiles array. Try assigning each property one at a time as so:
userProjectileChoice.projectName = myProjectiles[3].projectileName
userProjectileChoice.blastRadius= myProjectiles[3].blastRadius
It's been years since I've programmed in C, but it's worth a shot.
Or perhaps you mean to assign the "index" and not the entire struct. Like I said, it's difficult to come up with a correct answer when I don't know the type of userProjectileChoice. Perhaps your problem is in the assignment at the beginning of the code. So if the 4th choice is selected then it should be as so:
userProjectileChoice = 3
I think my english is just to bad to understand the other articles about this. But anyway:
I just thought i could write a program (in C), that can store a set of cards.
Not complicated, just store values and names of cards and print them out.
I'm a beginner in C, and because i'm in the section "Strings in Structures" in my Book, i wanted to try out structures on my own. This is my Code so far:
#include <stdio.h>
struct card
{
int value;
char name[];
};
int main(void)
{
const struct card heart[13] = { {2,"two"}, {3,"three"}, {4,"four"}, {5,"five"}, {6,"six"}, {7,"seven"}, {8,"eight"}, {9,"nine"}, {10,"ten"}, {11,"jack"}, {12,"queen"}, {13,"king"}, {14,"ace"} };
int i;
for (i = 0; i < 13; ++i)
{
printf("The card heart-%s has the value of %i", heart[i].name, heart[i].value);
}
return 0;
}
I just wanted to test if it works, so i just wrote the heart-cards in the code. If i want to compile this file, my compiler (gcc/mingw) hits me with 26 errors. It says:
"(near initialization of heart[0])"
"non static initialization of a flexible array member"
I don't really understand this. In the book, everything works as expected. I tried to rebuild the code in the book and changing the names, but it doesn't work. I think it's a problem with the strings, because if i use integers only, everything works.
In already read in another post, that every string should be allocated manually, and there was a code example, but i don't know what all the lines should mean, and i want understand what my code does, so i don't copy + paste.
Could you explain me why this doesn't work?
PS: I am writing currently in windows, so please don't use bash commands to explain or something like that.
I am also german and my english is not the "yellow of the egg", try to explain without using complex 'sentence builds' (i hope you know what i mean :D) and unusual words.
Thanks for all help!
You need to create some space for the name of each card. Easiest way to do this would be to change your struct card definition to something like:
struct card
{
int value;
char name[16]; // doesn't have to be 16, but make sure it's large enough to hold each card name plus a '\0' terminator
};
The prior answers suggest allocating a fixed length for your names. This has limitations and even dangers. It is always a good idea to avoid it all together.
e.g. You want to alter the name during the game, e.g. "Ace (Trump Card)" but that might be both too long even worse overwrite memory. (Many of the known vulnarabilities in code are caused by buffer overruns)
You are also building in a limitation; What if your game needs translating into another language?
By using pointers, you don't need to resort to either variable length structures or fixed string lengths.
You also add the ability to add API access functions that set data, allowing checks before it's written, preventing buffer overruns.
Instead of using character array (aka strings) you should use pointers in your structures. If you follow the link at the bottom I take this further and use pointers to the structures themselves.
As the pointer storage size never changes your names can be of any length and even altered later, perhaps as the game progresses.
Your card could look something like
typedef struct card
{
int value;
char * name;
}
Now the initial assignment can be done like this
card_t card_ace = {14, "Ace"};
And the values are not fixed (unless that is what you want, then you make them const).
card_ace.value = 200;
card_ace.name = "Trump card";
or an array of cards like this
card_t suit_hearts[] = {{2,"two"}, {3,"three"}, {4,"four"}, {5,"five"}, {6,"six"}, {7,"seven"}, {8,"eight"}, {9,"nine"}, {10,"ten"}, {11,"jack"}, {12,"queen"}, {13,"king"}, {14,"ace"}}
Even better make the whole thing using pointers
typedef card_t * cards_t;
cards_t mysuit = &(card_t){2,"two"}, &(card_t){3,"three"}, ...
Perhaps consider makeing the suit a structure.
typedef struct
{
char * name;
card_t ** cards;
} suit_t;
typedef card_t * cards_t[];
suit_t mysuit = {
.name = "Hearts",
.cards = (cards_t){&(card_t){2,"two"}, &(card_t){3,"three"},....}
}
* For a fully working example of the latter, demonstrating using arrays of pointers to sidestep the limitations of variable length members of fixed arrays, see this gist on github
I need to create mini social network in C. I made a struct for each person. And I'm storing each friend in a char pointer with id's. I thought I can manage it like this:
ptr_friends = id1,id2,id3,id4...
and when I need them I could just read those by using strtok.
But I couldn't manage to save it that way. It should be like this:
ptr_friends = ptr_friends + id + ","
but of course it doesn't work this why and I don't know how to do it.
How can I save and use this way? Or if you have another idea for a save method please tell.
I'd suggest that you make ptr_friends a pointer to multiple chars by using malloc(size_t) and then resizing the space with realloc(void *, size_t) everytime you want to add an ID to the friendlist. That way you can just get the numbers using ptr_friends[i].
For example :
int friends_size = 1;
char *ptr_friends = malloc((size_t)1);
ptr_friends[0] = john_id; // john_id is a fictional ID here
And when you want to add a friend :
ptr_friends = realloc(ptr_friends, ++friends_size);
ptr_friends[friends_size-1] = mary_id;
EDIT :
If you want to make a function to add a friend, for example addfriend(char *,int), doing the following is an error :
void addfriend(char *ptr_friends, int *friends_size, int id)
{
ptr_friends = realloc(ptr_friends, (size_t) ++(*friends_size));
ptr_friends[friends_size-1] = id;
}
ptr_friends here is getting reallocated, and since the pointer can move while being reallocated, we're storing it in ptr_friends. But, it's the ptr_friends from inside the function, that means that the pointer we give to the function will not get modified, since arguments to a function are copied elsewhere beforehand. That means that you have to give a pointer to the pointer, so you can modify the pointer in the main code.
I guess this will help you : https://stackoverflow.com/a/5901241/2549281
You should use something like :
strcat(ptr_friends, id);
strcat(ptr_friends, ",");
instead of ptr_friends + id + ","
Would not it be easier to you to do an array of ints with ids?
int max_friends = 50;
int friends_size = 0;
int friends* = malloc(sizeof(int) * MAX_FRIENDS);
friends[friens_size] = id;
friends_size++;
Another suggestion is instead of using a string or a simple array you can use a "generic" dynamic array (using void*). It's a simple code and you can find many examples.
take a look at that question: C dynamically growing array
I am trying to create a dynamic array of structures using malloc(). I have looked at some other answers already on this forum, but I got lost in answers that weren't the same from one question to the next. Here's what I did so far:
//This is above main()
struct linesegs
{
float*X;
float*Y;
float*Z;
float*Q;
float*R;
float*S;
};
struct linesegs *LINE;
//Inside main() I have this:
LINE = malloc((facets*3)*sizeof(linesegs));
//Later on I access the struct like so:
LINE[variable].X = SomeFloatNumber
LINE[variable].Y = SomeFloatNumber
LINE[variable].Z = SomeFloatNumber
LINE[variable].Q = SomeFloatNumber
LINE[variable].R = SomeFloatNumber
LINE[variable].S = SomeFloatNumber
From what I have read the above should be very close to correct, but my compliler underlined the = in LINE = malloc((facets*3)*sizeof(linesegs)); and gives the following error:
A value of type "void*" cannot be assigned to an entity of type "linesegs"
The places I learned this from were not exactly clear what goes where, and in what order they should go. I tried moving stuff around and playing with the pointers to no avail. Hopefully this question will help others (and me) by providing one solid answer with no confusion =). Thanks in advance for help with this.
would this solve the error or warning?
LINE = (struct linesegs *)malloc((facets*3)*sizeof(struct linesegs));
I am trying to learn C. I have created this structure where I am trying to pass names from an existing array to one of the structure element name[100], I am unable to understand how to pass it? Guys please help me and guide me how to do it. It would be a great help if somebody can guide me to a good structure tutorials(there are lots on web, but only basics)…thanks.
typedef struct new_st{
char name[100];
int icon_number;
float calculation;
}var;
char arr_name[] = {“name1”, “name1”, “name1”, “name1” };/this lines throws error
int main(){
var *ptr_var;
New_var = malloc(sizeof(struct new_st)*100);
strcpy(&arr_name[0], ptr_var[1].name);//this lines throws error
return 0;
}
use strcpy() :
strcpy(New_var[0].name, arr_name[0]);
Advice: do not cast the return value from malloc()
--EDIT after the source code posted --
You probably meant: strcpy(ptr_var[1].name, arr_name[0]); and
this is suppose to be:
char *arr_name[] = {“name1”, “name1”, “name1”, “name1” };/*this lines throws error*/
I think what you want to do is this:
var *ptr_var;
ptr_var = malloc(sizeof(struct new_st) * 100);
ptr_var[0].calculation = 1.5f; //assigning variable inside your struct 0 in your array of structs
ptr_var[0].name = "Foobar";
strcpy(&arr_name[0], ptr_var[1].name); //copy string
//Free memory at end of your program
free(ptr_var);