Link to home
Start Free TrialLog in
Avatar of ambuli
ambuliFlag for United States of America

asked on

C pointer question

Hi there,

The following small code crashes when executing.  What is
typedef struct{
	char *name;
}my_struct;
 
void copy_from(char *value)
{
          //value = "somevalue";  I tried this one with the same problem
          strcpy(value, "somevalue");	
}
 
void copy_another(my_struct *table)
{
	copy_from(table->name);
}
 
int main()
{
	my_struct my;
 
	copy_another(&my);
	printf("%s", my.name );
	
	return 0;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ambuli

ASKER

Thanks.
Yes, I tried
value = "somevalue" and it crashed as well.  How can I correct it.
Alternatives are :

1) use an array instead of a pointer :

        typedef struct{
                char name[16];
        } my_struct;

    The disadvantage is that there is a maximum size for the name field (and you have to always keep that in mind so you never write past the end of the buffer).


2) allocate some memory for the pointer :

        my_struct my;
        my.name = (char*) calloc(16, sizeof(char));
        copy_another(&my);
        printf("%s", my.name );

    The advantage here is that you can dynamically size the name field.


3) duplicate the string (assuming that strdup is available on your system - otherwise you'll have to implement it) :


typedef struct{
        char *name;
}my_struct;
 
void copy_another(my_struct *table)
{
        table->name = strdup("somevalue");   
}
 
int main()
{
        my_struct my;
 
        copy_another(&my);
        printf("%s", my.name );
        
        return 0;
}

Open in new window

>> value = "somevalue" and it crashed as well.

Yes, you can't put it in the copy_from method, since it works on a local copy of the pointer. I should have said that explicitly.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ambuli

ASKER

Thanks a lot.  I learnt something today :-)