Anda di halaman 1dari 43

Pointers

What is a pointer? Pointer types and Arrays Pointers and Strings

Pointer holds the memory address.

Pointer operators
* and & q = *m * unary operator returns the value located at the address. You can think * as at address. m = &count & return the memory address of its operand. You can think of & as returning the address of.

The variable ptr as a pointer to an integer as


int x; int *ptr; ptr = &x; x=5;
Since ptr points to its address, we can assign a value to the address that this pointer points to with *ptr = 5;
This is called dereferencing the pointer and it is identical to x=5;. The dereferencing operator says to set the contents of location pointed to by the pointer to the specified value.

The pointer ptr is located at memory address 100 x is located at memory address 200

int x, *ptr;

ptr=&x
& returns the memory address of its operand.

x=5 or *ptr=5

x=ptr;

This first one changes the value of x to y, while the second one changes the value of y to the new value of x, which is the same as y, and hence does not change its value.

Pointer types and Arrays


int my_array[] = {1,23,17,4,-5,100}; int *ptr; ptr = &my_array[0]; /* point our pointer at the first integer in our array */

Compile the program with gcc and check the output


#include <stdio.h>

int my_array[] = {1,23,17,4,-5,100}; int *ptr;


int main(void) { int i; ptr = &my_array[0];

/* point our pointer to the first element of the array */

printf("\n\n"); for (i = 0; i < 6; i++) { printf("my_array[%d] = %d ",i,my_array[i]); printf("ptr + %d = %d\n",i, *(ptr + i)); } return 0; }

/*<-- A */ /*<-- B */

change line B in program with following code and check output


printf("ptr + %d = %d\n",i, *ptr++);
Or printf("ptr + %d = %d\n",i, *(++ptr));

Pointers and Strings


char my_string[40]; my_string[0] my_string[1] my_string[2] my_string[3] OR char my_string[40] = {'T', 'e', 'd', '\0',}; OR char my_string[40] = "Ted"; NOTE: When the double quotes are used, instead of the single quotes as was done in the previous examples, the nul character ( '\0' ) is automatically appended to the end of the string. = = = = 'T'; 'e'; 'd': '\0';

Compile the program with gcc and check output


#include <stdio.h> char strA[80] = "A string to be used for demonstration purposes"; char strB[80]; int main(void) { char *pA; /* a pointer to type character */ char *pB; /* another pointer to type character */ puts(strA); /* show string A */ pA = strA; /* point pA at string A */ puts(pA); /* show what pA is pointing to */ pB = strB; /* point pB at string B */ putchar('\n'); /* move down one line on the screen */ while(*pA != '\0') /* line A (see text) */ { *pB++ = *pA++; /* line B (see text) */ } *pB = '\0'; /* line C (see text) */ puts(strB); /* show strB on screen */ return 0; }

Different pointers
1.What is pointer? Pointer holds memory address Example: Int *ptr; 2.What is constant pointer? A const pointer means you cannot change the pointer variable itself but you can change the value it points to Example:Char *const argv[ ]; 3.What is pointer to constant? A pointer to constant means you can change the pointer but not what it points to Example: Const char *arg;

4.What is void pointer? A pointer which accepts any data type. A void pointer is used for working with raw memory or for passing a pointer to an unspecified type. Example: Void *ptr; 5.What is double pointer? good use for pointers to pointers is in dynamically allocated, simulated multidimensional arrays Example: Int **ptr; 6. What is function pointer? Function pointer definition: A pointer which keeps address of a function is known as function pointer. Example: void (*foo)(int);

Array subscripts vs. pointer arithmetic


int array[100]; single dimensional array
Element Array subscript Dereferenced pointer First array[0] *array Second array[1] *(array + 1) Third array[2] *(array + 2) nth array[n - 1] *(array + n - 1)

array2d[4][3]; Multi dimensional array


Element Array subscript Dereferenced pointer First array[0][0] *(*(array + 0) + 0) Second row, second column array[1][1] *(*(array + 1) + 1) ith row, jth column array[i][j] *(*(array + i) + j)

2D array representation

2D array representation

*(*(multi + row) + col) OR multi[row][col] will have the same results.


#include <stdio.h> #define ROWS 5 #define COLS 10 int multi[ROWS][COLS]; int main(void) { int row, col; for (row = 0; row < ROWS; row++) { for (col = 0; col < COLS; col++) { multi[row][col] = row*col; } } for (row = 0; row < ROWS; row++) { for (col = 0; col < COLS; col++) { printf("\n%d ",multi[row][col]); printf("%d ",*(*(multi + row) + col)); } } return 0;

C's Memory Map


The stack is used for a great many things while your program executes. It holds the return addresses of function calls, arguments to functions, and local variables. It will also save the current state of the CPU. The heap is a region of free memory that your program can use via C's dynamic memory allocation functions. The next region is memory where global variables are stored. The first region is the memory that actually holds the program's executable code.

C's Memory Map

Dynamic memory allocation functions used in C


Function Task malloc Allocates memory requests size of bytes and returns a pointer to the Ist byte of allocated space

calloc

Allocates space for an array of elements initializes them to zero and returns a pointer to the memory

free

Frees previously allocated space

realloc

Modifies the size of previously allocated space.

ptr=(cast-type*)malloc(byte-size); ptr is a pointer of type cast-type the malloc returns a pointer (of cast type) to an area of memory with size byte-size. x=(int *)malloc(100*sizeof(int)); On successful execution of this statement a memory equivalent to 100 times the area of int bytes is reserved and the address of the first byte of memory allocated is assigned to the pointer x of type int

Allocating multiple blocks of memory


ptr=(cast-type*) calloc(n,elem-size); The above statement allocates contiguous space for n blocks each size of elements size bytes. All bytes are initialized to zero and a pointer to the first byte of the allocated region is returned. If there is not enough space a null pointer is returned.

Releasing the used space:


free(ptr); ptr is a pointer that has been created by using malloc or calloc.

To alter the size of allocated memory:


ptr=realloc(ptr,newsize); This function allocates new memory space of size newsize to the pointer variable ptr and returns a pointer to the first byte of the memory block. The allocated new block may be or may not be at the same region.

Check the output of following code


int i,*ip, ar[5]; ip = (int *)malloc(5*sizeof(int)); ip=ar; for(i=0;i< sizeof(ar)/sizeof(int);i++) { scanf("%d",&ip[i]); printf("%d\n",(*(ip+i)*5)); same result printf("%d\n",(*(ar+i)*5)); same result }

Check the output of following code


char s[256], *p; scanf("%s",s); p = (char *) malloc(strlen(s)+1); strcpy(p,s); printf("\n%s\n",p) ;

Storage class specifiers

Storage Classes examples


storage_specifier type var_name; extern int first, last;

static int series_num;//local,global


register int temp;

Auto variables

Extern variables

Static variables

Static local Variables


Storage Memory. Default initial value Zero. Scope Local to the block in which the variable is defined. Life Value of the variable persists between different function calls.

Static global Variables


Storage Memory. Default initial value Zero. Scope Local to the file in which the variable is defined. Life Value of the variable persists between different function calls within same file. functions in other files have no knowledge of it and cannot alter its contents directly.

Register variables

char copy(char []);//protype declaration OR char copy(char *);//protype declaration Int main() { int i; char a ,*ip; ip = (char *)malloc(5*sizeof(char)); for(i=0;i< 5;i++) { scanf(" %c",&ip[i]); } a = copy(ip);//call to copy function from main printf("\nvalue in main is %c",a); return 0; } copy(char *ip) { int i; for(i=0;i<5;i++) { printf("in function %c\n",*(ip+i)); } return (*ip); }

In the following code explain both copy function signatures i.e copy(char *ip) and copy(char ip[])

OR

copy(char ip[]) { int i; for(i=0;i<5;i++) { printf("\n in function %c",ip[i]); } return (*ip); }

Command line arguments


int main(int argc,char * argv[ ]) Argc := is an integer that is set to the number of items in the argument list Argv := array of character pointer.

Bit operations in C

Bit operations in C

Bit operations in C

Different bit Functions

Anda mungkin juga menyukai