TopBottom

Followers



Click on more
SUBSCRIBE

Enter your email address:

Delivered by FeedBurner



VIDEO

Announcement: wanna exchange links? contact me at ravikrak@yahoo.com

Pointers And Strings

Posted by Ravi Kumar at Sunday, September 25, 2011
Share this post:
Ma.gnolia DiggIt! Del.icio.us Yahoo Furl Technorati Reddit

We cannot assign a string to another,whereas we can assign
a char pointer to another char pointer. This is shown with an
example:

main()
{
char str1[]="hello";
char str2[10];
char *s="good morning";
char *q;
str2=str1;/*error*/
q=s;/*works*/
}
Also,once a string has been defined it cannot be initialized
to another set of characters.Unlike strings, such an operation
is perfectly valid with char pointers.

Example:

main()
{
char str1[]="hello";
char *="hello";
str1="bye";/*error*/
p="bye";/*works*/
}
THE const QUALIFIER:
The keyword const, if present, precedes the data type of a
variable. It specifies that the value of the variable will not
change throughout the program. Any attempt to vary the value
of variable will result into an error message from compiler.
const is usually used to replace # define d constants.

Example:

main()
{
float r,a;
const float,PI=3.14;
printf("\n Enter radius:");
scanf("%f",&r);
a=PI*r*r;
printf("Area=%f",a);
}

If a const is placed inside a function its effect would
be localised to that function,whereas if it is placed outside
all functions then its effect would be global.

RETURNING const VALUES:
A function can return a pointer to a constant string as
shown Example:

main()
{
const char *fun();
const char *p;
p=fun();
p='A';/error*/
printf("\n%s",p);
}
const char * fun()
{
return "Rain()";
}
Since the function fun() is returning a constant string we
cannot use the pointer p to modify it. The following
operations too would be invalid:

(a)main() cannot assign the return value to a pointer to a
non-const string.
(b)main() cannot pass the return value to a function that is
expecting a pointer to a non-const string.

Share |

Labels:

0 comments:

Post a Comment