C Tutorial Pointer style and strcpy()
Advanced C Arrays
Plus Syntax
Pointer Style and strcpy()

Pointer Type Effects
Arrays and Pointers
Array Names Are Const
Heap Memory
Memory Management
Dynamic Arrays
Advantages of being in the heap
Disadvantages of being in the heap
Dynamic Strings
 
 

 

HOME
 

Pointer++ Style -- strcpy()

If p is a pointer to an element in an array, then (p+1) points to the next element in the array. Code can exploit this using the construct p++ to step a pointer over the elements in

an array. It doesn't help readability any, so I can't recommend the technique, but you may see it in code written by others.

 

(This example was originally inspired by Mike Cleron) There's a library function called strcpy(char* destination, char* source) which copies the bytes of a C string from one place to another. Below are four different implementations of strcpy() written in order: from most verbose to most cryptic. In the first one, the normally straightforward while loop is actually sortof tricky to ensure that the terminating null character is copied over. The second removes that trickiness by moving assignment into

the test. The last two are cute (and they demonstrate using ++ on pointers), but not really the sort of code you want to maintain. Among the four, I think strcpy2() is the best stylistically. With a smart compiler, all four will compile to basically the same code with the same efficiency.

 

// Unfortunately, a straight while or for loop won't work.

// The best we can do is use a while (1) with the test

// in the middle of the loop.

void strcpy1(char dest[], const char source[]) {

int i = 0;

 

while (1) {

dest[i] = source[i];

if (dest[i] == '\0') break;      // we're done

i++;

}

}

 

 

// Move the assignment into the test

void strcpy2(char dest[], const char source[]) {

int i = 0;

 

while ((dest[i] = source[i]) != '\0') {

i++;

}

}

 

 

// Get rid of i and just move the pointers.

// Relies on the precedence of * and ++.

void strcpy3(char dest[], const char source[])

{

while ((*dest++ = *source++) != '\0') ;

}

 

 

// Rely on the fact that '\0' is equivalent to FALSE

void strcpy4(char dest[], const char source[])

{

while (*dest++ = *source++) ;

}

 want To Know more with

Video ???

Contact for more learning: webmaster@freehost7com