|
|
|
Example: the string "Hello" is represented as follows:
|
Note:
|
%s conversion character in printf for a string
|
int main(int argc, char *argv[])
{
printf("Print the string `%s' here\n", "Hello" );
}
|
Result:
Print the string `Hello' here |
How to run the program:
|
|
int main(int argc, char *argv[])
{
char a[10] = { 'H', 'e', 'l', 'l', 'o', '\0' } ; // String variable
// Don't forget the sentinel '\0'
// that ends the string !
printf( "sizeof(a) = %d\n", sizeof(a) );
printf( "String a = %s\n", &a[0] ); // Print string starting at a[0]
printf( "Strange string: %s\n", &a[3] ); // Print string starting at a[3]
}
|
Output:
sizeof(a) = 10 String a = Hello Strange string: lo |
Explanation:
The string in array a[] is as follows:
a[0] a[3] a[5]
+---+---+---+---+---+---+---+---+---+---+
| H | e | l | l | o | \0| ? | ? | ? | ? |
+---+---+---+---+---+---+---+---+---+---+
|
Note:
|
How to run the program:
|
char a[10] = "Hello";
|
char a[] = "Hello";
|
int main(int argc, char *argv[])
{
char a[10] = "Hello";
printf( "sizeof(a) = %d\n", sizeof(a) );
printf( "String a = %s\n", &a[0] );
printf( "Strange string: %s\n", &a[3] );
}
|
How to run the program:
|
|
Reason:
|
#include <stdio.h>
void print1( char x[] ) // Normal way to express array of string
{
printf( "print1: string x = %s\n", x);
}
void print2( char *x ) // Alternate way to express array of string
{
printf( "print2: string x = %s\n", x);
}
int main(int argc, char *argv[])
{
char a[10] = "Hello"; // String
print1( a );
print2( a );
}
|
How to run the program:
|
"......."
|
|
|
Example:
|
|
|
(The fact that this char typed variable is the first one in a serie (= array) does not void the fact that it is a char typed variable)
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("%lu\n", "Hello"); // Show me the address
printf("%s\n", (char *)(4195964) ); // Use the address to print the string
printf("%s\n", (char *)(4195965) );
}
|
How to run the program:
|
Output:
4195964 Hello ello |
|