Sample program using Function Pointer and structures. - c

I created a structure and wanted to assign the values to a Function Pointer of another structure. The sample code I wrote is like below. Please see what else I've missed.
#include <stdio.h>
#include <string.h>
struct PClass{
void *Funt;
}gpclass;
struct StrFu stringfunc;
struct StrFu{
int a ;
char c;
};
Initialise(){
}
main()
{
stringfunc.a = 5;
stringfunc.c = 'd';
gpclass.Funt = malloc(sizeof(struct StrFu));
gpclass.Funt = &stringfunc;
memcpy(gpclass.Funt,&stringfunc,sizeof(struct StrFu));
printf("%u %u",gpclass.Funt->a,gpclass.Funt->c);
}

There are several problems:
A function pointer is not the same as void *, in fact you cannot rely on being able to convert between them.
You shouldn't cast the return value of malloc() in C.
You shouldn't call malloc(), then overwrite the returned pointer.
You don't need to use malloc() to store a single pointer, just use a pointer.
You shouldn't use memcpy() to copy structures, just use assignment.
There are two valid main() prototypes: int main(void) and int main(int argc, char *argv[]), and you're not using either.

there is lots of problem in your code , I try to correct it ,hope it will help
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct PClass{
void *Funt;
}gpclass;
struct StrFu{
int a ;
char c;
};
struct StrFu stringfunc;
int main()
{
stringfunc.a = 5;
stringfunc.c = 'd';
gpclass.Funt = malloc(sizeof(struct StrFu));
gpclass.Funt = &stringfunc;
memcpy(gpclass.Funt,&stringfunc,sizeof(struct StrFu));
printf("%d %c",((struct StrFu*)gpclass.Funt)->a,((struct StrFu*)gpclass.Funt)->c);
return 0;
}
it outputs
5 d

Related

C segmentation fault while using structures

I'm trying to write a data structure with two elements, and then defining a variable of that type struct. However, after initializing the variable in the main function, I'm getting segmentation fault and I don't know why.
#include <stdio.h>
#include <string.h>
struct AnimalSizes {
char stringName[50];
double sizeLength;
} animalSizes[2];
int main()
{
struct AnimalSizes *snakes;
strcpy(snakes[0].stringName,"Anaconda");
snakes[0].sizeLength=3.7;
strcpy(snakes[1].stringName,"Python");
snakes[1].sizeLength= 2.4;
printf("%c", *snakes[0].stringName);
printf("%lf", snakes[0].sizeLength);
printf("%c", *snakes[1].stringName);
printf("%lf", snakes[1].sizeLength);
return 0;
}
You try to strcpy to destination where is no allocated memory. That is undefined behavior.
You should first allocate enough memory to hold two AnimalSizes instances:
struct AnimalSizes *snakes;
snakes = malloc(2 * sizeof(struct AnimalSizes));
Also, here
printf("%c", snakes[0].stringName);
you are trying to output the first character of stringName. I assume, what you rather want to do is to output whole string with %s.
You've declared a pointer to a struct AnimalSizes, and you have declared an array struct AnimalSizes[2], but you have not made the pointer point to this array:
int main()
{
struct AnimalSizes *snakes = &animalSizes[0];
...
}
Alternatively, you may choose to not declare a global variable, rather choosing to allocate memory in main:
#include <stdlib.c>
#include <stdio.h>
#include <string.h>
struct AnimalSizes {
char stringName[50];
double sizeLength;
};
int main()
{
struct AnimalSizes *snakes = (struct AnimalSizes*) malloc(2*sizeof(struct AnimalSizes));
strcpy(snakes[0].stringName,"Anaconda");
snakes[0].sizeLength=3.7;
strcpy(snakes[1].stringName,"Python");
snakes[1].sizeLength= 2.4;
printf("%c", *snakes[0].stringName);
printf("%lf", snakes[0].sizeLength);
printf("%c", *snakes[1].stringName);
printf("%lf", snakes[1].sizeLength);
free(snakes);
return 0;
}
the following proposed code:
eliminates any need for malloc() and free()
performs the desired functionality
separates the definition of the struct from any instance of the struct.
inserts some spacing between the first letter of the snake name and the 'size' of the snake, for readability
applies certain other changes to the code for 'human' readability
and now the proposed code:
#include <stdio.h>
#include <string.h>
struct AnimalSizes
{
char stringName[50];
double sizeLength;
};
int main( void )
{
struct AnimalSizes snakes[2];
strcpy(snakes[0].stringName,"Anaconda");
snakes[0].sizeLength=3.7;
strcpy(snakes[1].stringName,"Python");
snakes[1].sizeLength= 2.4;
printf("%c ", snakes[0].stringName[0]);
printf("%lf\n", snakes[0].sizeLength);
printf("%c ", snakes[1].stringName[0]);
printf("%lf\n", snakes[1].sizeLength);
return 0;
}
a run of the proposed code outputs:
A 3.700000
P 2.400000

What am I doing wrong in passing a struct around in C?

So I am working on a project in C that requires that I pass pointers to a struct into functions. The project is structured as follows:
struct structName {
unsigned short thing2;
char thing1[];
};
void function_1(struct structName *s) {
strcpy(s->thing1, "Hello");
printf("Function 1\n%s\n\n", s->thing1); // prints correctly
}
void function_2(struct structName *s) {
// can read thing2's value correctly
// thing1 comes out as a series of arbitrary characters
// I'm guessing it's an address being cast to a string or something?
printf("Function 2\n%s\n\n", s->thing1); // prints arbitrary characters ('É·/¨')
}
int main() {
struct structName s;
function_1(&s);
printf("Main\n%s\n\n", s.thing1);
function_2(&s);
printf("Main 2\n%s\n\n", s.thing1);
}
This code outputs the following:
Function 1
Hello
Main
Hello
Function 2
É·/¨
Main 2
É·/¨
Obviously, the program has more than just what I've written here; this is just a simplified version; so if there's anything I should check that might be causing this let me know. In all honesty I reckon it's probably just a stupid rookie error I'm making somewhere.
[EDIT: Seems like s.thing1 is being mutated in some way in the call to function_2(), since the odd value is replicated in main() - I should point out that in my program the printf()s are located right before the function call and in the first line of the function, so there's no chance that it's being written to by anything I'm doing. I've updated the example code above to show this.]
Thanks in advance!
The structure contains a flexible member at its end, if you declare a static object with this type, the length of this member will be zero, so strcpy(s->thing1, "Hello"); will have undefined behavior.
You are supposed to allocate instances of this type of structure with enough extra space to handle whatever data you wish to store into the flexible array.
Here is an example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct pstring {
size_t length;
char data[];
} pstring;
pstring *allocate_pstring(const char *s) {
size_t length = strlen(s);
pstring *p = malloc(sizeof(*p) + length + 1);
if (p != NULL) {
p->length = length;
strcpy(p->data, s);
}
return p;
}
void free_pstring(pstring *p) {
free(p);
}
int main() {
pstring *p = allocate_pstring("Hello");
printf("Main\n%.*s\n\n", (int)p->length, p->data);
free_pstring(p);
return 0;
}

How do I print elements of structures contained in an array

I have created an array of structure as a global variable. I initialised the array in a function and I could print out the elements of the structure from there. My problem is that I can't print out values of the array in another function( main() in my case) other than the one I used to initialise the array. Please how can I print those values? Thank you.
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
typedef struct s{
char *value;
} S;
S list[2];
void function( ){
char val1[] = "val1";
char val2[] = "val2";
S v1 = {val1};
S v2 = {val2};
list[0] = v1;
list[1] = v2;
printf("%s\n", list[1].value); //prints val2
}
int main(int argc, char** argv) {
function();
printf("%s", list[1].value); //prints nonsense
return 0;
}
What I have tried :
I modified function() to take list as an argument( function (list)) and declared list in main() instead. It didn't work.
I modified function to return list (S* function()), it didn't work.
I used an array of integers ( instead of structure i.e. int list[2], declared it as a global variable and initialised it in function()) and everything worked fine, suggesting that the problem is from how I am accessing structure, but I just can't figure it out.
I searched the internet, but couldn't get a similar problem.
In your function function you assign an address of a local variable to your structure. After returning from function this address is no longer valid. You could either make it static or allocated it dynamically.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct s
{
char *value;
} S;
S list[2];
void function( )
{
char val1[] = "val1";
char val2[] = "val2";
//Note that you are creating a copy of "val1" here which can be avoided by changing it to char *val1 = "val1";
list[0].value = malloc(strlen(val1)+1); //allocate space for val1 + NUL-terminator
strcpy(list[0].value, val1); //copy string
list[1].value = malloc(strlen(val2)+1);
strcpy(list[1].value, val2);
//You could also use the function strdup which allocates memory and duplicates the string
//list[0].value = strdup(val1);
printf("%s\n", list[1].value); //prints val2
}
int main(int argc, char** argv)
{
function();
printf("%s", list[1].value);
free(list[0].value); //Don't forget to free.
free(list[1].value);
return 0;
}

Return Pointer from function

I am new in C and literally trying to return pointer from my function to the pointer variable and have this "[Warning] assignment makes pointer from integer without a cast" no idea why compiler defines it as an int.
Can't declare my function before main as well, it throws this "undefined reference to `free_block'".
#include <stdio.h>
#include <stdlib.h>
struct block{
int num;
};
int main(int argc, char *argv[]) {
struct block *b;
b = free_block();
struct block *free_block(){
struct block *b = NULL;
return b;
}
return 0;
}
Thank you
Yea, my fault I know not too much about c syntax and had no idea about nested functions, soz.
But what could be wrong in this case:
I am trying to make my own memory allocator without using malloc or calloc functions. In my code I have the same Warning on the line with pointer = free_space_get(size);, here I have no more nested func(), my methods defined before main(), but still have no idea do I have to declare my functions or no, coz in the answer given to me it worked fine as soon as functions were defined before the main().
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct header{
size_t size;
struct header *next;
unsigned int free;
};
void *m_alloc(size_t size){
size_t total_size;
void *block;
struct header *pointer;
if(!size)
return NULL;
pointer = free_space_get(size);
if(pointer){
pointer->free = 0;
return (void*)(pointer + 1);
}
}
struct header *get_free_space(size_t size){
struct header *b = NULL;
return b;
}
int main() {
return 0;
}
Your code can be re-written as
#include <stdio.h>
#include <stdlib.h>
struct block{
int num;
};
struct block *free_block(){
struct block *b = NULL;
return b;
}
int main(int argc, char *argv[]) {
struct block *b;
b = free_block();
if(b == NULL) // Checking whether pointer is returned
printf("\n Recieved NULL \n");
return 0;
}

How to use structs, pointers and a function in C?

I have learned how to use functions and structs and pointers. I want to combined them all into one. But the code that I write doesn't seem to work. The compiler tells me the test is an undeclared identifier. Here is the code:
#include <stdio.h>
#include <stdlib.h>
struct character
{
int *power;
};
void test (use_power)
int main ()
{
test (use_power)
printf("%d\n",*power);
return 0;
}
void test ()
{
int use_power = 25;
struct character a;
a.power = &use_power;
}
Your code has many mistakes it can't even compile
Multiple missing semicolons.
Implicit declaration of test() here
test (use_power)
with a missing semicolon too.
power is not declared in main().
This line
void test use_power()
does not make sense and is invalid, and also has no semicolon.
The a instance in test() defined at the end is local to test() and as such will be deallocated when test() returns. The use_power int, has exactly the same problem and trying to extract it's address from the function is useless because you can't access it after the function has returned.
I have no idea what you were trying to do, but this might be?
#include <stdio.h>
#include <stdlib.h>
struct character {
int *power;
};
/* Decalre the function here, before calling it
* or perhaps move the definition here
*/
void test(struct character *pointer);
/* ^ please */
int
main(void) /* int main() is not really a valid signature */
{
struct character instance;
test(&instance);
if (instance.power == NULL)
return -1;
printf("%d\n", *instance.power);
free(instance.power);
return 0;
}
void
test(struct character *pointer)
{
pointer->power = malloc(sizeof(*pointer->power));
if (pointer->power != NULL)
*pointer->power = 25;
}
Your code seems to be wrong. Your definition for test contains no arguments as
void test ()
{
int use_power = 25;
struct character a;
a.power = &use_power;
}
but your prototype contains one argument
void test (use_power)
which is wrongly put. First there are no semicolons; at the end of your prototype declaration, secondly by looking at your code, use_power is a variable and not a datatype so it cannot be present solely in a function declaration.
You will get an argument mismatch error.
You have used the line in main()
printf("%d\n",*power);
which is absolutely wrong. you cannot access any member of a structure without a structure variable.
And again, you have not mentioned the; after your call to the incorrect test()before this line
As you have not put your question so properly, I must figure out what you wish to achieve. I bet you want to hold the address of a integer in the pointer member of a structure and then print its value.
Below is a code snippet which will work as you desire.
#include <stdio.h>
#include <stdlib.h>
struct character
{
int *power;
};
struct character a; //define a structure variable
void test ();
int main ()
{
test ();
printf("%d\n",*(a.power)); // print the member of structure variable a
return 0;
}
void test ()
{
int use_power = 25;
a.power = &use_power;
}
example
#include <stdio.h>
struct character {
int *power;
};
void test(struct character *var);
int main (void){
struct character use_power;
int power = 5;
use_power.power = &power;
test(&use_power);
printf("%d\n", power);
return 0;
}
void test(struct character *var){
int use_power = *var->power;
*var->power = use_power * use_power;
}

Resources