Pages

Wednesday, December 14, 2011

A simple C program

Let's talk about simplicity. And let's look at a simple C program today. Why not, every day we deal with complex problem, so let's talk about a simple C program now. Here is the program;

main()

{

    char *p1="name";

    char *p2;

    p2=(char*)malloc(20);

    memset (p2, 0, 20);

    while(*p2++ = *p1++);

    printf("%s\n", p2);

}

Well, what does this program do. This is the topic of today's blog.

Ans:

Looks like this program output's the string name , but that's not true.

What do you think about this program?

Write your comments about it.

6 comments:

Amber said...

It will syntax error the hell out because you left a stray malformed <p> tag in.

Also, you clearly intended it to copy the input string into p2.

Unknown said...

I have fixed that dangling /p> tag. So, now does it sounds good?

Pradeep Gopanapalli said...

Output will be NULL
small correction will print name

char *p1="name";
char *p2,*p3;
p2=(char*)malloc(20); memset (p2, 0, 20);
p3 = p2;
while(*p3++ = *p1++);
printf("%s\n", p2);

Pradeep Gopanapalli said...

Output will be null, small change will print name

char *p1="name";
char *p2,*p3;
p2=(char*)malloc(20);
memset (p2, 0, 20);
p3 = p2;
while(*p3++ = *p1++);

Anonymous said...

Look more easy way to solve a problem in C language
http://cproblem.blogspot.com
my other blog:
http://findipodtouch.com

Krupa said...

Well, p2 is getting incremented all the way and is pointing where "name" ends and all null characters with which it had been initilized to.