0% found this document useful (0 votes)
34 views4 pages

Pointer

Uploaded by

educlenttinfo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views4 pages

Pointer

Uploaded by

educlenttinfo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

1.

Pointer to an Integer

c
Copy code
#include <stdio.h>

int main() {
int num = 10;
int *ptr = &num;

printf("Value of num: %d\n", num);


printf("Value of ptr: %d\n", *ptr);

return 0;
}

2. Pointer to a Float

c
Copy code
#include <stdio.h>

int main() {
float num = 5.67;
float *ptr = &num;

printf("Value of num: %.2f\n", num);


printf("Value of ptr: %.2f\n", *ptr);

return 0;
}

3. Pointer Arithmetic

c
Copy code
#include <stdio.h>

int main() {
int arr[3] = {1, 2, 3};
int *ptr = arr;

for (int i = 0; i < 3; i++) {


printf("Value at arr[%d] = %d\n", i, *(ptr + i));
}

return 0;
}
4. Pointer to a Character

c
Copy code
#include <stdio.h>

int main() {
char ch = 'A';
char *ptr = &ch;

printf("Character: %c\n", ch);


printf("Pointer points to: %c\n", *ptr);

return 0;
}

5. Swapping Two Numbers Using Pointers

c
Copy code
#include <stdio.h>

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

int main() {
int x = 5, y = 10;
swap(&x, &y);

printf("x: %d, y: %d\n", x, y);

return 0;
}

6. Pointer to an Array

c
Copy code
#include <stdio.h>

int main() {
int arr[3] = {10, 20, 30};
int *ptr = arr;

for (int i = 0; i < 3; i++) {


printf("arr[%d] = %d\n", i, *(ptr + i));
}

return 0;
}
7. Pointer to a Pointer

c
Copy code
#include <stdio.h>

int main() {
int num = 100;
int *ptr = &num;
int **pptr = &ptr;

printf("Value of num: %d\n", num);


printf("Value pointed to by ptr: %d\n", *ptr);
printf("Value pointed to by pptr: %d\n", **pptr);

return 0;
}

8. Using Pointers with Functions

c
Copy code
#include <stdio.h>

void addOne(int *num) {


(*num)++;
}

int main() {
int x = 10;
addOne(&x);

printf("x after adding one: %d\n", x);

return 0;
}

9. Pointer to a Structure

c
Copy code
#include <stdio.h>

typedef struct {
int id;
char name[50];
} Student;

int main() {
Student s1 = {1, "John"};
Student *ptr = &s1;

printf("Student ID: %d\n", ptr->id);


printf("Student Name: %s\n", ptr->name);

return 0;
}
10. Dynamic Memory Allocation

c
Copy code
#include <stdio.h>
#include <stdlib.h>

int main() {
int *arr = (int *)malloc(3 * sizeof(int));

if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}

for (int i = 0; i < 3; i++) {


arr[i] = i + 1;
printf("arr[%d] = %d\n", i, arr[i]);
}

free(arr);

return 0;
}

You might also like