Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In C, there is nothing stopping you from casting this struct to a char* and treating it like a string. </p> <p>Having said that however, you are going to have to be careful how you treat this "string". Consider the following example:</p> <pre><code>typedef struct format{ char R[12]; char M[15]; } format; void main(){ format A; int i; strcpy(A.R,"AA"); strcpy(A.M,"AABBCC"); char *B=(char*)&amp;A; //Note the typecasting printf("%s",B); for (i=0;i&lt;strlen(B);i++){ printf("%d\n",*(B+i)); } } </code></pre> <p>The example above is not going to work as expected, i.e. it is not going to iterate over all the characters within A because strings in C are null terminated (http://en.wikipedia.org/wiki/Null-terminated_string) and this is how various functions (strlen, strcpy and others) know that they have reached the end of a stream of chars. So, the above code will output "AA" and [65,65] (which is the asci equivalent of "A").</p> <p>For the above piece of code to do what it is expected to do, we would have to EITHER:</p> <p>1) Remove all "\0" (null) characters from A EXCEPT the last one, prior to treating it as a string (and feeding it to other functions like printf for example)</p> <p>2) Or, if we want to maintain all individual fields as strings and still parse it, we would now have to use sizeof(format) (or sizeof(A)) instead of strlen(B) in the "for" iteration above.</p> <p>So, yes you can typecast a struct of chars to a (char *) and treat it like a string but there's a bit of preprocessing you are going to have to do for this to work as expected. You could for example have a function that implements the removal of "\0"s as in (1) above, called something like "structToString".</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload