How to declare pointers in c?

Below is the general form of pointer declaration.

datatype  * var_name;

datatype   - type of data to which the pointer points to
 *             - indirection operator(used to represent pointer)
var_name - name of the pointer variable.

The following are few pointer declarations:
char  * char_ptr;  /* pointer to character */
int     *integer_ptr; /* pointer to integer */
float  *float_ptr;  /* pointer to float */

How to assign values to pointers in c?
Below program illustrates how to assign values to pointers.


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

  int main() {
        char *char_ptr, str[32];
        int *int_ptr, int_val;
        float *float_ptr, float_val;

        /* assigning values to non-pointer variables */
        strcpy(str, "String");
        int_val = 100;
        float_val = 98.9;

        /* 
         * address of non-pointer variables 
         * is assigned as value for pointers
         */
        char_ptr = &str[0];
        int_ptr = &int_val;
        float_ptr = &float_val;

        /* printing the address of variables and values of pointers */
        printf("Value of int_ptr: 0x%x\tAddress of "
                "int_val: 0x%x\n", (int)int_ptr, (int)&int_val);
        printf("Value of char_ptr: 0x%x\tAddress of "
                "str[0]: 0x%x\n", (int)char_ptr, (int)&str[0]);
        printf("Value of float_ptr: 0x%x\tAddress of "
                "float_val: 0x%x\n", (int)float_ptr, (int)&float_val);

        /* printing the values pointed by pointer */
        printf("\n*int_ptr: %d\n", *int_ptr);
        printf("*float_ptr: %.2f\n", *float_ptr);
        printf("string pointed by char_ptr: ");
        while (*char_ptr != '\0') {
                printf("%c", *char_ptr);
                char_ptr++;
        }
        printf("\n");

        return 0;
  }




  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Value of int_ptr: 0xbf9da510 Address of int_val: 0xbf9da510
  Value of char_ptr: 0xbf9da51c Address of str[0]: 0xbf9da51c
  Value of float_ptr: 0xbf9da508 Address of float_val: 0xbf9da508

  *int_ptr: 100
  *float_ptr: 98.90
  string pointed by char_ptr: String


How to declare pointers in c? How to declare pointers in c? Reviewed by Mursal Zheker on Selasa, Oktober 08, 2013 Rating: 5

Tidak ada komentar:

Diberdayakan oleh Blogger.