Arrays & Strings

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 76

ARRAYS

Array is the collection of similar datatype whose


elements are unique and are stored at different-2 memory
locations.
int i=101;
int i=102;
int i=103;
int i=110;

Int i[10];
i[0]=101;
i[1]=102;
i[2]=103;
i[9]=110;
2

Using arrays we can group similar type of data type


Elements of array share the same variable name but each element
has different index number known as SUBSCRIPT
Subscript starts from zero
Array can be 1-d or 2-d
1-d arrays are known as VECTORS OR LINEAR array and 2-d are
known as METRICES.

DATATYPE ARRAYNAME [SIZE];

tells the compiler we are dealing


with arrays,

Key Array Properties

Arrays are defined with [].


Array indices start from 0.
The last element in an array of size N has index N-1.
Array initialisation may be performed using {}.
The elements within an array always starts with 0. If
the array has N elements, the last element is in position
N-1

Declaration of arrays
Like any variable you have to declare an array before use.
Syntax:
Datatype variable-name[size];
ex- float grade[50];
As individual array element can be used anywhere with a
statement such as
g=grade[6];
for(sum=0;i=0;i<50;i++)
sum=sum+grades[i];
5

Inialization of arrays
Type array_name [size]={list of values};
Ex--int number[3]={0,1,2};
Float number [5]={0.0,3.7,8.9};
It will initilize only first 3 elements and rest will be at to zero.
In declaration of an array,the size may be omitted,in such cases
the compiler allocates enough space for all initialized elements.
int number[]={1,1,1,1};
Int number[3]={10,20,30,40};
6

Character Arrays and Strings


Character arrays are special because of their relationship with
strings. More precisely, with string constants.
Can initialise char arrays like ordinary arrays:
char letters[] = { 'a', 'b', 'c', 'd', 'e' };

Can also initialise with a string constant:


char letters[] = "abcde";

Above array is size 6, not 5. Equivalent to:


char letters[] = { 'a', 'b', 'c', 'd', 'e', '\0' };

The following is not an error, but poor style. We get a char


array, not a string.
char letters[5] = "abcde";
7

Elements of local array have garbage value


Elements of global and static arrays are automatically
initialized to zero.
We can explicitly initialize arrays at the time of
declaration.
We cant copy all the elements of an array to another
array by simply assigning it to other array.
int a[5]={1,2,3,4,5};
int b[5];
b=a; //not valid
8

Drawbacks
1.There is no convenient way to initialize only selected
elements.in case we know abt the index of a particular
element only then we can initialize that element acc.to
own choice.
2.There is no shortcut method to initialize a large number
of elements.

Find max.and min.number in an array


main()
{
int i,j,min,max,arr[10]={2,4,9,10,87,92,34,65,79,56};
min=max=0;
for(i=1;i<10;i++)
{
if(arr[i]<min)
min=arr[i];
if(arr[i]>max)
max=arr[i];
}
printf(minimum=%d,maximum=%d,min,max);
}
10

Input value into an array and display them


main()
{
int arr[5],i;
for(i=0;i<5;i++)
{
printf(enter the value for arr[%d],i);
scanf(%d,&arr[i]);
}
printf(the array elements are);
for(i=0;i<5;i++)
{
printf(%d,arr[i]);
printf(\n);
}
}
11

Find out sum of numbers


int n,i,sum=0,a[100];
printf(enter the range);
scanf(%d,&n);
for(i=0;i<n;i++)
{
scanf(%d,&a[i]);
}
for(i=0;i<n;i++)
{
sum=sum+a[i];
}
printf(sum of numbers %d,sum);
12

Calculate the avg marks


main()
{
int marks[5],i;
float avg=0;
for(i=0;i<5;i++)
{
printf(enter values in cell[%d],i);
scanf(%d,&marks[i]);
sum=sum+marks[i];
}
avg=sum/5;
printf(average marks %f,avg);
for(i=0;i<5;i++)
if(marks[i]<avg)
printf(marks in cell [%d]are less than avg,I,marks[i]);
else
printf(marks in cell [%d]are above/equal to avg,I,marks[i]);
}

13

Dynamic memory allocation

Till now static memory allocation. (fixed)


We could not increase or decrease the size of memory during the
execution of program.
In many applications it is not possible to predict how much
memory would be needed by the the program at run time.
int emp_no[200];
In array it is must to specify the size of array and hence there is
wastage of memory.
To overcome of these problems we should be able to allocate
memory at run time.
The process of allocating memory at the time of execution is
called DYNAMIC MEMORY ALLOCATION.

14

The allocation and release of this memory space can


be done with the help of some built in functions whose
prototypes are found in ALLOC.H AND STDLIB.H
These function take memory from memory area called
heap and release this memory whenever not required
so that it can be used again for some other purpose.
We can access dynamically allocated memory only
through pointers so they play very imp.role.

15

Malloc declaration:void *malloc (size_t size);


size specifies the number of bytes to be allocated.
on success malloc() returns a pointer to the first byte
of allocated memory.
The returned pointer is of type void,which can type
cast to appropriate type of pointer:ptr=(datatype *)malloc(specified size);

16

int *ptr;
Ptr=(int *)malloc(10);
We can use SIZE OF operator to make program more readable
ptr=(int *)malloc(5*sizeof(int));
It allocates memory space to hold 5 integers value.
If there is not sufficient memory then malloc return NULL.
ptr=(float *)malloc(10 * sizeof(float));
if(ptr= =NULL)
printf(sufficient memory not available);
Unlike variables and arrays,allocated memory has no name
associated with it so it can be accessed only THRO
POINTERS.
17

main()
{
int *p,n,i;
printf(enter no.of integers to be entered);
scanf(%d,&n);
p=(int *)malloc(n * sizeof(int));
if(p= =NULL)
{
printf(memory not available);
exit(0);
}
for(i=0;i<n;i++)
{
printf(enter the integer);
scanf(%d,p+i);
}
for(i=0;i<n;i++)
{
printf(%d,*(p+i));
}
}

18

CALLOC:Void *calloc(size_t n size_t size);


calloc function is used to allocate multiple blocks of memory
It is similar to malloc()function except for 2 differences
1.

It takes 2 arguments-first argument specifies no.of blocks


and the second specifies the size of each block
Ptr=(int *)calloc(5,sizeof(int));
5 blocks of memory allocated and each block contains 2 bytes.
Calloc function perform calculation for us.

.
19

2. Memory allocated by malloc() contains garbage value


while memory allocated by calloc() is initialized to
zero.
3.Like malloc(),calloc() also returns NULL if there is not
sufficient memory available in the heap.
4.But initialization by calloc()is not very reliable,it is
better to explicitly initialize the elements whenever
there is need to do so.

20

REALLOC( ):- void * realloc(void *ptr,size_t newsize);


We want to increase & decrease the memory allocated by
malloc() or calloc().
realloc() is used to change the size of the memory block.
It alters the size of the memory block without losing of old
data known as REALLOCATION OF MEMORY.
It also take 2 arguments,first is a pointer to the block of
memory that was previously allocated by malloc() or calloc()
And second is the new size for that block.
ptr=(int *)malloc(size);
ptr=(int *)realloc(ptr,newsize);

21

Address of this memory is stored in pointer variable.


New size may be smaller or larger than the old size
If memory is larger,then old data is not lost and the
newly allocated bytes are uninitialized.
Starting address contained in ptr may change if there is
not sufficient memory at the old address to store all the
bytes consecutively.
This function moves the contents of old block into the
new block and the data of the old block is not lost.
Failure-returns NULL

22

main()
{
int I ,*ptr;
ptr=(int *)malloc(5* sizeof(int));
if(ptr= =NULL)
{
printf(memory not available);
exit(0);
}
printf(enter 5 integers);
for(i=0;i<5;i++)
scanf(%d,ptr+i);
ptr=(int *)realloc(ptr, 9* sizeof(int));
if(ptr= =NULL)
{
printf(memory not available);
exit(0);
}
printf(enter more4 integer);
for(i=5;i<9;i++)
{
scanf(%d,ptr+i);
}
for(i=0;i<9;i++)
{
printf(%d,*(ptr+i));
}
}

23

FREE(): Dynamically allocated memory is not automatically


released,it wil exist till the end of program.
It is our responsibility to release that memory so that it
can be reused.
The function free() is used to release the memory space
dynamically.
Memory released by free()is made available to the
heap again and can be used for some other purpose.
free(ptr);
We dont get any error if we dont free the dynamically
allocated memory,but this would lead to MEMORY
LEAK. Memory is slowly leaking away and can be
reused only after the termination of program.
24

func()
{
space for 10 int will reserve
int *ptr;
ptr=(int*)malloc(10* size of(int));
.
}
All local variable vanish when function terminates and since ptr
is a local variable so it will deallocated at the termination of
function.
But space allocated dynamically is not deallocated automatically
so that space remains there leading to memory leak.
We should free memory space by putting a call to free( )at the
end of function.
It is valid to return a pointer to dynamically allocated memory
because the space allocated dynamically is not released after
termination of function.
25

26

2-D arrays
int i,j,a[3][3];
printf(enter matrix);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf(%d,&a[i][j]);
}
}
printf(the entered matrix);
for(i=0;i<3;i++)
{
for(j=0;j<3j++)
{
printf(%d,a[i][j]);
}
}

Col 0
[0][0]
row 0

310

[1][0]
row1

100

789

col 2
[0][2]
276

[1][1]

[1][2]

456

[2][0]
row2

col 1
[0][1]

567

780

[2][1]
456

[2][2]
123

27

28

Pointers and arrays

An array is in reality a pointer:


int a[10], y;
int* px;
px = a;
/* px points to a[0] */
px++;
/* px points to a[1] */
px=&a[4];
/*px points to a[4] */
y = *(px+3); /*y gets the value in a[3] */
The pointer arithmetic in C guarantees that if a pointer is
incremented or decremented,the pointer will vary according to
its type.
For instance, if px points to an array,px++ will always yield the
next element independently of what is the type stored in
29

Pointers and arrays


Address
&a[0]
&a[1]
&a[2]

value
a[0]
a[1]
a[2]

address
a+0
a+1
a+2

value
*a
*(a+1)
*(a+2)

30

Pointer to a group of continuous 1-D array


DATA-TYPE (*ARRAY-NAME) [COLUMN-SIZE];
int a[2][6];
It can be explained in terms of pointers as:int (*a)[6];
Here ais a pointer to a group of 1-D 6 elements of integer array.
a is pointer to the row 0 of 6 element array.
a+1 is pointer to row 1 of 6 element array.
*a is a pointer to the element 0 in 0th row.
*(a+1) is pointer to the element 0 in 1st row.
*(*(a+2)+3) is the value in column 3 of the row 2.

31

Array of pointers
int *a[2][5];
It can be explained in terms of pointers as:int (*a)[5]; //[ ] has higher precedence than *
a[0] points to 1st element in 0th row.
a[1] points to 1st element in 1st row.
a[2] points to 1st element in the 2nd row.
a([2]+3) points to 3rd element in 2nd row.
*(a[2]+3) points to valus of 3rd element in 2nd row.
32

Pointer to 1-D array


main()
{
int a[4]={1,2,3,4};
for(i=0;i<3;i++)
{
printf(%da+i);
printf(%d,*a+i);
}
33

Reverse the no.using pointers


main()
{
int a[5]={10,20,30,40,50};
int i,n,*p;
p=a;
n=5;
printf(data is);
for(i=0;i<n;i++)
{
printf(%d,*(p+i));
}
printf(reverse data);
for(i=n;i>0;i--)
{
printf(%d,*(p+i));
}
34

main()
{
int arr[4][2]={ {156,90},
{456,67},
{134,45},
{890,32} };
int i,j;
for(i=0;i<4;i++)
{
for(j=0;j<2;j++)
{
printf(%d, *(*(arr+i)+j));
}
}
35

Pointer to 2-D array


main()
{
int a[3][3]={ {3,5,9},
{ 4,6,7},
{9,4,6} };
int i,j=1;*p;
printf(elements of an array with their addresses);
p=&a[0][0];
for(i=0;i<9;i++;j++)
{
printf(%d,%u,*(p),p);
p++;
if(j= =3)
{
printf(\n);
j=0;
}}}
36

37

Using array itself as a pointer


#include<stdio.h>
#include<conio.h>
void main()
{
int i;
int a[][3]={{1,2,3},{4,5,6},{7,8,9}};
clrscr();
printf(\t elements of an array their addresses\n);
for(i=0;i<9;i++)
{
printf(%8u,&a[0][0]+i);
printf( [%d],*(&a[0][0]+i));
if(i==2 || i==5)
printf(\n);
}
getch();
}

38

Array of pointers
main()
{
int *arrp[3];
int arr[3]={5,10,15},i;
for(i=0;i<3;i++)
arrp[i]=arr+i;
printf(address and element);
for(i=0;i<3;i++)
{
printf(%u,arrp[i]);
printf(%d,*(arrp+i));
}
}
Output : 5 10 15
39

Passing array as args to function


main()
{
int arr[4]={1,2,3,4};
int Sum(arr);
exit(0);
}
int sum(int a[])
{
int sum=0,i;
for(i=0;i<3;i++)
{
sum=sum+a[i];
}
printf(%d,sum);
}

/*calling function*/

pass array as arguments

/*function definition*/

40

Pointer to function
main()
{
int mul( ),(*p)( ),x,y,z;
sacnf(%d%d,&x,&y);
p=&mul;
z=(*p)(x,y);
printf(%d,z);
getch();
}
int mul(int p,int q)
{
int m=p*q;
return(m);
}
41

STRING
String is collection of Characters (or ) group of elements in which
symbols enclosed within quotation marks.
String is always declared as character arrays.
in other words character arrays are called as STRINGS.
Every string is terminated with \0( NULL)character.
char name[ ]={I,n,d,I,a,\0};

42

interpretation
Arrays whose elements are characters called as string

Strings are always terminated with a NULL character


('\0' or 0)
char a[]="hello\n";

/* size? */

43

String Initialization
Initialization
char m[9] = I like C;
char m[ ] = I like C;
char m[ ] = { I, , l, i, k, e, ,C };
char m[ ] ={ { I },{ l },{ i },{ k },{ e },{ u } };

44

main()
{
char name1[9] = I like C;
char name2[9 ] ={ { I },{ l },{ i },{ k },{ e },{ u } };
char name3[9 ] = { I, , l, i, k, e, ,c,\0 };
clrscr();
printf(name1=%s,name1);
printf(name1=%s,name1);
printf(name1=%s,name1);
}

45

Print the elements of char array


main()
{
char str[15]=have a nice day;
int i=0;
while(i<=15)
{
printf(%c,str[i]);
i++;
}
}
46

Print the elements of char array


main()
{
char str[ ]=have a nice day;
int i=0;
while( str[i]!=\0)
{
printf(%c,str[i]);
i++;
}
}
47

Standard string functions


Strlen :-determines length of string
Strcpy :-copies a string from source to destination
Strncpy:-copies char of string to another string upto
specific length
Strcmp:-compare char of 2 strings
Stricmp:-compare 2 strings
Strncmp:-compare char of 2 strings upto specific
length
Strnicmp:-compare char of 2 strings upto specific
length .Ignore case.
48

Strlen function
It counts the number of characters in a given string.

49

To count no of chars in a given string


main()
{
char str[10];
int length;
printf(enter string);
gets(str);
length=strlen(str);
printf(length of string=%d,length);
}
50

Strcpy function
This function copies the contents of 1 string to another.
strcpy(s2,s1);
S1 =source string
S2 =destination string
S1 is copied to s2.

51

To copy contents of 1 string to other


main()
{
char s1[10],s2[10];
printf(enter string);
gets(s1);
strcpy(s2,s1);
printf(first string,s1);
printf(second string,s2);
}

main()
{
char s1[10],s2[10];
int i;
printf(enter string);
gets(s1);
for(i=0;i<10;i++)
s2[i]=s1[i];
printf(first string,s1);
printf(second string,s2);
}

52

Copy contents upto a specific length


main()
{
///////strncpy function/////////////
char str1[10],str2[10];
int n;
printf(enter source string);
gets(str1);
printf(enter destination string);
gets(str2);
Printf(enter no. of char to be replaced);
Scanf(%d,&n);
strncpy(str2,str1,n);
printf(first string,str1);
printf(second string,str2);
}
53

Stricmp function
This function compares 2 strings.it compares 2 strings
without knowing upper case and lower case.if strings
are same then it returns to 0 otherwise non-zero value.
diff=stricmp(str1,str2);
if(diff= =0)
puts(strings are equal);
else
puts(strings are not equal);
54

Strcmp function
This function compares 2 strings.it compares 2 strings
and also check the upper case and lower case. if strings
are same then it returns to 0 otherwise non-zero value

diff=strcmp(str1,str2);
if(diff= =0)
puts(strings are equal);
else
puts(strings are not equal);
55

Pointers and Efficiency


Pointers were once important for their ability to produce more
efficient (faster) code than array indexing.
Modern optimising compilers have reduced this importance. A
good compiler would produce the same executable code for all
three implementations of strcpy().
Avoid writing obscure pointer code just for efficiency.
Use pointers when:
They make code simpler, more concise, and more readable.
They are required for operations that cannot be done otherwise (e.g.,
pass by reference semantics).
56

String Constants
String constants are different to all other constant types (e.g.,
character, float, short, enum, int, etc).
All other constants are not allocated memory, and do not have an
address. That is, they are not variables.
double *pval1 = 9.6;
/* Invalid. Won't compile. */
double *pval2 = &9.6;
/* Invalid. Won't compile. */
int *parray = { 1, 2, 3 }; /* Invalid. Won't compile. */

String constants are allocated memory with static


extent. They have an address and so can be pointed to.
However, memory cannot be changed.
char *str = "Hello World!\n"; /* Correct. But read-only. */
57

Properties of String Constants

Memory region is read-only. Cannot change elements of a string constant.


char *str = "This is a string constant";
str[11] = 'p'; /* Undefined behaviour. */

Memory has static extent. Can return a pointer to a string constant from a function.
char * getHello()
/* Return a pointer to an array defined within
the function */
{
char *phello = "Hello World\n";
return phello;
}

String constant expression defines a pointer to the beginning of constant array. Can
index string constant directly. Show print_base_b().
58

Aside: String Constant Concatenation

String constants may be concatenated at compile time. This is useful for writing a long
string as the following is illegal.
"this is
a string"

To string constants are concatenated if they are adjacent.


"this is " "a string"
"this is"
"a string"

Another way to write multiple line strings is to use a \


"this is \
a string

For this \ form, the second line must appear on the first column, else the
intervening white-space will be added to the string.
The string concatenation form is preferred over the \ form.

59

Character arrays
A character array may be initialised with a string constant.
char string[] = a string;

The result is read-writable. Why?


Compiler allocates memory for array and then copies the
elements of the string constant into the array.
Initialisation of char array by string constant is the only time the
compiler does copying for you. In every other situation you have
to
Copy elements across one-at-a-time (eg, in a for loop).
Use a function like strcpy() or memcpy() to copy the elements
across.
60

Summary
The following are a selection of valid array
operations.
short val = 9;
short *pval = &val;
double array[] = { 1.0, 2.0, 3.0 };
double *parray = array;
char str[] = "Hello World!\n"; /* readwrite. */
str[1] = 'u';
61

Strings and the Standard Library


<string.h>

size_t strlen(const char *s)


char *strcpy(char *s, const char *t)
char *strncpy(char *s, const char *t, size n)
into strcmp(const char *s, const char *t)
int strncmp(const char *s, const char *t, size_t n)
char *strcat(char *s, const char *t)
char *strncat(char *s, const char *t, size_t n)
char *strchr(const char *s, int c)
char *strrchr(const char *s, int c)
char *strstr(const char *s, const char *t)
<stdio.h>
int sprintf(char *s, const char *format, )
62

Characters and the Standard Library


<ctype.h>
Recall that characters are represented by an integer code, usually ASCII.
int
int
int
int
int
int
int
int
int

isupper(int
islower(int
isalpha(int
isdigit(int
isalnum(int
isprint(int
isgraph(int
ispunct(int
isspace(int

c)
c)
c)
c)
c)
c)
c)
c)
c)

(printable character, including space )


(printable character, except space )
(printable character, except space or letter or digit)
(space, newline, carriage return, form feed, tab, vertical tab )

int toupper(int c)
int tolower(int c)
63

Arrays of Pointers
Pointers are themselves variables. Can have an array of
pointers.
int *parray[N];

Each pointer behaves as an ordinary pointer


double val = 9.7;
double array[] = { 3.2, 4.3, 5.4 };
double *pa[] = { &val, array+1, NULL };
64

Using Pointer Arrays as Arrays of Arrays


int
int
int
int
int
int

a1[] = { 1, 2, 3, 4 };
a2[] = { 5, 6, 7 };
*pa[] = { a1, a2 };
**pp = pa;
*p = pa[1];
val;

val
val
val
val
val
val

=
=
=
=
=
=

pa[1][1];
pp[1][1];
*(pa[1] +
*(pp[1] +
*(*(pp+1)
p[1];

/* equivalent operations */
1);
1);
+ 1));

Notice that pa and pp are equivalent in an expression, but pa is


an array name and pp is a pointer variable. They are different.
65

Why use Arrays of Pointers?


Pointer arrays are useful for grouping related pointers
together.
Pointers to large objects (structs, etc).
Pointers to arrays (can produce matrix-like objects).
Pointers to functions.

Most interesting applications of pointer arrays involves


dynamic memory allocation (malloc(), free(),
etc), which we will discuss next lecture.
Simple example, program to print months of year
66

Arrays of Function Pointers


Arrays of function pointers are useful for creating dispatchtables, where an array index specifies which function to invoke.
Basic syntax:
int (*pf[10])(char *);
Array of size 10 of function pointers, where each function has
interface: takes char *, returns int.
Notice, an array of function pointers can only point to functions
of the same interface specification.
Example program, simple arithmetic operations
67

Complicated Declarations and typedef


Some C declarations, when combined together, can get
very complicated. Particularly when they involve
pointers to functions.
Complexity can be reduced by using typedef.
The keyword typedef is used to create new datatype names.
typedef char * String;
String message = "This is a string.";

68

Example use of typedef


In the previous example program, we had the following array-offunction-pointers declaration:
double (*pf[])(double,double) = { add, sub, mult, div };

Using typedef, we can break this up into:


typedef double (*Arithmetic)(double,double);
Arithmetic pf[] = { add, sub, mult, div };

Complicated declarations are rare in C, but they do occur.


Declarations can get much more complicated than this example
More on typedef in a later lecture.
69

Multi-dimensional Arrays
C provides rectangular multiple-dimensional arrays.
These are not to be confused with arrays of pointers to arrays.
Multi-dimensional arrays are defined by multiple square
brackets [][].
float
{
{
{
};

matrix[3][4] =
2.4, 8.7, 9.5,
6.2, 4.8, 5.1,
7.2, 1.6, 4.4,

{
2.3 },
8.9 },
3.6 }

The initialisation list for the array consists of nested braces for
each row of the array.
70

Multi-dimensional Arrays: Memory Layout


Multi-dimensional Arrays are laid out in memory as a 1-D array
with each row adjacent to the next.
float matrix[3][4] = {
{ 2.4, 8.7, 9.5, 2.3 },
{ 6.2, 4.8, 5.1, 8.9 },
{ 7.2, 1.6, 4.4, 3.6 }
};
float onedmatrix[12] = {
2.4, 8.7, 9.5, 2.3, 6.2, 4.8, 5.1, 8.9, 7.2, 1.6, 4.4, 3.6
};

71

M-D Arrays with Unspecified Size


As for 1-D arrays, and M-D array can be defined
without a specific size provided it has an initialiser list.
However, only the left-most subscript may be
unspecified.
float matrix[][4] = {
{ 2.4, 8.7, 9.5, 2.3 },
{ 6.2, 4.8, 5.1, 8.9 }
};
72

M-D Array Element Access


Access uses separate []-brackets for each dimension.
This differs from many other languages which use
comma separated subscripts (,).
float a = matrix[1][2]; /* Correct. */
float b = matrix[1,2]; /* Wrong. */

Example program. Matrix multiplication (Note


interface to multiply()).
73

Higher Dimensions
M-D arrays can be higher than just 2-D.
short
{
{
{
{
};

array3d[4][2][3] = {
{ 0, 1, 2 }, { 3, 4, 5 }
{ 6, 7, 8 }, { 9, 10, 11 }
{ 12, 13, 14 }, { 15, 16, 17 }
{ 18, 19, 20 }, { 21, 22, 23 }

},
},
},
}

The left-most subscript may be free, but the others


must be fully specified.
short array3d[][2][3] = { };
74

Similarities Between Arrays of Pointers and


M-D Arrays
Arrays of pointers and M-D arrays are similar enough to
confuse most novice C programmers. But they are not the same.
Consider the following:
char
char
char
char

a[] = { 1, 2, 3 };
b[] = { 4, 5, 6 };
*c[] = { a, b };
d[][3] = { { 1, 2, 3 }, { 4, 5, 6 } };

Subscripts c[i][j] and d[i][j] will give the same results.


75

Differences Between Arrays of Pointers and


M-D Arrays

M-D arrays:
1.
2.
3.

Pointer arrays:
1.
2.
3.

Contiguous region of memory. Rows laid out adjacently.


Each row is of the same length. Array is rectangular.
Left-most subscript must be specified when passed to a function.
Each pointer may point to a completely different region of memory.
Non-contiguous.
Each pointer may point to an array of different length. For example, an
array length N, an isolated (non-array) variable, and NULL.
A pointer array may be passed to a function with no size specifications
whatsoever. Can be passed as a pointer-to-a-pointer if desired.

Generally, arrays of pointers are more useful than M-D arrays.


They are more flexible, and often more efficient.
76

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy