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);
Related
I have defined a struct as below
struct Invariant
{
int * numberOfConstPi; // Saves the number of constant Pi in each kernel
Invariant * next;
};
I then modified it later in the code as
invariant->numberOfConstPi = (int *)calloc(invariant->numberOfUniqueKernels, sizeof(int));
invariant->numberOfConstPi[countKernel] = numberOfConstPi;
Where countKernel is an iterator and numberOfConstPi is a variable.
Is this the correct way? When I run the code I'm getting segmentation errors.
But when I instead defined the array as
int * hello = (int *)calloc(invariant->numberOfUniqueKernels, sizeof(int));
and
hello[countKernel] = numberOfConstPi;
It works perfectly fine.
Kindly ignore the int variable numerOfUniqueKernels. It's just a number which I deleted from the Struct(to make the struct look simpler for the question)
You don't show much code, but as for your question regarding this piece of code,
invariant->numberOfConstPi = (int *)calloc(invariant->numberOfUniqueKernels, sizeof(int));
invariant->numberOfConstPi[countKernel] = numberOfConstPi;
Is this the correct way?
I can say, this is a valid way to do it.
But you don't show much code and you say that you are running into segfault errors. I would guess that maybe you are not allocating memory for the pointer to struct?
You should have something like,
Invariant *invariant = malloc(sizeof*invariant);
my project is to build book structure - and fill it with users parameters.
involving dynamic allocation, arrays and pointers.
my book structure has the following:
struct BOOK
{
char* author;
char** genders;
int totalGenders;
char* name;
int* chapterPages;
int totalChapters;
}typedef book;
when I tried reaching author name, line 1 in structure:
struct BOOK
{
char* author;
I failed doing that.. my code in main :
int main()
{
book* b;
char authorChar[10] = { 0 };
int authorLen;
char* authorName;
// get author name
puts("please enter the name of the author");
scanf("%s", &authorChar);
authorLen = strlen(authorChar);
printf("%d", authorLen); //print to see that lentgh is correct.
authorName = (char*)calloc(authorLen, sizeof(char));
strcpy(authorName, authorChar);
puts("\n");
b->author = authorName;
printf("%d", b->author);
when i have debugged i got a problem in this line :
b->author = authorName;
ideas please? :)
The problem is in the following line
b->author = authorName;
at this point, b is not allocated memory, i.e., b is an uninitialized pointer. It points to some random memory location which is not a valid one. Any attempt to access invalid memory invokes undefined behavior.
You can use either of the following approach to resolve the issue:
allocate memory to b dynamically before using it, like b = malloc(sizeof*b); and a check for success.
define b as a variable of type book, instead of a pointer-to-type.
That said, int main() should be int main(void) at least, to conform to the standards.
You are forgetting to do the memory allocation for b variable.
b = malloc(sizeof(book));
b->author = malloc(sizeof(100000)); // replace value for the size you want
I've a struct like the one who follows:
typedef struct author
{
char letter;
char *name[200];
int counter;
} Aut, *i_aut;
It consists of a char, and array of "Strings" and int. My goal is to allocate space in memory for an array of 30 of this kind of structs, therefore I tried something like the following:
i_aut lista_autores=calloc(30,sizeof(Aut));
However, it always returns "segmentation fault". I tried to initialize one at a time too, but with the same result. My question is, how do I allocate memory of this kind and how can I access it later?
Thank you in advance, and sorry for any typo.
the struct member name is an array of 200 pointers.
You may want to assign the result of malloc to elements of the array.
struct author *i_aut;
i_aut = malloc(sizeof *i_aut);
if (i_aut) {
for (size_t k = 0; k < 200; k++) {
i_aut->name[k] = malloc(30);
if (!i_aut->name[k]) /* error */;
/* DONT FORGET TO FREE EACH NAME LATER ON */
}
free(i_aut);
}
try using this
struct author **i_aut;
i_aut=(struct author **)malloc(30*sizeof(struct author*));
for(i=0;i<30;i++)
i_aut[i]=(struct *)malloc(sizeof(struct author));
after this you need not allocate space for name[] seperately.
you have array of 30 elements of type struct author*
and you can access all three type using
i_aut[i]->letter;
i_aut[i]->name[j];
i_aut[i]->counter;
here i<30
Firstly, I am really sorry if this has already been asked and resolved - I have spent ages searching and trying to adapt code samples to give me what I need... but sadly to no avail. Essentially I am just trying to copy the contents of one struct to another (which is documented here elsewhere but I cannot get it to work).
A scanner populates the following struct when it reads a barcode:
struct barcode
{
char *text;
int length;
int id;
int min;
int max;
};
This is instantiated as:
static struct barcode code = {0};
I instantiate another one of the same type:
struct barcode *barcodeHolder;
This is intended to store a copy of the scanned barcode. This is because other codes will then be scanned that indicated other steps such as barcodes to indicate numbers or stages (eg. end, start, etc). Once I want to write the struct contents to disk I use the "copy" of the struct as that is what I want.
However, the char *text property always equals 'c' and not the value of the barcode.
I copy them as follows:
barcodeHolder = malloc(sizeof(code));
barcodeHolder->text = malloc(strlen(code->text) + 1);
strcpy(barcodeHolder->text, code->text);
barcodeHolder->id = code->id;
barcodeHolder->length = code->length;
barcodeHolder->max = code->max;
barcodeHolder->min = code->min;
This is what I have got from other posts on a similar topic.
However, I am clearly doing something stupidly wrong and would welcome any help anyone might be able to offer so that my copy of the struct text element does actually get the right value copied.
Thank you!
Your code is not a pointer
You need this:
barcodeHolder = malloc(sizeof(code));
barcodeHolder->text = malloc(strlen(code.text) + 1);
strcpy(barcodeHolder->text, code.text);
barcodeHolder->id = code.id;
barcodeHolder->length = code.length;
barcodeHolder->max = code.max;
barcodeHolder->min = code.min;
I don't believe that your code is really:
static struct barcode code = {0};
[..]
strcpy(barcodeHolder->text, code->text);
Because the last statement would yield a compile error - because code is not a pointer you have to use code.text there (instead of code->text).
Assuming that you are actually using something like
struct barcode *code = ...;
You are allocating with your above code sizeof pointer of struct code bytes which is not enough for your structure.
Thus, copy it like this:
barcodeHolder = malloc(sizeof(struct barcode));
// alternative: ... = malloc(sizeof(*code));
*barcodeHolder = *code;
barcodeHolder->text = malloc(strlen(code->text) + 1);
strcpy(barcodeHolder->text, code->text);
Or, more simply:
barcodeHolder = malloc(sizeof(code));
*barcodeHolder = code;
barcodeHolder->text = strdup(code.text);
Probably unrelated, but if code in your example is a pointer to a struct, then your sizeof is wrong. It should be sizeof(*code) or sizeof(struct barcode). – Sean Bright 21 hours ago
#SeanBright In no way would I ever call myself a C programmer - ever! - so you saved completely here! Thank you. No, "code" is not a pointer in programme which confused me too... and was probably why I couldn't get anywhere. I just needed to get it work to prove we can do it for a demo. Should it progress I will come back (hopefully!) and revisit the code to better understand why it is working when it maybe shouldn't be. Thank you again!!!
Hi friends following practice program getting compiled with zero errors but output is not showing in console window...i think there is something which i am missing ...please guide me...thanks!
struct card{
char *face;
char *suit;
}aCard,deck[52], *cardPtr;
int main()
{
struct card aCard; //define one struct card Variable
struct card *cardPtr; //define a pointer to structure card
cardPtr = &aCard;
printf("%s\n %s\n",cardPtr->face, cardPtr->suit);
system("PAUSE");
return 0;
}
You haven't assigned anything to aCard. Assign values to aCard and then assign it to cardPtr.
aCard.face="Hello";
aCard.suit="world";
cardPtr = &aCard;
Now you can see the values getting printed.
cardPtr->face and cardPtr->suit are uninitialized. Hence, undefined behaviour. Allocate memory, and assign values before printing.
EDIT
cardPtr->face = malloc(n * sizeof(char));
where n is the number of characters that the memory block can hold. You will still have to put something in this char array before printing it.