The document contains code snippets related to data structures and pointers in C programming. It includes examples of using pointers to access array elements, dynamically allocating memory using functions like malloc(), calloc(), and realloc(). It also demonstrates writing and reading data from binary files using pointers, structs, and file I/O functions. Additional examples include concatenating files, counting words and characters in a file, and implementing employee records using file operations.
Guardians and Glitches: Navigating the Duality of Gen AI in AppSec
Data structures
1. DATA STRUCTURES
************acess element using
pointer*****************
#include<stdio.h>
int main()
{
int data[5], i;
printf("Enter elements: ");
for(i = 0; i < 5; ++i)
scanf("%d", data + i);
printf("You entered: n");
for(i = 0; i < 5; ++i)
printf("%dn", *(data + i));
return 0;
}
*****************addmaloc*****************
2. #include<stdio.h>
#include<stdlib.h>
int main()
{
//1
int i,j;
int count;
int *arr;
int sum = 0;
int product=1;
//2
arr = (int *)malloc(count* sizeof(int));
printf("Enter the total number of elements you want to
enter : ");
scanf("%d",&count);
printf("adresses of allocatedmeroryn");
for(i = 0;i<count;++i)
printf("%ut",arr+i);
4. int main()
{
//1
int i,j,s1,s2;
int count;
int *arr;
int sum = 0;
int product=1;
//2
arr = (int *)malloc(count* sizeof(int));
printf("Enter the total number of elements you want to
enter : ");
scanf("%d",&count);
printf("adresses of allocatedmeroryn");
for(i = 0;i<count;++i)
printf("%ut",arr+i);
s1=sizeof(int);
s2=count * s1;
printf("size of int=%d , size of one data =%dn",s1,s2);
5. printf("Size of integer type array having total %d * %d = %d
bytesn",s2/s1,s1,s2);
for(i = 0;i<count;i++)
{
//5
printf("nEnterelement %d : ",(i+1));
scanf("%d",arr+i);
//6
sum += *(arr+i);
product *= *(arr+i);
}
//7
printf("sum is %d n",sum);
printf("product is %d n",product);
//8
free(arr);
return 0;
}
**************reallocatingthe memory to
0***************
6. #include<stdio.h>
#include<stdlib.h>
int main(void)
{
int *ptr = (int*) malloc(10);
/* we are calling realloc with size = 0 */
realloc(ptr, 0);
return 0;
}
*****************limittest using malloc***********
/*C program to input and print text
using Dynamic Memory Allocation.*/
#include<stdio.h>
#include<stdlib.h>
7. int main()
{
int n;
char *text;
printf("Enterlimit of the text: ");
scanf("%d",&n);
/*allocatememory dynamically*/
text=(char*)malloc(n*sizeof(char));
printf("Entertext: ");
scanf(" "); /*clear input buffer*/
gets(text);
printf("Inputtedtext is: %sn",text);
/*Free Memory*/
free(text);
9. for (j = 0; j < sortnum; j++)
printf("%fn", *(list + j));
free(list);
return 0;
}
******************calloc********************
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i, num;
float *data;
printf("Entertotal number of elements(1 to 100): ");
scanf("%d", &num);
// Allocatesthe memory for 'num' elements.
data = (float*) calloc(num, sizeof(float));
10. if(data == NULL)
{
printf("Error!!! memory not allocated.");
exit(0);
}
printf("n");
// Stores the number entered by the user.
for(i = 0; i < num; ++i)
{
printf("Enter Number %d: ", i + 1);
scanf("%f", data + i);
}
// Loop to store largest number at address data
for(i = 1; i < num; ++i)
{
// Change < to > if you want to find the smallest number
11. if(*data < *(data + i))
*data = *(data + i);
}
printf("Largest element = %.2f", *data);
return 0;
}
*******************array additionand multiplication
using pointers*************
#include<stdio.h>
main()
{
int arr[5];
int sum,product, i;
int s1=sizeof(arr);
int s2=sizeof(int);
12. printf("Size of int=%d bytesn",s2);
printf("Size of one data=%d bytesn",sizeof(arr[0]));
printf("Size of integer type array having %d elements =
%d bytesn",s1/s2, s1);
/*read array elements*/
printf("nenter elements:n");
for(i=0;i<5;i++)
{
printf("enter arr[%d]",i);
scanf("%d",&arr[i]);
}
/*calculate sum and product*/
sum=0;
product=1;
for(i=0;i<5;i++)
{
sum=sum+arr[i];
product=product*arr[i];
}
printf("nsum of array is: %d",sum);
13. printf("nproduct of array is: %d",product);
}
*****************binaryfile using fwrite with
pointer***************
#include<stdio.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:program.bin","wb")) == NULL){
14. printf("Error! opening file");
// Program exits if the file pointerreturns NULL.
exit(1);
}
for(n = 1; n < 5; ++n)
{
num.n1 = n;
num.n2 = 5*n;
num.n3 = 5*n + 1;
fwrite(&num, sizeof(struct threeNum), 1, fptr);
}
fclose(fptr);
return 0;
}
***************code to read a file***********
#include<stdio.h>
15. #include<stdlib.h> // For exit() function
int main()
{
char c[1000];
FILE *fptr;
if ((fptr = fopen("program.txt", "r")) == NULL)
{
printf("Error! openingfile");
// Program exits if file pointer returns NULL.
exit(1);
}
// reads text until newline
fscanf(fptr,"%[^n]", c);
printf("Datafrom the file:n%s", c);
fclose(fptr);
return 0;
16. }
****************reverse in a file**********
/*
* C Program to Reverse the Contents of a File and Print it
*/
#include<stdio.h>
#include<errno.h>
long count_characters(FILE *);
int main()
17. {
int i;
long cnt;
char ch, ch1;
FILE *fp1, *fp2;
if (fp1 = fopen("file1.txt", "r"))
{
printf("The FILE hasbeen opened...n");
fp2 = fopen("file123.txt", "w");
18. cnt = count_characters(fp1); // to count the total
number of characters inside the source file
fseek(fp1, -1L, 2); // makes the pointerfp1 to point
at the last character of the file
printf("Number of characters to be copied %dn",
ftell(fp1));
while (cnt)
{
ch = fgetc(fp1);
fputc(ch, fp2);
fseek(fp1, -2L, 1); // shifts the pointerto the
previouscharacter
20. fclose(fp2);
}
// count the total number of characters in the file that *f
pointsto
long count_characters(FILE *f)
{
fseek(f, -1L, 2);
long last_pos= ftell(f); // returns the positionof the last
element of the file
last_pos++;
return last_pos;
21. }
******************struct student in file*******
#include<stdio.h>
struct student
{
char name[50];
int height;
};
int main(){
struct student stud1[5], stud2[5];
FILE *fptr;
int i;
fptr = fopen("file.txt","wb");
for(i = 0; i < 5; ++i)
{
fflush(stdin);
printf("Enter name: ");
gets(stud1[i].name);
25. printf("Enter name of first filen");
gets(file1);
printf("Enter name of second filen");
gets(file2);
printf("Enter name of file which will store contents of the
two filesn");
gets(file3);
fs1 = fopen(file1, "r");
fs2 = fopen(file2, "r");
if(fs1 == NULL || fs2 == NULL)
{
perror("Error ");
printf("Press any key to exit...n");
exit(EXIT_FAILURE);
}
26. ft = fopen(file3, "w"); // Opening in write mode
if(ft == NULL)
{
perror("Error ");
printf("Press any key to exit...n");
exit(EXIT_FAILURE);
}
while((ch = fgetc(fs1)) != EOF)
fputc(ch,ft);
while((ch = fgetc(fs2)) != EOF)
fputc(ch,ft);
printf("The two files were merged into %s file
successfully.n", file3);
{
ft=fopen(file3,"r");
27. fs3=fopen("file3.txt","w");
if (ft)
{
while ((ch1=getc(ft)) != EOF)
{
// Increment character count if NOT new line or
space
if (ch1 != ' ' && ch1 != 'n') { ++charcount; }
// Increment word count if new line or space
character
if (ch1 == ' ' || ch1 == 'n') { ++wordcount; }
// Increment line count if new line character
if (ch1 == 'n') { ++linecount;}
}
if (charcount > 0)
{
++linecount;
29. }
return 0;
}
**************to count word and character**********
#include<stdio.h>
int main()
{
FILE *fp1,*fp2;
char filename1[100],filename2[100];
char ch;
int linecount,wordcount, charcount;
// Initialize countervariables
linecount = 0;
wordcount = 0;
charcount = 0;
// Prompt user to enter filename
printf("Entera filename :n");
30. gets(filename1);
printf("enter file name2:n");
gets(filename2);
// Open file in read-only mode
fp1 = fopen(filename1,"r");
fp2=fopen(filename2,"w");
// If file opened successfully, then write the string to file
if ( fp1 )
{
//Repeat until End Of File character is reached.
while ((ch=getc(fp1)) != EOF) {
// Increment character count if NOT new line or
space
if (ch != ' ' && ch != 'n') { ++charcount;}
// Increment word count if new line or space
character
if (ch == ' ' || ch == 'n') { ++wordcount; }
31. // Increment line count if new line character
if (ch == 'n') { ++linecount;}
}
if (charcount > 0) {
++linecount;
++wordcount;
}
}
else
{
printf("Failedto open the filen");
}
fprintf(fp2,"Lines : %d n", linecount);
fprintf(fp2,"Words : %d n", wordcount);
32. fprintf(fp2,"Characters : %d n", charcount);
getchar();
return(0);
}
***********concatenatetwo files************
#include<stdio.h>
int main()
{
FILE *fp1,*fp2,*fp3;
int i,j,temp,count1,count,size,size2;
char str[100]={"This is a pattern matching"};
char substr[20]={"pattern"};
char
ch[100],ch1[100],filename1[100],filename2[100],filename3[1
00];
printf("Entera filename :n");
gets(filename1);
printf("enter file name2:n");
33. gets(filename2);
printf("enter file name2:n");
gets(filename3);
// Open file in read-only mode
fp1 = fopen(filename1,"r");
fp2=fopen(filename2,"r");
fp3=fopen(filename3,"w");
if(fp1&&fp2)
{
while((ch[i]= fgetc(fp1)) != EOF)
fseek(fp1, 0, 2); /* file pointerat the end of file */
size = ftell(fp1); /* take a positionof file pointerun size
variable*/
while((ch1[i] = fgetc(fp2)) != EOF)
fseek(fp2, 0, 2); /* file pointer at the end of file */
34. size2 = ftell(fp2); /* take a position of file pointerun size
variable*/
for (i = 0; i < size;)
{
j = 0;
count = 0;
while ((ch[i] == ch1[j]))
{
count++;
i++;
36. fprintf(fp3," %d times in %s",count1, str);
}
}
return 0;
}
***************employ record using files********
/*
* C Program to Update Detailsof Employee using Files
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
37. struct emp
{
int empid;
char *name;
};
int count = 0;
void add_rec(char*a);
void display(char*a);
void update_rec(char*a);
38. void main(intargc, char *argv[])
{
int choice;
while (1)
{
printf("MENU:n");
printf("1.Add a recordn");
printf("2.Displaythe filen");
printf("3.Update the recordn");
50. main()
{
int choice, num;
n = 0;/*Represents number of nodes in the heap*/
while(1)
{
printf("1.Insert the element n");
printf("2.Delete the element n");
printf("3.Display all elements n");
printf("4.Quit n");
51. printf("Enter your choice : ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter the element to be inserted to the list : ");
scanf("%d", &num);
insert(num, n);
n = n + 1;
break;
52. case 2:
printf("Enter the elements to be deleted from the list:
");
scanf("%d", &num);
delete(num);
break;
case 3:
display();
break;
case 4:
exit(0);
54. {
printf("Heap is empty n");
return;
}
for (i = 0; i < n; i++)
printf("%d ", array[i]);
printf("n");
}/*End of display()*/
insert(int num, int location)
56. array[location]= array[parentnode];
location = parentnode;
}/*End of while*/
array[0] = num; /*assign number to the root node */
}/*End of insert()*/
delete(int num)
{
int left, right, i, temp, parentnode;
57. for (i = 0; i < num; i++) {
if (num == array[i])
break;
}
if (num != array[i])
{
printf("%d not found in heap listn", num);
return;
}
array[i] = array[n - 1];
58. n = n - 1;
parentnode=(i - 1) / 2; /*find parentnode of node i */
if (array[i] > array[parentnode])
{
insert(array[i], i);
return;
}
left = 2 * i + 1; /*left child of i*/
right = 2 * i + 2; /* right childof i*/
while (right < n)
59. {
if (array[i] >= array[left] && array[i] >= array[right])
return;
if (array[right] <= array[left])
{
temp = array[i];
array[i] = array[left];
array[left] = temp;
i = left;
}
60. else
{
temp = array[i];
array[i] = array[right];
array[right] = temp;
i = right;
}
left = 2 * i + 1;
right = 2 * i + 2;
}/*End of while*/
62. int i,j,s1,s2;
float count;
float *arr;
int sum = 0;
int product=1;
//2
arr = (float *)malloc(count* sizeof(float));
{
printf("Enter the total number of elements you want to
enter : ");
scanf("%d",&count);
printf("adresses of allocatedmeroryn");
for(i = 0;i<count;++i)
printf("%ut",arr+i);
}
s1=sizeof(float);
s2=count * s1;
printf("nsize of float=%f n",s1);
63. printf("Size of integer type array having total %f * %f = %f
bytesn",s2/s1,s1,s2);
for(i = 0;i<count;i++)
{
//5
printf("nEnterelement %d : ",(i+1));
scanf("%f",arr+i);
//6
sum += *(arr+i);
product *= *(arr+i);
}
//7
printf("sum is %.2f n",sum);
printf("product is %.2f n",product);
//8
free(arr);
return 0;
}
*****************displaythe count of line word ans
characters***********
64. #include<stdio.h>
int main()
{
FILE *fp1,*fp2;
char filename1[100],filename2[100];
char ch;
int linecount,wordcount, charcount;
// Initialize countervariables
linecount = 0;
wordcount = 0;
charcount = 0;
// Prompt user to enter filename
printf("Entera filename :n");
gets(filename1);
printf("enter file name2:n");
gets(filename2);
// Open file in read-only mode
65. fp1 = fopen(filename1,"r");
fp2=fopen(filename2,"w");
// If file opened successfully, then write the string to file
if ( fp1 )
{
//Repeat until End Of File character is reached.
while ((ch=getc(fp1)) != EOF) {
// Increment character count if NOT new line or
space
if (ch != ' ' && ch != 'n') { ++charcount;}
// Increment word count if new line or space
character
if (ch == ' ' || ch == 'n') { ++wordcount; }
// Increment line count if new line character
if (ch == 'n') { ++linecount;}
68. printf("nFile unableto open ");
else
printf("nFile opened ");
fseek(fp, 0, 2); /* file pointer at the end of file */
size = ftell(fp); /* take a positionof file pointer un size
variable*/
printf("The size of given file is : %dn", size);
fclose(fp);
}
**************write a sentence into a file********
#include<stdio.h>
#include<stdlib.h> /* For exit() function */
74. //Create Linked List
void insert(int data) {
// Allocate memory for new node;
struct node *link = (struct node*) malloc(sizeof(struct
node));
link->data= data;
link->prev = NULL;
link->next = NULL;
// If head is empty, create new list
if(head==NULL) {
head = link;
return;
}
current = head;
// move to the end of the list
while(current->next!=NULL)
75. current = current->next;
// Insert link at the end of the list
current->next = link;
last = link;
link->prev = current;
}
//display the list
void printList() {
struct node *ptr = head;
printf("n[head]<=>");
//start from the beginning
while(ptr->next != NULL) {
printf(" %d <=>",ptr->data);
ptr = ptr->next;
}
77. {
int marks;
char subject[30];
};
int main()
{
struct course *ptr;
int i, noOfRecords;
printf("Enter number of records: ");
scanf("%d", &noOfRecords);
// Allocatesthe memory for noOfRecords structures with
pointerptr pointingto the base address.
ptr = (struct course*) malloc (noOfRecords * sizeof(struct
course));
for(i = 0; i < noOfRecords; ++i)
{
printf("Enter name of the subject and marks
respectively:n");
79. int main()
{
struct course *ptr;
int i, noOfRecords;
printf("Enter number of records: ");
scanf("%d", &noOfRecords);
// Allocatesthe memory for noOfRecords structures with
pointerptr pointingto the base address.
ptr = (struct course*) malloc (noOfRecords * sizeof(struct
course));
for(i = 0; i < noOfRecords; ++i)
{
printf("Enter name of the subject and marks
respectively:n");
scanf("%s %d", &(ptr+i)->subject, &(ptr+i)->marks);
}
printf("DisplayingInformation:n");
80. for(i = 0; i < noOfRecords ; ++i)
printf("%st%dn", (ptr+i)->subject, (ptr+i)->marks);
return 0;
}
***************doublylinkedlist
1*********************
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
struct Node *prev;
}node;
void insert(node *pointer, int data)
{
/* Iterate through the list till we encounterthe last
node.*/
while(pointer->next!=NULL)
81. {
pointer= pointer -> next;
}
/* Allocate memory for the new node and put data in
it.*/
pointer->next = (node *)malloc(sizeof(node));
(pointer->next)->prev = pointer;
pointer = pointer->next;
pointer->data = data;
pointer->next = NULL;
}
int find(node*pointer, int key)
{
pointer = pointer -> next; //First node is dummy node.
/* Iterate through the entire linked list and search for
the key. */
while(pointer!=NULL)
{
if(pointer->data== key) //key is found.
{
82. return 1;
}
pointer= pointer -> next;//Search in the next node.
}
/*Key is not found */
return 0;
}
void delete(node *pointer, int data)
{
/* Go to the node for which the node next to it has to be
deleted */
while(pointer->next!=NULL && (pointer->next)->data !=
data)
{
pointer= pointer -> next;
}
if(pointer->next==NULL)
{
printf("Element %d is not present in the
listn",data);
return;
83. }
/* Now pointerpointsto a node and the node next to it
has to be removed */
node *temp;
temp = pointer -> next;
/*temp pointsto the node which has to be removed*/
pointer->next = temp->next;
temp->prev = pointer;
/*We removed the node which is next to the pointer
(which is also temp) */
free(temp);
/* Beacuse we deleted the node, we no longer require
the memory used for it .
free() will deallocatethe memory.
*/
return;
}
void print(node *pointer)
{
if(pointer==NULL)
{
84. return;
}
printf("%d ",pointer->data);
print(pointer->next);
}
int main()
{
/* start alwayspoints to the first node of the linked list.
temp is used to point to the last node of the linked
list.*/
node *start,*temp;
start = (node *)malloc(sizeof(node));
temp = start;
temp -> next = NULL;
temp -> prev = NULL;
/* Here in this code, we take the first node as a dummy
node.
The first nozdoes not contain data, but it used because
to avoid handlingspecialcases
in insert and delete functions.
*/
85. printf("1. Insertn");
printf("2. Deleten");
printf("3. Printn");
printf("4. Findn");
while(1)
{
int query;
scanf("%d",&query);
if(query==1)
{
int data;
scanf("%d",&data);
insert(start,data);
}
else if(query==2)
{
int data;
scanf("%d",&data);
delete(start,data);
}
86. else if(query==3)
{
printf("The list is ");
print(start->next);
printf("n");
}
else if(query==4)
{
int da ta;
scanf("%d",&data);
int status = find(start,data);
if(status)
{
printf("ElementFoundn");
}
else
{
printf("ElementNot Foundn");
}
94. int list[MAX] = {1,8,4,6,0,3,5,2,7,9};
void display() {
int i;
printf("[");
// navigate through all items
for(i = 0; i < MAX; i++) {
printf("%d ",list[i]);
}
printf("]n");
}
void bubbleSort() {
int temp;
int i,j;
bool swapped = false;
95. // loop through all numbers
for(i = 0; i < MAX-1; i++) {
swapped = false;
// loopthrough numbers falling ahead
for(j = 0; j < MAX-1-i; j++) {
printf(" Items compared: [ %d, %d ] ", list[j],list[j+1]);
// check if next number is lesser than current no
// swap the numbers.
// (Bubble up the highest number)
if(list[j] > list[j+1]) {
temp = list[j];
list[j] = list[j+1];
list[j+1] = temp;
swapped = true;
printf(" => swapped [%d, %d]n",list[j],list[j+1]);
96. } else {
printf(" => not swappedn");
}
}
// if no number was swapped that means
// array is sorted now, break the loop.
if(!swapped) {
break;
}
printf("Iteration%d#: ",(i+1));
display();
}
}
int main() {
printf("Input Array: ");
98. // navigate through all items
for(i = 0;i < MAX;i++) {
printf("%d ",intArray[i]);
}
printf("]n");
}
void shellSort() {
int inner, outer;
int valueToInsert;
int interval = 1;
int elements = MAX;
int i = 0;
while(interval<= elements/3) {
interval= interval*3 +1;
}
101. int intArray[MAX] = {4,6,3,2,1,9,7};
/*void printline(intcount) {
int i;
for(i = 0;i < count-1;i++) {
printf("=");
}
printf("=n");
}*/
void display() {
int i;
printf("[");
// navigate through all items
for(i = 0;i < MAX;i++) {
printf("%d ", intArray[i]);
}
102. printf("]n");
}
void selectionSort() {
int indexMin,i,j;
// loop through all numbers
for(i = 0; i < MAX-1; i++) {
// set current element as minimum
indexMin= i;
// check the element to be minimum
for(j = i+1;j < MAX;j++) {
if(intArray[j] < intArray[indexMin]) {
indexMin= j;
}
}
109. printf("1. Insert into stack (Push operation).n");
printf("2. Delete from stack (Pop operation).n");
printf("3. Print top element of stack.n");
printf("4. Check if stack is empty.n");
printf("5. Traverse stack.n");
printf("6. Exit.n");
printf("Enteryour choice.n");
scanf("%d",&choice);
switch (choice)
{
case 1:
if (top == 5)
printf("Error: Overflownn");
else {
printf("Enter the value to insert.n");
scanf("%d", &element);
push(element);
}
break;
110. case 2:
if (top == 0)
printf("Error: Underflow.nn");
else {
element = pop();
printf("Element removed from stack is %d.n",
element);
}
break;
case 3:
if (!is_empty()) {
element = top_element();
printf("Element at the top of stack is %dnn",
element);
}
else
printf("Stack is empty.nn");
break;
111. case 4:
if (is_empty())
printf("Stack is empty.nn");
else
printf("Stack isn't empty.nn");
break;
case 5:
traverse();
break;
case 6:
exit(0);
}
}
}
void push(int value) {
stack[top] = value;
112. top++;
}
int pop() {
top--;
return stack[top];
}
void traverse() {
int d;
if (top == 0) {
printf("Stack is empty.nn");
return;
}
printf("There are %d elements in stack.n", top);
for (d = top - 1; d >= 0; d--)
printf("%dn", stack[d]);