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);
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.
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.
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 (").
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With