String Constants in C Language

String constants have double quote marks around them and can be assigned to char pointers.

Alternatively, you can assign a string constant to a char array either with no size specified, or you can specify a size, but don’t forget to leave a space for the null character!

Suppose you create the following two code fragments and run them:

/* Fragment 1 */
{
char *s;
s=hello”;
printf(“%s\n”,s);
}
/* Fragment 2 */
{
char s[100];
strcpy(s, “ hello”);
printf(“%s\n”,s);
}

These two fragments produce the same output, but their internal behavior is quite different.

In fragment 2, you cannot say s = hello;

To understand the differences, you have to understand how the string constant table works in C. When your program is compiled, the compiler forms the object code file, which contains your machine code and a table of all the string constants declared in the program.

In fragment 1, the statement s = hello; causes s to point to the address of the string hello in the string constant table.

Since this string is in the string constant table, and therefore technically a part of the executable code, you cannot modify it. You can only point to it and use it in a read-only manner.

In fragment 2, the string hello also exists in the constant table, so you can copy it into the array of characters named s. Since s is not an address, the statement s=hello; will not work in fragment 2. It will not even compile.

Write a program to read a name from the keyboard and display message Hello onto the monitor

/*Program that reads the name and display the hello along with your name*/
#include <stdio.h>
main()
{
char name[10];
printf(“\nEnter Your Name : “);
scanf(“%s”, name);
printf(“Hello %s\n”, name);
}

OUTPUT

Enter Your Name : kelly

Hello kelly

In the above example, declaration char name [10] allocates 10 bytes of memory space (on 16 bit computing) to array name [ ].

We are passing the base address to scanf function and scanf() function fills the characters typed at the keyboard into array until enter is pressed.

The scanf() places ‘\0’ into array at the end of the input.

The printf()function prints the characters from the array on to monitor, leaving the end of the string ‘\0’.

The %s used in the scanf() and printf() functions is a format specification for strings.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: