Code:
test{
int no
char * name ;
}
i don't think this will work.
Try
Code:
typedef struct {
int no;
char * name ;
} test;
then
Code:
main()
{
struct test ptr; <- omit struct, just use test ptr
/* Also ptr in the above line is not a pointer, it's not an error, u may use whatever name you
want, but it's not very good to use the name ptr for something that is not a pointer.*/
/*here i do memeset to initialize all the variables of structureto zero*/
or simply do:
ptr.no=0;
ptr.name=NULL;
/* if you are going to set those values later, no need to zero them, or initialize*/
funciton1(&ptr); <- u pass the adress of ptr to function1, that's OK
}
Code:
fucntion1(char *ptr) <- this may work but why cast a struct pointer to a char pointer?????
define fucntion1(test *ptr) better
{
/*some operations here this fucntion further call the a fucntion2*/
function2(ptr);
}
And now your real problem:
Code:
fucntion2(char *var)
{
var->no =100; <- that's OK with me
vat->name?????
}
in the struct you have defined a pointer to point to a character or an array of characters (string);
You haven't allocated any space for the string the pointer points.
You may do that in two ways, static or dynamic.
STATIC
Code:
test{
int no
char name[100] ; <- allocate space for 100 characters static in compilation
}
the space will be allocated when you do
test ptr; <- for example in main when you define ptr;
and don't do ptr.name=NULL;, you will lose the allocated space
DYNAMIC
Code:
fucntion2(char *var){
var->no =100;
var->name = (char *)malloc(100*sizeof(char)); <- allocate space for 100 characters dynamic in execution
}
then use strcpy or better strncpy to fill the name for both ways
strncpy(var->name,"John",99); I think strncpy does not count '\0', but i'm not sure
if u use malloc, don't forget to free the allocated space when you don't need it any more.
free( var->name);
or free(var.name); if you are in main.
malloc needs stdlib.h (#include <stdlib.h>)
strncpy needs string.h
do
man malloc
man strncpy
for more info