We help IT Professionals succeed at work.

C pointer question

ambuli
ambuli asked
on
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

Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2009
Commented:
>>          strcpy(value, "somevalue");

You can't do that since value is a char* and doesn't point to valid memory (yet).

Did you mean :

        value = "somevalue";

Author

Commented:
Thanks.
Yes, I tried
value = "somevalue" and it crashed as well.  How can I correct it.
CERTIFIED EXPERT
Top Expert 2009

Commented:
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

CERTIFIED EXPERT
Top Expert 2009

Commented:
>> 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.
jkr
CERTIFIED EXPERT
Top Expert 2012
Commented:
Or, allocate memory:
#include <stdlib.h>
 
typedef struct{
        char *name;
}my_struct;
 
void copy_from(char *value)
{
          
          strcpy(value, "somevalue");   
}
 
void copy_another(my_struct *table)
{
        copy_from(table->name);
}
 
int main()
{
        my_struct my;
 
        my.name = (char*) malloc(255); // <---
 
        copy_another(&my);
        printf("%s", my.name );
 
        free(my.name);
        
        return 0;
}

Open in new window

Author

Commented:
Thanks a lot.  I learnt something today :-)

Explore More ContentExplore courses, solutions, and other research materials related to this topic.