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.
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);
I have created an array of structs and I am getting a BAD_ACCESS error. When I switch everything to dot notation it works fine, why is this?
Struct
typedef struct data{
int num;
}data;
Main
int main(void){
// This works
data data[4];
data[0].num = 10;
printf("Number is = %d\n", data[0].num);
// This does not work
data *data[4];
data[0]->num = 10;
printf("Number is = %d\n", data[0]->num);
// This does not work
data *data[4];
data[0]->num = 10;
printf("Number is = %d\n", data[0]->num);
Since data is an array of four pointers, data[0] is the first of those four pointers. But what does it point to? Since you haven't done something like data[0] = malloc(sizeof(struct data));, it points to nothing in particular -- uninitialized garbage. It's not surprising that trying to write to what the pointer points to causes a bad access error.
Before you dereference a pointer, you need to make the pointer actually point to something.
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
I am working on an assignment and ran into challenging problem. As far as I'm concerned and from what I've learnt the code that follows should be correct however it does not work. Basically what I am trying to is copy a string value into the variable member of a structure the is part of an array passed into a method as a pointer. What am I missing?
typedef struct
{
char * name; //variable in struct I am trying to access
} Struct;
void foo(Struct * arr) //array of Structs passed into function as a pointer
{
int i = 0;
while(i++ < 2)
{
arr[i].name = malloc(sizeof(char *)); //assigning memory to variable in each Struct
arr[i].name = strdup("name"); //copying "name" to variable in each Struct
printf("C - %s\n", arr[i].name); //printing out name variable in each Struct
}
}
main()
{
Struct * arr; //defining pointer
arr = calloc(2, sizeof(Struct)); //allocating memory so pointer can hold 2 Structs
foo(arr); //calling function foo passing pointer into function
return 0;
}
This code compiles and runs however it does not do what it is designed to do. Forgive me if it is something trivial. I am new to the language C
Two issues:
while(i++ < 2) This line changes the value of i as soon as it checks it, so your loop body will not be the same as it was checked.
arr[i].name = strdup("name"); overwrites the value of the .name pointer, causing a memory leak of the memory you malloc()'ed earlier.
Extending on 2 pointed out correctly already,
arr[i].name = strdup("name");
Even if you use following instead of above,
strcpy(array[i].name, "name");
you haven't allocated enough bytes to store the string i.e. this is wrong
arr[i].name = malloc(sizeof(char *));
// even if pointer is 8 byte here, concept isn't right
Should be something like
arr[i].name = malloc(strlen("name")+1);
// or MAX_SIZE where it is greater than the possible "name".
Or better yet, remove the malloc at all, strdup takes care of allocation itself
This is not answering your question directly, but addresses an issue to big to put into a comment...
Additional issue: You probably did not intend to allocate only a (char *) worth of memory to a variable intended to hold at least "name". Change;
arr[i].name = malloc(sizeof(char *));
to:
arr[i].name = malloc(sizeof(char)*strlen("name")+1); //+1 for '\0'
or better yet, use char *name="name";, then:
arr[i].name = malloc(sizeof(char)*strlen(name)+1);
Even more general (and better):
char *name;
name = malloc(strlen(someInputString)+1);
//do stuff with name...
free(name);
Now, you can allocate name to any length needed based on the length of someInputString.
[EDIT]
Etienz, I wanted to address one more thing, alluded to by #H2CO3 above, but not really explained, that I think might be useful to you:
Regarding your desire to have room for two structs, because you typedef'd your struct, you can simply do something like this: (but I am going to change the name you used from Struct to NAME :) The whole point being that when a struct is created as an array, you do not need to use calloc or malloc to create space for them, it is done as shown below...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char *name;
}NAME;
//use new variable type NAME to create global variables:
NAME n[2], *pN; //2 copies AND pointer created here
//prototype func
int func(NAME *a);
int main()
{
pN = &n[0]; //pointer initialized here
func(pN); //pointer used here (no malloc or calloc)
printf("name1 is %s\nname 2 is %s", pN[0].name, pN[1].name);
return 0;
}
int func(NAME *a)
{
char namme1[]="andrew";
char namme2[]="billebong";
//You DO have to allocate the members though
a[0].name = malloc(strlen(namme1)+1);
a[1].name = malloc(strlen(namme2)+1);
strcpy(a[0].name, namme1);
strcpy(a[1].name, namme2);
return 0;
}
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);