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;
}
Related
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;
}
..C..
I am trying to figure out how to access my filled array which utilizes a struct with another function which I will use later for sorting, but I can't even print my function that filled the array in my main.
I have loaded the function inside main which works and printing inside the fillArray function works but I will need to access the array from outside the function later on for a bubble sort and a binary search.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define SIZE 100
typedef struct Person
{
char firstname[25];
char lastname[25];
} person;
person list [SIZE];
person loadPeople(char firstname[25],char lastname[25])
{
person p;
strcpy(p.firstname, firstname);
strcpy(p.lastname, lastname);
return p;
}
void fillArray()
{
list[0] = loadPeople("Bob","Baker");
list[1] = loadPeople("Bill","Johnson");
list[2] = loadPeople("John","Finmeister");
list[3] = loadPeople("Jennifer","Ratblaster");
list[4] = loadPeople("Shaun","Gares");
list[5] = loadPeople("Diggy","McDigMaster");
list[6] = loadPeople("Joanne","TheStore");
}
int main(int argc , char *argv[])
{
printf("First homie's name is: %s %s\n",list[0].firstname,list[0].lastname);
return 0;
}
I just want to print from main recalling from fillArray but right now it only prints:
First homie's name is:
thats it
You need to call fillArray() in order to execute it:
int main(int argc , char *argv[])
{
fillArray();
printf("First homie's name is: %s %s\n",list[0].firstname,list[0].lastname);
return 0;
}
Note that main() should only have two parameters as shown here.
I'm fully prepared to be told that I'm doing something stupid/wrong; this is what I expect.
I'm getting a feel for structures and coming a cropper when it comes to accessing the fields from the pointers. Code to follow.
matrix.h:
#ifndef MATRIX_H_INCLUDED
#define MATRIX_H_INCLUDED
#include <stdlib.h>
typedef struct
{
size_t size;
int* vector;
} vector_t;
#endif // MATRIX_H_INCLUDED
main.c:
#include <stdio.h>
#include <stdlib.h>
#include "matrix.h"
vector_t* vector_new(size_t size)
{
int vector[size];
vector_t v;
v.size = size;
v.vector = vector;
return &v;
}
int main(int argc, char* argv[])
{
vector_t* vec = vector_new(3);
printf("v has size %d.\n", vec->size);
printf("v has size %d.\n", vec->size);
return EXIT_SUCCESS;
}
So this is a very simple program where I create a vector structure of size 3, return the pointer to the structure and then print its size. This, on the first print instance is 3 which then changes to 2686668 on the next print. What is going on?
Thanks in advance.
You are returning a pointer to a local variable v from vector_new. This does not have a slightest chance to work. By the time vector_new returns to main, all local variables are destroyed and your pointer points to nowhere. Moreover, the memory v.vector points to is also a local array vector. It is also destroyed when vector_new returns.
This is why you see garbage printed by your printf.
Your code has to be completely redesigned with regard to memory management. The actual array has to be allocated dynamically, using malloc. The vector_t object itself might be allocated dynamically or might be declared as a local variable in main and passed to vector_new for initialization. (Which approach you want to follow is up to you).
For example, if we decide to do everything using dynamic allocation, then it might look as follows
vector_t* vector_new(size_t size)
{
vector_t* v = malloc(sizeof *v);
v->size = size;
v->vector = malloc(v->size * sizeof *v->vector);
return v;
}
(and don't forget to check that malloc succeeded).
However, everything that we allocated dynamically we have to deallocate later using free. So, you will have to write a vector_free function for that purpose.
Complete re-write of answer to address your question, and to provide alternate approach:
The code as written in OP will not compile: &v is an illegal return value.
If I modify your code as such:
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
size_t size;
int* vector;
} vector_t;
vector_t* vector_new(size_t size)
{
int vector[size];
vector_t v, *pV;
pV = &v;
pV->size = size;
pV->vector = vector;
return pV;
}
int main(int argc, char* argv[])
{
vector_t* vec = vector_new(3);
printf("v has size %d.\n", vec->size);
printf("v has size %d.\n", vec->size);
getchar();
return EXIT_SUCCESS;
}
It builds and runs, but returns unintended values for vec->size in main() due to the local scope of that variable in the function vector_new.
Recommend creating globally visible instance of your struct, and redefine vector_new() to int initVector(void):
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
typedef struct
{
size_t size;
int* vector;
} vector_t;
vector_t v, *pV;//globally visible instance of struct
int initVector(void)
{
int i;
pV->size = SIZE;
pV->vector = calloc(SIZE, sizeof(int));
if(!pV->vector) return -1;
for(i=0;i<SIZE;i++)
{
pV->vector[i] = i;
}
return 0;
}
int main(int argc, char* argv[])
{
int i;
pV = &v; //initialize instance of struct
if(initVector() == 0)
{
printf("pV->size has size %d.\n", pV->size);
for(i=0;i<SIZE;i++) printf("pV->vector[%d] == %d.\n", i, pV->vector[i]);
}
getchar(); //to pause execution
return EXIT_SUCCESS;
}
Yields these results:
You still need to write a freeVector function to undo all the allocated memory.
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
I want to create a static array of string in a function , then the return value of this function will assign to another array of string .
but it seems I can't do this assignment array2 = function(); but I think use char * for array of string is ok?
what's wrong in my code?
thanks
here is my code
#include <stdio.h>
#include <stdlib.h>
char * function();
int main(){
char * array2[100] = {};
array2 = function();
// print this array of string
int i;
for(i=0;i<strlen(array2);i++){
printf("%s\n",array2[i]);
}
system("pause");
}
char * function(){
static char * array[100] = {};
array[0] = "100";
array[1] = "200";
return array;
}
You should use char** or char* array[] for array of strings.
In your function(), array is the first address of array of char*.the prototype should be char **function().
And I don't think array's name can be changed.Say int a[3], b[3];, a is a constant, So a = b is not allowed.
Be careful about the spelling mistakes like funtion() function().
I'd do something like this:
#include <stdio.h>
#include <stdlib.h>
static char **function(void)
{
char **array = malloc(2 * sizeof(*array));
array[0] = "100";
array[1] = "200";
return array;
}
int main(int argc, char *argv[])
{
char **array2;
array2 = function();
/* print this array of string */
int i;
for (i = 0; i < 2; i++)
printf("%s\n",array2[i]);
free(array2);
return 0;
}
There are many ways to solve your problem. It seems to be similar to these questions [general arrays][1]
[String arrays][2]
Or you can pass the array instead and get it working like this
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include "string.h"
using namespace std;
void function(char *input[100]){
input[0] = "100";
input[1] = "200";
}
int main(){
char * array2[100];
function(array2);
// print this array of string (int)strlen(*array2)
int i;
for(i=0;i<(int)strlen(*array2) - 1;i++){
printf("%s\n",array2[i]);
}
system("pause");
}