Community
cancel
Showing results for 
Search instead for 
Did you mean: 
Highlighted
New Contributor III
46 Views

The necessity of passing string length from C to Fortran or vice vera

Jump to solution

Since C strings are NUL terminated, is there a necessity or preference to pass the length of a string along with the string to a Fortran routine? Are C strings always NUL terminated according to the C standard? Do all C compilers follow this rule and add the same NUL character to the end the C strings?

0 Kudos

Accepted Solutions
Highlighted
Black Belt
46 Views

The C standard defines the term string to be a sequence of terminated by a null character.  Literal strings in C always end up with an in-memory representation that has a trailing null.  The null character in the basic execution character set has to be a byte with all bits zero, or of value zero in other character sets, that practically means that the null is the same "zeroth" character.  C standard library functions that deal with strings follow the convention for literals, and require and typically (exceptions exist) produce null terminated strings.  Third party written C functions also typically follow the convention.

But whether you pass the length to Fortran or deal in Fortran with null terminated strings depends on the nature and requirements of your Fortran code - it is not a necessity.  If you pass a string from Fortran to C, a null often needs to be added along the way if the C code requires it.

Often I prefer to have the string length passed separately, but not always.

 

View solution in original post

1 Reply
Highlighted
Black Belt
47 Views

The C standard defines the term string to be a sequence of terminated by a null character.  Literal strings in C always end up with an in-memory representation that has a trailing null.  The null character in the basic execution character set has to be a byte with all bits zero, or of value zero in other character sets, that practically means that the null is the same "zeroth" character.  C standard library functions that deal with strings follow the convention for literals, and require and typically (exceptions exist) produce null terminated strings.  Third party written C functions also typically follow the convention.

But whether you pass the length to Fortran or deal in Fortran with null terminated strings depends on the nature and requirements of your Fortran code - it is not a necessity.  If you pass a string from Fortran to C, a null often needs to be added along the way if the C code requires it.

Often I prefer to have the string length passed separately, but not always.

 

View solution in original post