Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C inserting string into char pointer

Tags:

c

string

Hi all I trying to assign string into a char * pointer. Below is how I am doing but I am getting this warning: assignment makes integer from pointer without a cast.

What is the correct why to deal with strings in C ?

char* protoName = "";

if(h->extended_hdr.parsed_pkt.l3_proto==0)
    *protoName = "HOPOPT";  
else if(h->extended_hdr.parsed_pkt.l3_proto==1)
    *protoName = "ICMP";    
else if(h->extended_hdr.parsed_pkt.l3_proto==2)
    *protoName = "IGMP";    
else if(h->extended_hdr.parsed_pkt.l3_proto==3)
    *protoName = "IGMP";    
else if(h->extended_hdr.parsed_pkt.l3_proto==4)
    *protoName = "IGMP";

char all[500];

sprintf(all,"IPv4','%s'",* protoName);
like image 331
user2711681 Avatar asked Aug 28 '13 15:08

user2711681


People also ask

How do I assign a string to a char pointer?

To store the string in a pointer variable, we need to create a char type variable and use the asterisk * operator to tell the compiler the variable is a pointer.

Is char * A string in C?

This last part of the definition is important: all C-strings are char arrays, but not all char arrays are c-strings. C-strings of this form are called “string literals“: const char * str = "This is a string literal.

Is char * a string?

char is a primitive data type whereas String is a class in java. char represents a single character whereas String can have zero or more characters. So String is an array of chars. We define char in java program using single quote (') whereas we can define String in Java using double quotes (").


1 Answers

If you just want to change which string literal protoName points to, you just need to change

*protoName = "HOPOPT";

to

protoName = "HOPOPT";

*protoName = attempts to write to the first character pointed to by protoName. This won't work in your case as protoName points to a string literal which cannot be modified.

You also need to change your sprintf call to

sprintf(all,"IPv4','%s'", protoName);

The %s format specifier signals that you'll be passing a pointer to a nul-terminated char array. *protoName gives you the character code of the first character pointed to by protoName; sprintf doesn't know this so would treat that character code as the address of the array to read from. You don't own this memory so the effects of reading from it would be undefined; a crash would be likely.

As an aside, if you had a writeable char array and wanted to change its contents, you'd need to use strcpy to copy a new array of chars into it.

like image 56
simonc Avatar answered Sep 30 '22 00:09

simonc