Sunday, July 27, 2014

Technique on programming

Technique 1 :
Length of the string without loop and without recursion (only using printf and gets)

#include <stdio.h>
int main()
{
     char str[100];
     printf("Enter a string: ");
     printf( "\rLength is: %d",
              printf("Entered string is: %s\n", gets(str)) - 20
           );
     return 0;
}
Output:
Enter a string: GeeksforGeeks
Entered string is: GeeksforGeeks
Length is: 13
The idea is to use return values of printf() and gets().
gets() returns the entered string length.
printf() returns the number of characters successfully written on output.

Source:  http://www.geeksforgeeks.org/find-length-string-without-strlen-loop/


technique 2:

  1. to get the long line with spcae, you can only use gets(string name). scanf will not help
  2. to compare the space of the string you can use if(str[index] == 32). since the 32 is the ASCII value for the 32. refer ASCII table at http://www.asciitable.com/

Example:

SELVATHA-M-V0HE:test selvatha$ more scan.c 
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
        char name1[100]={0};
        char name2[100]={0};
        printf("\n================================ \n");
        printf("\n Scanning using scanf without space");
        printf("\n================================ \n");
        printf("\n enter the name1\t:");
        scanf("%s",name1);
        printf("\n string is \t:%s\n",name1);
        printf("\n================================ \n");
        printf("\n Scanning using gets with space");
        printf("\n================================ \n");
        printf("\n enter the name2\t:");
        gets(name2);
        printf("\n string is \t:%s\n",name2);
        return 0;
}
SELVATHA-M-V0HE:test selvatha$ ./a.out 

================================ 

 Scanning using scanf without space
================================ 

 enter the name1	:selva kumar hi 

 string is 	:selva

================================ 

 Scanning using gets with space
================================ 

warning: this program uses gets(), which is unsafe.  ---> 
---> program terminated as it wont allow us to use the gets which create a buffer
overflow. this output is waste. 
 enter the name2	:
 string is 	: kumar hi

Awareness:

A1. strcpy will do null termination :-)
       but strncpy will not do null termination :-(


stcpy:

The strcpy() function copies the string pointed to by src, including
       the terminating null byte ('\0'), to the buffer pointed to by dest
 
stncpy:
       The strncpy() function is similar, except that at most n bytes of src
       are copied.  Warning: If there is no null byte among the first n
       bytes of src, the string placed in dest will not be null-terminated.


A simple implementation of strncpy() might be:

           char *
           strncpy(char *dest, const char *src, size_t n)
           {
               size_t i;

               for (i = 0; i < n && src[i] != '\0'; i++)
                   dest[i] = src[i];
               for ( ; i < n; i++)
                   dest[i] = '\0';

               return dest;
           }

source: http://man7.org/linux/man-pages/man3/strncpy.3.html

But what strcpy will do if the source string dont have a room for the null termination:

 selvatha$ more test.c

#include<stdio.h>
#include<string.h>
int main() {
        char name[7];
        strcpy(name,"1234567");
        printf("\n %s \n",name);
        return 0;
}

SELVATHA-M-V0HE:Unused Desktop selvatha$ gcc test.c
SELVATHA-M-V0HE:Unused Desktop selvatha$ ./a.out
Abort trap: 6

After giving the space for NULL termination:



#include<stdio.h>
#include<string.h>
int main() {
        char name[7];
        strcpy(name,"1234567");
        printf("\n %s \n",name);
        return 0;
}

SELVATHA-M-V0HE:Unused Desktop selvatha$ gcc test.c
SELVATHA-M-V0HE:Unused Desktop selvatha$ ./a.out

 123456

strchr:


This returns a pointer to the first occurrence of the character c in the string str, or NULL if the character is not found.

Example:

The following example shows the usage of strchr() function.
#include <stdio.h>
#include <string.h>

int main ()
{
   const char str[] = "http://www.tutorialspoint.com";
   const char ch = '.';
   char *ret;

   ret = strchr(str, ch);

   printf("String after |%c| is - |%s|\n", ch, ret);
   
   return(0);
}
Let us compile and run the above program, this will produce the following result:
String after |.| is - |.tutorialspoint.com|


source: www.tutorialspoint.com/c_standard_library/c_function_strchr.htm

sprintf

char *itoa(int n)
 {
 char *retbuf = malloc(25);
 if(retbuf == NULL)
  return NULL;
 sprintf(retbuf, "%d", n);
 return retbuf;
 }
source: http://www.eskimo.com/~scs/cclass/int/sx5.html 

tech2:

%u used for printing the &var
%d itself used for sizeof() operator

tech3:
expr1 << expr2 == expr1 *  2expr2
10 * 32       ==  10 << 5 (becuase 32 = 25)
expr1 >> expr2 == expr1 /  2expr2 

40 / 4                     == 40 >> 2      (becuase 4 = 22)

tech 3:

pointer array to store the character data array


  • char name[max][size]  == char *ptr[ ]  (so char *ptr[ ] can be used to rx datat array in the funcion)
  •  char *ptr[] == char **ptr (so char **ptr can be used to rx char *ptr[ ]in the funcion)
  • so i guess char name[max][size] also can be received via char ** in the function call


example:
http://www.netospgm.blogspot.in/2014/08/pointer-array-and-its-advantage.html
http://publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=%2Fcom.ibm.vacpp6m.doc%2Flanguage%2Fref%2Fclrc03example_prog_pointers.htm


tech 4:


  • to print the address use %x or %p 

example:


#include <stdio.h>

int main ()
{
   int  var = 20;   /* actual variable declaration */
   int  *ip;        /* pointer variable declaration */

   ip = &var;  /* store address of var in pointer variable*/

   printf("Address of var variable: %x\n", &var  );

   /* address stored in pointer variable */
   printf("Address stored in ip variable: %x\n", ip );

   /* access the value using the pointer */
   printf("Value of *ip variable: %d\n", *ip );

   return 0;
}

tech 5:



   
b & 0xff gets the last byte of b


root@selvakumar-Lenovo-B460e:/C_pgms/memory# cat last_byte.c #include<stdio.h> /* program to mask last one byte of the given number*/ int main() { short a=0x0101; // two byte integer in hex format short b; printf("\n%d\n",a); b = a & 0xff; // this mask last 1 byte printf("\n%d\n",b); return 0; } root@selvakumar-Lenovo-B460e:/C_pgms/memory# gcc last_byte.c root@selvakumar-Lenovo-B460e:/C_pgms/memory# ./a.out 257 1 root@selvakumar-Lenovo-B460e:/C_pgms/memory#






tech 6;

size of void * and char * is 4

http://www.netospgm.blogspot.in/2014/08/sizeof-void-char.html

tech 7: how do memset on string array:

void *memset(void *str, int c, size_t n)

#include <stdio.h>
#include <string.h>

int main ()
{
   char str[50];

   strcpy(str,"This is string.h library function");
   puts(str);

   memset(str,'$',7);
   puts(str);
   
   return(0);
}
This is string.h library function
$$$$$$$ string.h library function
Refer:https://www.tutorialspoint.com/c_standard_library/c_function_memset.htm



Techniqure 8:

To define a function as static, the static keyword has to be included in the signature of the function. It does not matter in which position the keyword is mentioned, it can be inserted before or after the return type and other optional keywords, but must be inserted before the function name


so "static void test()" 
or "void static test()".
 both are same. but static keyword should be before function name

Reference: https://wr.informatik.uni-hamburg.de/_media/teaching/wintersemester_2013_2014/epc-1314-fasselt-c-keywords-report.pdf

Technique 9:

- int a[10] we can assingn to int *p as p=a . as like normal single interger variable
- we can access the arrary variable using pointer with index operator as p[i]. see second example. so in the function we can receive the array using pointer variable and access that poiter inside function using index operator.
- or we can access the array using pointer as *(p+i)

#include <stdio.h>
int main ()  
{    int i;   
        int AR [] = { 10, 20, 30, 40, 50 };
        int *pAR = AR;    
        clrscr();
        printf("\nAR = %p\t &AR[0] = %p\t pAR = %p\n",AR,&AR[0],pAR);
        for (i=0;i<5;i++)      
                printf("*pAR = %d\t AR[%d] = %d\n",*pAR++, i, AR[i]);
        return 0;
}


int *pAR &AR[0];
The values of elements of the array AR [4] may be obtained from its pointer pAR in the following manner:
* pAR = 10
*(pAR+l)= 20
*(pAR+2)= 30
*(pAR+3)= 40

[tselva@bng-junos-d037 /b/tselva/bcopy/bk_copy_needed/copy-needed/work_tips_dir/sample_c_program]$ cat array_pointer.c
#include <stdio.h>
int main ()
{
  int i;
  int AR [] = { 10, 20, 30, 40, 50 };
  int *pAR = AR;
  printf("\nAR = %p\t &AR[0] = %p\t pAR = %p\n",AR,&AR[0],pAR);

  for (i=0;i<5;i++)
    printf("pAR[%d]=%d\n",i,pAR[i]);
  for (i=0;i<5;i++)
    printf("*pAR = %d\t AR[%d] = %d \n",*pAR++, i, AR[i]);
    return 0;
}
[tselva@bng-junos-d037 /b/tselva/bcopy/bk_copy_needed/copy-needed/work_tips_dir/sample_c_program]$ ./a.out

AR = 0xffffc838 &AR[0] = 0xffffc838 pAR = 0xffffc838
pAR[0]=10
pAR[1]=20
pAR[2]=30
pAR[3]=40
pAR[4]=50
*pAR = 10 AR[0] = 10
*pAR = 20 AR[1] = 20
*pAR = 30 AR[2] = 30
*pAR = 40 AR[3] = 40
*pAR = 50 AR[4] = 50

Ref: http://ecomputernotes.com/what-is-c/function-a-pointer/one-dimensional-array-with-pointer

Technique 10: character array

http://control.ucsd.edu/mauricio/courses/mae9/lectures/lecture5.pdf

Technique 11: sizeof vs strlen:


/* 
 * sizeof_vs_strlen.c -- program shows difference between using sizeof and
 * strlen with array and string
 */
#include <stdio.h>
#include <string.h>
 
int main(void)
{
    char msg[] = {'c','h','r','i','s','t','o','p','h','e','r'};
                                 /* Character array */ 
    char name1[] = "christopher";       /* character array */
    char *name2 = "christopher";        /* string literal */
 
    printf("sizeof: size of char array msg[] \"%s\" is %d bytes!\n",
           msg, sizeof(msg));
    printf("strlen: size of char array msg[] \"%s\" is %d bytes!\n",
           msg, strlen(msg)); 
 
    printf("sizeof: size of char array name1[] \"%s\" is %d bytes!\n",
           name1, sizeof(name1));
    printf("strlen: size of char array name1[] \"%s\" is %d bytes!\n",
           name1, strlen(name1));
 
    printf("sizeof: size of string \"%s\" is %d bytes!\n",
           name2, sizeof(name2));
    printf("strlen: size of string \"%s\" is %d bytes!\n",
           name2, strlen(name2));
 
    return 0;
}
Output follows:
sizeof: size of char array msg[] "christopher" is 11 bytes!
strlen: size of char array msg[] "christopher" is 11 bytes!
sizeof: size of char array name1[] "christopher" is 12 bytes! 
strlen: size of char array name1[] "christopher" is 11 bytes!
sizeof: size of string "christopher" is 8 bytes!
strlen: size of string "christopher" is 11 bytes!
Ref: http://www.sanfoundry.com/c-tutorials-size-array-using-sizeof-operator-strlen-function/

Technique 12:
This will not work:
char *myfunc1()
{
char temp[] = "string";
return temp;
}


char *myfunc2()
{
char temp[] = {'s', 't', 'r', 'i', 'n', 'g', '\0'};
return temp;
}


int main()
{
puts(myfunc1());
puts(myfunc2());
}




The returned pointer should be to a static buffer (like static char buffer[20];), or to a buffer passed in by the caller function, or to memory obtained using malloc(), but not to a local array. 

This will work:
char *myfunc()
{
char *temp = "string";
return temp;
}

int main()
{
puts(someFun());
}

Ref: http://vijayinterviewquestions.blogspot.in/search?q=strcpy


Tehcnique 13:
A to Z ascii value = 65 to 90

a to z ascii value = 97 to 122




int
strcmp(const char *str1, const char *str2)

Output:
  • if Return value < 0 then it indicates str1 is less than str2.
  • if Return value > 0 then it indicates str2 is less than str1.
  • if Return value = 0 then it indicates str1 is equal to str2.

Technique 14:
* INADDR_ANY is used when you don't need to bind a socket to a specific IP. When you use this value as the address when calling bind(), the socket accepts connections to all the IPs of the machine.
 This allowed your program to work without knowing the IP address of the machine it was running on, or, in the case of a machine with multiple network interfaces, it allowed your server to receive packets destined to any of the interfaces.
If you wish to bind your socket to localhost only, the syntax would be my_sockaddress.sin_addr.s_addr = inet_addr("127.0.0.1");, then call bind(my_socket, (SOCKADDR *) &my_sockaddr, ...)
* Example: . For example, suppose that a host has interfaces 0, 1 and 2. If a UDP socket on this host is bound using INADDR_ANY and udp port 8000, then the socket will receive all packets for port 8000 that arrive on interfaces 0, 1, or 2. If a second socket attempts to Bind to port 8000 on interface 1, the Bind will fail since the first socket already ``owns'' that port/interface.



Ref:
https://www.cs.cmu.edu/~srini/15-441/F01.full/www/assignments/P2/htmlsim_split/node18.html

https://stackoverflow.com/questions/16508685/understanding-inaddr-any-for-socket-programming-c


Technique 15:
sprintf vs snprintf

Both will give the result you want, but snprintf is more generic, and will protect your string from overruns no matter the format string given. In addition, because snprintf(or sprintf for that matter) adds a final \0 , you should make the string buffer one byte bigger, char buff[MAXLEN + 1] 
snprintf ... Writes the results to a character string buffer. (...) will be terminated with a null character, unless buf_size is zero.

Technique 16:
In short: memset require more assembly operations then bzero . You probably shouldn't use bzero , it's not actually standard C, it was a POSIX thing. And note that word "was" - it was deprecated in POSIX.1-2001 and removed in POSIX.1-2008 in deference to memset so you're better off using the standard C 

Ref: https://stackoverflow.com/questions/17096990/why-use-bzero-over-memset

Ref: 
https://stackoverflow.com/questions/7706936/is-snprintf-always-null-terminating

All in all URL (networks,kernel,system,c)
http://blmrgnn.blogspot.in/2014/06/memory-layout-of-c-program-code-data.html

Techniqure 17:
enum starts with 0 if we dont specify any default value



Technique 18:

Returning the pointer from the function:

https://www.geeksforgeeks.org/return-local-array-c-function/

Ref: https://www.tutorialspoint.com/cprogramming/c_return_pointer_from_functions.htm

Technique 19: deep copy and shallow copy in the C

A shallow copy in this particular context means that you copy "references" (pointers, whatever) to objects, and the backing store of these references or pointers is identical, it's the very same object at the same memory location.
A deep copy, in contrast, means that you copy an entire object (struct). If it has members that can be copied shallow or deep, you also make a deep copy of them. Consider the following example:



typedef struct {
    char *name;
    int value;
} Node;

Node n1, n2, n3;

char name[] = "This is the name";

n1 = (Node){ name, 1337 };
n2 = n1; // Shallow copy, n2.name points to the same string as n1.name

n3.value = n1.value;
n3.name = strdup(n1.name); // Deep copy - n3.name is identical to n1.name 
                           // regarding
                           // its *contents* only, but it's not anymore the 
                           // same pointer


And  Using struct:

We can wrap array in a structure/class and return an 
instance of the struct/class. The reason for this 
work is, array members of structures are deeply 
copied. In below program deep copy happens when 
we returned instance is copied in main.
#include <stdio.h>
  
struct arrWrap {
    int arr[100];
};
  
struct arrWrap fun()
{
    struct arrWrap x;
  
    x.arr[0] = 10;
    x.arr[1] = 20;
  
    return x;
}
  
int main()
{
    struct arrWrap x = fun();
    printf("%d %d", x.arr[0], x.arr[1]);
    return 0;
}



Ref:  

 

Technique 20:

How to pass an entire array to a function as an argument?

In the above example, we have passed the address of each array element one by one using a for loop in C. However you can also pass an entire array to a function like this:

Note: The array name itself is the address of first element of that array. For example if array name is arr then you can say that arr is equivalent to the &arr[0].

#include <stdio.h>
void myfuncn( int *var1, int var2)
{
	/* The pointer var1 is pointing to the first element of
	 * the array and the var2 is the size of the array. In the
	 * loop we are incrementing pointer so that it points to
	 * the next element of the array on each increment.
	 *
	 */
    for(int x=0; x<var2; x++)
    {
        printf("Value of var_arr[%d] is: %d \n", x, *var1);
        /*increment pointer for next element fetch*/
        var1++;
    }
}

int main()
{
     int var_arr[] = {11, 22, 33, 44, 55, 66, 77};
     myfuncn(var_arr, 7);
     return 0;
}

Ref: https://beginnersbook.com/2014/01/c-passing-array-to-function-example/


Technique 21: convert the string to upper case:

A = 65
a = 97
A-a= 32

Example:

#include <stdio.h>
#include <string.h>
int main() {
   char s[100];
   int i;
   printf("\nEnter a string : ");
   gets(s);
   for (i = 0; s[i]!='\0'; i++) {
      if(s[i] >= 'a' && s[i] <= 'z') {
         s[i] = s[i] -32;  // s[i] = s[i]+32 to conver into lower case
      }
   }
   printf("\nString in Upper Case = %s", s);
   return 0;
}

No comments:

Post a Comment