Dynamic memory allocation allows programs to request additional memory at runtime as needed, rather than having a fixed amount allocated at compile time. The malloc function allocates memory on the heap and returns a pointer to it. This memory must later be freed using free to avoid memory leaks. Calloc initializes allocated memory to zero, while realloc changes the size of previously allocated memory. C supports dynamic memory allocation through library functions like malloc, calloc, free and realloc.
(5) cpp dynamic memory_arrays_and_c-stringsNico Ludwig
Check out these exercises: http://de.slideshare.net/nicolayludwig/5-cpp-dynamic-memoryarraysandcstringsexercises
- The Heap: Dynamic Memory and dynamic Array Allocation
- Automatic versus Dynamic Arrays
- A Glimpse of the Topic "Stack versus Heap"
-- "Geometric" Properties of the Heap and the Stack
- Lost Pointers and Memory Leaks
- Advanced C-strings: Buffers, Concatenation and Formatting
Memory management is one of the most fundamental and important aspect for any computer programming language. In the dynamic memory allocation, the memory is allocated to a variable or program at the run time.
Dynamic Memory Allocation, Pointers and Functions, Pointers and StructuresSelvaraj Seerangan
After go through this ppt the learners could be able to know the c programming concepts like dynamic memory allocation, pointers and functions and pointers to structures with examples.
The .NET garbage collector can be your best friend or your worst enemy; and it’s not friendly with a lot of people. The GC left more than a few production systems burning in smoke after developers failed to anticipate the effects of real production loads on the memory subsystem. In this talk, we will methodically measure and improve the .NET garbage collector’s performance. We will begin with a quick refresher on dynamic performance tools that can identify GC issues: CLR performance counters, ETW GC events, and ETW object allocation events; as well as static analysis tools, such as the Roslyn-based heap allocations analyzer. Then, we will inspect multiple issues at the source code level: excessive boxing, unintended effects of lambdas closing over local variables, await-generated state machines, intermediate objects in LINQ queries, and many others. We will also discuss higher-level memory problems: how to get rid of large object allocations, how to avoid finalization, and how to convert heap-based designs to local objects. Some of these ideas are now being applied at the language and framework level in C# 7 and .NET Core. At the end of the talk, you will be equipped to reduce memory traffic and GC overhead in your own applications, often by a factor of 10 or more!
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...Amil Baba Dawood bangali
Contact with Dawood Bhai Just call on +92322-6382012 and we'll help you. We'll solve all your problems within 12 to 24 hours and with 101% guarantee and with astrology systematic. If you want to take any personal or professional advice then also you can call us on +92322-6382012 , ONLINE LOVE PROBLEM & Other all types of Daily Life Problem's.Then CALL or WHATSAPP us on +92322-6382012 and Get all these problems solutions here by Amil Baba DAWOOD BANGALI
#vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore#blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #blackmagicforlove #blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #Amilbabainuk #amilbabainspain #amilbabaindubai #Amilbabainnorway #amilbabainkrachi #amilbabainlahore #amilbabaingujranwalan #amilbabainislamabad
(5) cpp dynamic memory_arrays_and_c-stringsNico Ludwig
Check out these exercises: http://de.slideshare.net/nicolayludwig/5-cpp-dynamic-memoryarraysandcstringsexercises
- The Heap: Dynamic Memory and dynamic Array Allocation
- Automatic versus Dynamic Arrays
- A Glimpse of the Topic "Stack versus Heap"
-- "Geometric" Properties of the Heap and the Stack
- Lost Pointers and Memory Leaks
- Advanced C-strings: Buffers, Concatenation and Formatting
Memory management is one of the most fundamental and important aspect for any computer programming language. In the dynamic memory allocation, the memory is allocated to a variable or program at the run time.
Dynamic Memory Allocation, Pointers and Functions, Pointers and StructuresSelvaraj Seerangan
After go through this ppt the learners could be able to know the c programming concepts like dynamic memory allocation, pointers and functions and pointers to structures with examples.
The .NET garbage collector can be your best friend or your worst enemy; and it’s not friendly with a lot of people. The GC left more than a few production systems burning in smoke after developers failed to anticipate the effects of real production loads on the memory subsystem. In this talk, we will methodically measure and improve the .NET garbage collector’s performance. We will begin with a quick refresher on dynamic performance tools that can identify GC issues: CLR performance counters, ETW GC events, and ETW object allocation events; as well as static analysis tools, such as the Roslyn-based heap allocations analyzer. Then, we will inspect multiple issues at the source code level: excessive boxing, unintended effects of lambdas closing over local variables, await-generated state machines, intermediate objects in LINQ queries, and many others. We will also discuss higher-level memory problems: how to get rid of large object allocations, how to avoid finalization, and how to convert heap-based designs to local objects. Some of these ideas are now being applied at the language and framework level in C# 7 and .NET Core. At the end of the talk, you will be equipped to reduce memory traffic and GC overhead in your own applications, often by a factor of 10 or more!
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...Amil Baba Dawood bangali
Contact with Dawood Bhai Just call on +92322-6382012 and we'll help you. We'll solve all your problems within 12 to 24 hours and with 101% guarantee and with astrology systematic. If you want to take any personal or professional advice then also you can call us on +92322-6382012 , ONLINE LOVE PROBLEM & Other all types of Daily Life Problem's.Then CALL or WHATSAPP us on +92322-6382012 and Get all these problems solutions here by Amil Baba DAWOOD BANGALI
#vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore#blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #blackmagicforlove #blackmagicformarriage #aamilbaba #kalajadu #kalailam #taweez #wazifaexpert #jadumantar #vashikaranspecialist #astrologer #palmistry #amliyaat #taweez #manpasandshadi #horoscope #spiritual #lovelife #lovespell #marriagespell#aamilbabainpakistan #amilbabainkarachi #powerfullblackmagicspell #kalajadumantarspecialist #realamilbaba #AmilbabainPakistan #astrologerincanada #astrologerindubai #lovespellsmaster #kalajaduspecialist #lovespellsthatwork #aamilbabainlahore #Amilbabainuk #amilbabainspain #amilbabaindubai #Amilbabainnorway #amilbabainkrachi #amilbabainlahore #amilbabaingujranwalan #amilbabainislamabad
An Approach to Detecting Writing Styles Based on Clustering Techniquesambekarshweta25
An Approach to Detecting Writing Styles Based on Clustering Techniques
Authors:
-Devkinandan Jagtap
-Shweta Ambekar
-Harshit Singh
-Nakul Sharma (Assistant Professor)
Institution:
VIIT Pune, India
Abstract:
This paper proposes a system to differentiate between human-generated and AI-generated texts using stylometric analysis. The system analyzes text files and classifies writing styles by employing various clustering algorithms, such as k-means, k-means++, hierarchical, and DBSCAN. The effectiveness of these algorithms is measured using silhouette scores. The system successfully identifies distinct writing styles within documents, demonstrating its potential for plagiarism detection.
Introduction:
Stylometry, the study of linguistic and structural features in texts, is used for tasks like plagiarism detection, genre separation, and author verification. This paper leverages stylometric analysis to identify different writing styles and improve plagiarism detection methods.
Methodology:
The system includes data collection, preprocessing, feature extraction, dimensional reduction, machine learning models for clustering, and performance comparison using silhouette scores. Feature extraction focuses on lexical features, vocabulary richness, and readability scores. The study uses a small dataset of texts from various authors and employs algorithms like k-means, k-means++, hierarchical clustering, and DBSCAN for clustering.
Results:
Experiments show that the system effectively identifies writing styles, with silhouette scores indicating reasonable to strong clustering when k=2. As the number of clusters increases, the silhouette scores decrease, indicating a drop in accuracy. K-means and k-means++ perform similarly, while hierarchical clustering is less optimized.
Conclusion and Future Work:
The system works well for distinguishing writing styles with two clusters but becomes less accurate as the number of clusters increases. Future research could focus on adding more parameters and optimizing the methodology to improve accuracy with higher cluster values. This system can enhance existing plagiarism detection tools, especially in academic settings.
Literature Review Basics and Understanding Reference Management.pptxDr Ramhari Poudyal
Three-day training on academic research focuses on analytical tools at United Technical College, supported by the University Grant Commission, Nepal. 24-26 May 2024
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Dr.Costas Sachpazis
Terzaghi's soil bearing capacity theory, developed by Karl Terzaghi, is a fundamental principle in geotechnical engineering used to determine the bearing capacity of shallow foundations. This theory provides a method to calculate the ultimate bearing capacity of soil, which is the maximum load per unit area that the soil can support without undergoing shear failure. The Calculation HTML Code included.
Online aptitude test management system project report.pdfKamal Acharya
The purpose of on-line aptitude test system is to take online test in an efficient manner and no time wasting for checking the paper. The main objective of on-line aptitude test system is to efficiently evaluate the candidate thoroughly through a fully automated system that not only saves lot of time but also gives fast results. For students they give papers according to their convenience and time and there is no need of using extra thing like paper, pen etc. This can be used in educational institutions as well as in corporate world. Can be used anywhere any time as it is a web based application (user Location doesn’t matter). No restriction that examiner has to be present when the candidate takes the test.
Every time when lecturers/professors need to conduct examinations they have to sit down think about the questions and then create a whole new set of questions for each and every exam. In some cases the professor may want to give an open book online exam that is the student can take the exam any time anywhere, but the student might have to answer the questions in a limited time period. The professor may want to change the sequence of questions for every student. The problem that a student has is whenever a date for the exam is declared the student has to take it and there is no way he can take it at some other time. This project will create an interface for the examiner to create and store questions in a repository. It will also create an interface for the student to take examinations at his convenience and the questions and/or exams may be timed. Thereby creating an application which can be used by examiners and examinee’s simultaneously.
Examination System is very useful for Teachers/Professors. As in the teaching profession, you are responsible for writing question papers. In the conventional method, you write the question paper on paper, keep question papers separate from answers and all this information you have to keep in a locker to avoid unauthorized access. Using the Examination System you can create a question paper and everything will be written to a single exam file in encrypted format. You can set the General and Administrator password to avoid unauthorized access to your question paper. Every time you start the examination, the program shuffles all the questions and selects them randomly from the database, which reduces the chances of memorizing the questions.
Student information management system project report ii.pdfKamal Acharya
Our project explains about the student management. This project mainly explains the various actions related to student details. This project shows some ease in adding, editing and deleting the student details. It also provides a less time consuming process for viewing, adding, editing and deleting the marks of the students.
Forklift Classes Overview by Intella PartsIntella Parts
Discover the different forklift classes and their specific applications. Learn how to choose the right forklift for your needs to ensure safety, efficiency, and compliance in your operations.
For more technical information, visit our website https://intellaparts.com
Understanding Inductive Bias in Machine LearningSUTEJAS
This presentation explores the concept of inductive bias in machine learning. It explains how algorithms come with built-in assumptions and preferences that guide the learning process. You'll learn about the different types of inductive bias and how they can impact the performance and generalizability of machine learning models.
The presentation also covers the positive and negative aspects of inductive bias, along with strategies for mitigating potential drawbacks. We'll explore examples of how bias manifests in algorithms like neural networks and decision trees.
By understanding inductive bias, you can gain valuable insights into how machine learning models work and make informed decisions when building and deploying them.
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsVictor Morales
K8sGPT is a tool that analyzes and diagnoses Kubernetes clusters. This presentation was used to share the requirements and dependencies to deploy K8sGPT in a local environment.
Hierarchical Digital Twin of a Naval Power SystemKerry Sado
A hierarchical digital twin of a Naval DC power system has been developed and experimentally verified. Similar to other state-of-the-art digital twins, this technology creates a digital replica of the physical system executed in real-time or faster, which can modify hardware controls. However, its advantage stems from distributing computational efforts by utilizing a hierarchical structure composed of lower-level digital twin blocks and a higher-level system digital twin. Each digital twin block is associated with a physical subsystem of the hardware and communicates with a singular system digital twin, which creates a system-level response. By extracting information from each level of the hierarchy, power system controls of the hardware were reconfigured autonomously. This hierarchical digital twin development offers several advantages over other digital twins, particularly in the field of naval power systems. The hierarchical structure allows for greater computational efficiency and scalability while the ability to autonomously reconfigure hardware controls offers increased flexibility and responsiveness. The hierarchical decomposition and models utilized were well aligned with the physical twin, as indicated by the maximum deviations between the developed digital twin hierarchy and the hardware.
2. Basic Idea
• In some situations, data is dynamic in nature.
– Amount of data cannot be predicted beforehand.
– Number of data item keeps changing during program
execution.
• Dynamic Memory Allocation: Ability of a program to use more
memory space at execution time
– Memory space required can be specified at the time of
execution.
– C supports allocating and freeing memory dynamically
using library routines.
Spring 2012 Programming and Data Structure 2
3. Dynamic Memory Allocation
• Ability of a program to use more memory space at
execution time
– Hold new nodes
• Use function malloc to allocate memory
– Release space no longer needed
• Use function free to deallocate memory
– Use #include <stdlib.h> header file when using
malloc & free functions
4. Memory Usage + Heap
Variable memory is allocated in three areas:
• Global data section
• Run-time stack
• Dynamically allocated - heap
Global variables are allocated in the global
data section and are accessible from all
parts of the program.
Local variables are allocated during
execution on the run-time stack.
Dynamically allocated variables are items
created during run-time and are
allocated on the heap.
Trap Vector Table
Program Code
Global Data Section
(Global and Static vars)
Run-Time Stack
(Local and Auto vars)
Trap Routines
0x0000
0xFFFF
Operating System
Heap
(Dynamically allocated vars)
I/O Space
Interrupt Vector Table
0x3000
5. Memory Allocation Functions
• malloc
– Allocates requested number of bytes and returns a
pointer to the first byte of the allocated space.
• calloc
– Allocates space for an array of elements, initializes
them to zero and then returns a pointer to the
memory.
• free
Frees previously allocated space.
• realloc
– Modifies the size of previously allocated space.
Spring 2012 Programming and Data Structure 5
6. Functions malloc & free
• ptr = malloc(sizeof(struct node));
– sizeof(struct node) returns the size in bytes of the structure
– malloc() allocates the specified number of bytes in memory
– Returns a pointer to the place in memory
– Returns NULL, if no more memory is available
• free(ptr);
– Deallocates the memory referred to by the pointer so it can
be reused
7. Contd.
• Examples
p = (int *) malloc (100 * sizeof (int)) ;
• A memory space equivalent to “100 times the size of an
int” bytes is reserved.
• The address of the first byte of the allocated memory is
assigned to the pointer p of type int.
Spring 2012 Programming and Data Structure 7
p
400 bytes of space
8. malloc
int *ip;
ip = (int *) malloc(10 * sizeof(int));
If (ip == NULL)
{
/* Handle Error! */
}
• Options for handling error
– Abort
– Ask again
– Save user data
– Ask for less
– Free up something
9. malloc -- What happens?
int foo(int n) {
int *ip;
ip = malloc(n * sizeof(int));
if(ip == NULL) {
/* Handle Error! */
}
...
Stack
Heap
Data
Code
40 bytes
11. Using the space
int sample(int n)
{
int i;
int *ip;
if((ip = malloc(n*sizeof(int))) == NULL)
{
/* Handle Error Here */
}
for(i = 0; i < n; i++)
ip[i] = 0;
...
17. void pointer
• Not originally in c
• Relatively recent addition
• Basically a “generic” pointer
• Intended for use in applications like free
where the block of memory located at some
address will be freed without any necessity of
defining the type
18. Using calloc() (1)
• calloc()is a variant of malloc()
• calloc() takes two arguments: the number of "things"
to be allocated and the size of each "thing" (in bytes)
• calloc() returns the address of the chunk of memory
that was allocated
• calloc() also sets all the values in the allocated memory
to zeros (malloc() doesn't)
19. Using calloc() (2)
• calloc()is also used to dynamically allocate arrays
• For instance, to dynamically allocate an array of 10
ints:
int *arr;
arr = (int *) calloc(10, sizeof(int));
/* now arr has the address
of an array of 10 ints, all 0s */
20. malloc/calloc return value (1)
• malloc and calloc both return the address of the newly-
allocated block of memory
• However, they are not guaranteed to succeed!
– maybe there is no more memory available
• If they fail, they return NULL
• You must always check for NULL when using malloc or
calloc
21. malloc/calloc return value (2)
• bad:
int *arr = (int *) malloc(10 * sizeof(int));
/* code that uses arr... */
• good:
int *arr = (int *) malloc(10 * sizeof(int));
if (arr == NULL) {
fprintf(stderr, "out of memory!n");
exit(1);
}
• Always do this!
22. malloc() vs. calloc()
• malloc/calloc both allocate memory
• calloc() zeros out allocated memory,
malloc() doesn't.
23. Functions malloc & free: Examples
• Once allocated, the memory belongs to your program until it terminates or is
free()’d.
#include <stdio.h>
#include <stdlib.h>
int main() {
int* dynArray;
/* Allocate space for 16 ints */
dynArray = (int *)malloc( 16 * sizeof(int) );
dynArray[6] = 65;
dynArray[12] = 2;
doSomething( dynArray );
free( dynArray );
}
24. Using free() (2)
int *arr;
arr = (int *) calloc(10, sizeof(int));
/* now arr has the address of an array of 10 ints, all 0s */
/* Code that uses the array... */
/* Now we no longer need the array, so "free" it: */
free(arr);
/* Now we can't use arr anymore. */
25. Using free() (3)
• NOTE: When we free() some memory, the memory is not
erased or destroyed
• Instead, the operating system is informed that we don't need
the memory any more, so it may use it for e.g. another program
• Trying to use memory after freeing it can cause a segmentation
violation (program crash)
26. Dynamic memory allocation (3)
#include <stdlib.h>
int *foo(int n) {
int i[10]; /* memory allocated here */
int i2[n]; /* ERROR: NOT VALID! */
int *j;
j = (int *)malloc(n * sizeof(int));
/* Alternatively: */
/* j = (int *)calloc(n, sizeof(int)); */
return j;
} /* i’s memory deallocated here; j’s not */
27. Dynamic memory allocation (4)
void bar(void) {
int *arr = foo(10);
arr[0] = 10;
arr[1] = 20;
/* ... do something with arr ... */
free(arr); /* deallocate memory */
}
• Not calling free() leads to memory leaks !
28. Structures and malloc
struct person {
char initials[4];
long int ssn;
int height;
struct person *father;
struct person *mother;
} *tom, *bill, *susan;
int main() {
tom = (struct person *)malloc( sizeof( struct person ) );
bill = (struct person *)malloc( sizeof( struct person ) );
susan = (struct person *)malloc( sizeof( struct person ) );
strncpy(tom->initials, "tj“, 2);
tom->ssn = 555235512;
tom->father = bill;
tom->mother = susan;
susan->height = 68;
/* Since tom is now a pointer, tom->mother->height is correct. */
printf(“nTom's mother's height is: %d", tom->mother->height);
}
29. Structures and malloc
struct person {
char initials[4];
long int ssn;
int height;
struct person *father;
struct person *mother;
} *tom, *bill, *susan;
30. Structures and malloc
int main( ) {
tom = (struct person *)malloc( sizeof( struct person ) );
bill = (struct person *)malloc( sizeof( struct person ) );
susan = (struct person *)malloc( sizeof( struct person ) );
strncpy(tom->initials, "tj“, 2);
tom->ssn = 555235512;
tom->father = bill;
tom->mother = susan;
susan->height = 68;
printf(“nTom's mother's height: %d", tom->mother->height);
}
31. Dynamic Allocation – Example 1
int *p; Call stack Heap
p
?
p = (int*)malloc(sizeof(int));
p
*p = 24;
24
p
*p
*p
?
free(p);
24
p
unstable
memory
33. Realloc
ptr = realloc(ptr, num_bytes);
• What it does (conceptually)
– Find space for new allocation
– Copy original data into new space
– Free old space
– Return pointer to new space
36. void read_array (int *a, int n) ;
int sum_array (int *a, int n) ;
void wrt_array (int *a, int n) ;
int main () {
int *a, n;
printf (“Input n: “) ;
scanf (“%d”, &n) ;
a = calloc (n, sizeof (int)) ;
read_array (a, n) ;
wrt_array (a, n) ;
printf (“Sum = %dn”, sum_array(a, n);
}
37. void read_array (int *a, int n) {
int i;
for (i=0; i<n; i++)
scanf (“%d”, &a[i]) ;
}
void sum_array (int *a, int n) {
int i, sum=0;
for (i=0; i<n; i++)
sum += a[i] ;
return sum;
}
void wrt_array (int *a, int n) {
int i;
........
}
38. Arrays of Pointers
• Array elements can be of any type
– array of structures
– array of pointers
39. int main (void) {
char word[MAXWORD];
char * w[N]; /* an array of pointers */
int i, n; /* n: no of words to sort */
for (i=0; scanf(“%s”, word) == 1); ++i) {
w[i] = calloc (strlen(word)+1, sizeof(char));
if (w[i] == NULL) exit(0);
strcpy (w[i], word) ;
}
n = i;
sortwords (w, n) ;
wrt_words (w, n);
return 0;
}
40. w
0
1
2
3
17
Input : A is for apple or alphabet pie which
all get a slice of come taste it and try
A 0
i s 0
f o r 0
a p p l e 0
t r y 0
41. void sort_words (char *w[], int n) {
int i, j;
for (i=0; i<n; ++i)
for (j=i+1; j<n; ++j)
if (strcmp(w[i], w[j]) > 0)
swap (&w[i], &w[j]) ;
}
void swap (char **p, char **q) {
char *tmp ;
tmp = *p;
*p = *q;
*q = tmp;
}
44. Example
Spring 2012 Programming and Data Structure 44
printf("Input heights for %d
students n",N);
for(i=0;i<N;i++)
scanf("%f",&height[i]);
for(i=0;i<N;i++)
sum+=height[i];
avg=sum/(float) N;
printf("Average height= %f n",
avg);
}
#include <stdio.h>
int main() {
int i,N;
float *height;
float sum=0,avg;
printf("Input the number of students. n");
scanf("%d",&N);
height=(float *) malloc(N * sizeof(float));
Input the number of students.
5
Input heights for 5 students
23 24 25 26 27
Average height= 25.000000
45. 2d arrays and pointers
• Recall that when we declare a two-dimensional array, we can
think of it as an array of arrays. For example, if we have the
following array declaration,
int data[3][4];
• we can think of this as an array with three members, each of
which is an array of four ints. We can visualize it like this:
Spring 2012 Programming and Data Structure 45
46. • The address of the beginning of the entire array is the same as the
address of the first row of the array, which is the address of the first
element of the first row.
• However, to get to the first row we must dereference the array
name and to get the value of the first element of the first row we
must dereference twice
int sales[2][3] = { {1, 2, 3},
{9, 10, 11} };
printf("address of data is %pn", sales);
printf("address of row 0 of data is %pn", *sales);
printf("the value of sales[0][0] is %dn", **sales);
produces
address of data is 0x7fffffed8140
address of row 0 of data is 0x7fffffed8140
the value of sales[0][0] is 1
Spring 2012 Programming and Data Structure 46
47. 2d arrays
• The general form for getting the address of any
element of any row is
*(array_name + row) + column
• For example, when we write *(data + 1) + 2,
we are saying “add the size of one row to the
address of data, get the address of this, then
add the size of two elements of a row to this”.
Spring 2012 Programming and Data Structure 47
49. Pointer to Pointer
• Example:
int **p;
p=(int **) malloc(3 * sizeof(int *));
Spring 2012 Programming and Data Structure 49
p
p[2]
p[1]
p[0]
int *
int **
int *
int *
50. 2d array
int AA[MAX][15]
• A two dimensional array is considered to be a one
dimensional array of rows, which are, themselves, one
dimensional arrays.
• The rows are stored in sequence, starting with row 0.
AA[0] is stored first, then AA[1], then AA[2], and so on to
AA[MAX-1].
• Each of these ``elements'' is an array.
• The same is true for higher dimensional arrays.
• A n-dimensional array is considered to be a one dimensional
array whose elements are, themselves, arrays of dimension.
Spring 2012 Programming and Data Structure 50
52. 2d array
• Recall that an array name (without an index)
represents a pointer to the first object of the array.
• So the name, AA, is a pointer to the element AA[0].
• But, AA[0] is a one dimensional array; so, AA[0]
points to the first object in row 0, i.e. AA[0] points to
AA[0][0].
• AA[k] is the address of AA[k][0].
• AA[k] + j points to AA[k][j], and *(AA[k] + j)
accesses the value of AA[k][j] .
Spring 2012 Programming and Data Structure 52
53. 2d array
• The name, AA points to the first object in this array of arrays,
i.e. AA points to the array AA[0].
• The addresses represented by AA and AA[0] are the same;
however, they point to objects of different types.
• AA[0] points to AA[0][0], so it is an integer pointer.
• AA points to AA[0], so it is a pointer to an integer pointer.
• If we add 1 to AA, the resulting pointer, AA + 1, points to the
array AA[1], and AA + k points to the array AA[k].
• Adding 1 to AA[0] results in a pointer that points to AA[0][1]
Spring 2012 Programming and Data Structure 53
55. Dynamically Allocating 2D Arrays
Can not simply dynamically
allocate 2D (or higher)
array
Idea - allocate an array of
pointers (first dimension),
make each pointer point
to a 1D array of the
appropriate size
Can treat result as 2D array
0
4
3
2
1
0 3
2
1
A
56. Dynamically Allocating 2D Array
float **A; /* A is an array (pointer) of float
pointers */
int I;
A = (float **) calloc(5,sizeof(float *));
/* A is a 1D array (size 5) of float pointers */
for (I = 0; I < 5; I++)
A[I] = (float *) calloc(4,sizeof(float));
/* Each element of array points to an array of 4
float variables */
/* A[I][J] is the Jth entry in the array that the
Ith member of A points to */
57. Non-Square 2D Arrays
No need to allocate square 2D
arrays:
float **A;
int I;
A = (float **) calloc(5,
sizeof(float *));
for (I = 0; I < 5; I++)
A[I] = (float **)
calloc(I+1,
sizeof(float));
0
4
3
2
1
0 3
2
1
A
4
59. 2-D Array Allocation
Spring 2012 Programming and Data Structure 59
#include <stdio.h>
#include <stdlib.h>
int **allocate(int h, int w)
{
int **p;
int i,j;
p=(int **) calloc(h, sizeof (int *) );
for(i=0;i<h;i++)
p[i]=(int *) calloc(w,sizeof (int));
return(p);
}
void read_data(int **p,int h,int w)
{
int i,j;
for(i=0;i<h;i++)
for(j=0;j<w;j++)
scanf ("%d",&p[i][j]);
}
Allocate array
of pointers
Allocate array of
integers for each
row
Elements accessed
like 2-D array elements.
60. 2-D Array: Contd.
Spring 2012 Programming and Data Structure 60
void print_data(int **p,int h,int w)
{
int i,j;
for(i=0;i<h;i++)
{
for(j=0;j<w;j++)
printf("%5d ",p[i][j]);
printf("n");
}
}
int main()
{
int **p;
int M,N;
printf("Give M and N n");
scanf("%d%d",&M,&N);
p=allocate(M,N);
read_data(p,M,N);
printf("n The array read as n");
print_data(p,M,N);
}
Give M and N
3 3
1 2 3
4 5 6
7 8 9
The array read as
1 2 3
4 5 6
7 8 9
61. 2d arrays and pointers
• Recall that when we declare a two-dimensional array, we can
think of it as an array of arrays. For example, if we have the
following array declaration,
int data[3][4];
• we can think of this as an array with three members, each of
which is an array of four ints. We can visualize it like this:
Spring 2012 Programming and Data Structure 61
62. 2d arrays
• The general form for getting the address of any
element of any row is
*(array_name + row) + column
• For example, when we write *(data + 1) + 2,
we are saying “add the size of one row to the
address of data, get the address of this, then
add the size of two elements of a row to this”.
Spring 2012 Programming and Data Structure 62
63. Pointer to Pointer
• Example:
int **p;
p=(int **) malloc(3 * sizeof(int *));
Spring 2012 Programming and Data Structure 63
p
p[2]
p[1]
p[0]
int *
int **
int *
int *
64. 2d array
int AA[MAX][15]
• A two dimensional array is considered to be a one
dimensional array of rows, which are, themselves, one
dimensional arrays.
• The rows are stored in sequence, starting with row 0.
AA[0] is stored first, then AA[1], then AA[2], and so on to
AA[MAX-1].
• Each of these ``elements'' is an array.
• The same is true for higher dimensional arrays.
• A n-dimensional array is considered to be a one dimensional
array whose elements are, themselves, arrays of dimension.
Spring 2012 Programming and Data Structure 64
66. 2d array
• Recall that an array name (without an index)
represents a pointer to the first object of the array.
• So the name, AA, is a pointer to the element AA[0].
• But, AA[0] is a one dimensional array; so, AA[0]
points to the first object in row 0, i.e. AA[0] points to
AA[0][0].
• AA[k] is the address of AA[k][0].
• AA[k] + j points to AA[k][j], and *(AA[k] + j)
accesses the value of AA[k][j] .
Spring 2012 Programming and Data Structure 66
67. 2d array
• The name, AA points to the first object in this array of arrays,
i.e. AA points to the array AA[0].
• The addresses represented by AA and AA[0] are the same;
however, they point to objects of different types.
• AA[0] points to AA[0][0], so it is an integer pointer.
• AA points to AA[0], so it is a pointer to an integer pointer.
• If we add 1 to AA, the resulting pointer, AA + 1, points to the
array AA[1], and AA + k points to the array AA[k].
• Adding 1 to AA[0] results in a pointer that points to AA[0][1]
Spring 2012 Programming and Data Structure 67
69. Dynamically Allocating 2D Arrays
Can not simply dynamically
allocate 2D (or higher)
array
Idea - allocate an array of
pointers (first dimension),
make each pointer point
to a 1D array of the
appropriate size
Can treat result as 2D array
0
4
3
2
1
0 3
2
1
A
70. Dynamically Allocating 2D Array
float **A; /* A is an array (pointer) of float
pointers */
int I;
A = (float **) calloc(5,sizeof(float *));
/* A is a 1D array (size 5) of float pointers */
for (I = 0; I < 5; I++)
A[I] = (float *) calloc(4,sizeof(float));
/* Each element of array points to an array of 4
float variables */
/* A[I][J] is the Jth entry in the array that the
Ith member of A points to */
71. Non-Square 2D Arrays
No need to allocate square 2D
arrays:
float **A;
int I;
A = (float **) calloc(5,
sizeof(float *));
for (I = 0; I < 5; I++)
A[I] = (float **)
calloc(I+1,
sizeof(float));
0
4
3
2
1
0 3
2
1
A
4
72. 2-D Array Allocation
Spring 2012 Programming and Data Structure 73
#include <stdio.h>
#include <stdlib.h>
int **allocate(int h, int w)
{
int **p;
int i,j;
p=(int **) calloc(h, sizeof (int *) );
for(i=0;i<h;i++)
p[i]=(int *) calloc(w,sizeof (int));
return(p);
}
void read_data(int **p,int h,int w)
{
int i,j;
for(i=0;i<h;i++)
for(j=0;j<w;j++)
scanf ("%d",&p[i][j]);
}
Allocate array
of pointers
Allocate array of
integers for each
row
Elements accessed
like 2-D array elements.
73. 2-D Array: Contd.
Spring 2012 Programming and Data Structure 74
void print_data(int **p,int h,int w)
{
int i,j;
for(i=0;i<h;i++)
{
for(j=0;j<w;j++)
printf("%5d ",p[i][j]);
printf("n");
}
}
int main()
{
int **p;
int M,N;
printf("Give M and N n");
scanf("%d%d",&M,&N);
p=allocate(M,N);
read_data(p,M,N);
printf("n The array read as n");
print_data(p,M,N);
}
Give M and N
3 3
1 2 3
4 5 6
7 8 9
The array read as
1 2 3
4 5 6
7 8 9
74. Array Pointers
• To declare a pointer to an array type, you must
use parentheses
int (* arrPtr)[10] ; // A pointer to an array of
// ten elements with type int
Spring 2012 Programming and Data Structure 75
75. int *a[10];
• Declares and allocates an array of pointers to
int. Each element must be dereferenced
individually.
int (*a)[10];
• Declares (without allocating) a pointer to an
array of int(s). The pointer to the array must
be dereferenced to access the value of each
element.
• int a[10]; Declares and allocates an array of
int(s).
Spring 2012 Programming and Data Structure 76
76. Array Pointers
int (* arrPtr)[10] ; // A pointer to an array of 10 elements
// with type int
if we assign it the address of an appropriate array,
• *arrPtr yields the array, and
• (*arrPtr)[i] yields the array element with the index i.
Spring 2012 Programming and Data Structure 77
77. int matrix[3][10]; // Array of 3 rows, each with 10 columns.
// The array name is a pointer to the first row.
arrPtr = matrix; // Let arrPtr point to the first row of the matrix.
(*arrPtr)[0] = 5; // Assign the value 5 to the first element of the first row.
arrPtr[2][9] = 6; // Assign 6 to the last element of the last row.
++arrPtr; // Advance the pointer to the next row.
(*arrPtr)[0] = 7; // Assign 7 to the first element of the second row.
++arrPtr; // Advance the pointer to the next row.
(*arrPtr)[0] = 7; // Assign value 7 to the first element of the second row.
Spring 2012 Programming and Data Structure 78
78. int main ( ) {
int i;
int * a[10] ;
printf (“sizeof a = %dn” , sizeof(a));
int x=1, y=2, z=3;
a[0] = &x; a[1] = &y; a[2] = &z;
for (i=0; i<10; i++)
printf ("*a[%d] = %dn", i, *(a[i])) ;
}
Spring 2012 Programming and Data Structure 80
sizeof a = 80
*a[0] = 1
*a[1] = 2
*a[2] = 3
79. int main ( ) {
int i;
int (*b)[10] ;
printf (“sizeof b = %dn”, sizeof(b));
b = malloc (10*sizeof(int)) ;
printf ("b = %pn", b) ;
printf ("b+1 = %pn", b+1) ;
for (i=0; i<10; i++) {
(*b)[i] = i;
printf (“(*b)*%d+ = %dn",i, (*b)[i]) ;
}
}
Spring 2012 Programming and Data Structure 81
sizeof b = 8
b = 0x601010
b+1 = 0x601038
(*b)[0] = 0
(*b)[1] = 1
(*b)[2] = 2
(*b)[3] = 3
(*b)[4] = 4