in Programming in C edited by
1,530 views
1 vote
1 vote
main()
{
    char *p1="name";
    char *p2;
    p2=(char*)malloc(20);
    memset(p2,0,20);
    while(*p2++=*p1++);
    printf("%s\n",p2);
}
in Programming in C edited by
1.5k views

2 Comments

@akash, wat issues u have with dis code?
0
0
i can't able to crack the logic of method memset . help me
0
0

2 Answers

1 vote
1 vote
Best answer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
	char *p1="name";
	char *p2;
	p2=(char*)malloc(20);
	memset(p2,0,20);
	
	char *temp = p2; // add this line of code
	                 // which stores the pointer location returned by malloc 
	while(*p2++=*p1++); // copy string content pointed by p1 to p2
	                    // in this process both p1 and p2 gets incremented
	printf("%s\n",temp);// temp still pointing to the start 
	                    // of newly created string 
}
selected by
by

4 Comments

memset line isnot required here .rt?
0
0
it Set 0 every place so yes not neccesory.
0
0
means?
0
0

memset works as Calloc() i.e. clear the memory. Memory previously allocated to some variable so it can contain some garbage value so memset will clear memory by setting Zero every place.

1
1
1 vote
1 vote

Improved Code:

Compiler DOS Box. 

#include<stdio.h>

#include<stdlib.h>

#include<conio.h>

#include<string.h>

void main()

{

  char *p1="name";

char *p2;

clrscr();

p2=(char *) malloc(20);

memset(p2,0,20);

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

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

getch();

}

edited by

4 Comments

calloc() allocates the memory and also initializes the allocates memory to zero.

void * calloc( size_t num, size_t size );

calloc() takes two arguments: 1) number of blocks to be allocated 2) size of each block.

so We can achieve same functionality as calloc() by using malloc() followed by memset(),

ptr = malloc(size);

memset(ptr, 0, size);

refer: http://www.geeksforgeeks.org/calloc-versus-malloc/

0
0
0
0
Even without memset it is giving same output. :)
0
0

Related questions