ARRAYS, STRINGS, POINTERSclass PDF
ARRAYS, STRINGS, POINTERSclass PDF
Introduction
• basic data types in C (char, int, float, double),
• also supports some advanced data constructs.
• An array - group together a list of values, all of the same
type, under one variable name.
• A structure - group together an assortment of values of
different types under a single variable name. Like an array,
it makes it easier to code computations.
• A string - group together a series of character symbols
under one variable name. closely related to an array, but
because it is intended only for text data, a number of
functions have been crafted to perform text-specific
operations on strings.
• A pointer -holds the address of another variable, to provide
a “gateway” or path of indirect access to the other variable.
It is used most often in passing values between pieces of
code (functions).
1. Arrays
• A construct used to store a set of values using only one variable name.
• Each of the values occupies a cell. Every cell in the array is the same size,- it
occupies the same amount of memory.
• The size of each cell is dictated by the data type (char, int, float, double) given in
the variable declaration.
• The number of cells is also given in the variable declaration. Here are some
examples:
• Cells are accessed using indices, with syntax similar to that used in the variable
declarations.
• Array bounds for an array say an Array[x] is;
0 to x (total number of cells in array) -1.
Multidimensional Arrays
• computer memory is all arranged in one dimensional order, as though it were one
long street of bytes.
• cells in the multidimensional array are listed out, one at a time, in one-dimensional
order. For example, consider the following code:
int a[3][2];
a[0][1]=7;
a[1][0]=13;
• There are a total of 6 cells in this array. They are listed in order by cycling through
the range on the rightmost index, incrementing the next index to the left when
done.
• The same procedure works for any number of dimensions.
• The order of incrementing dimension indices is similar to how base 10 numbers
are counted, cycling through the one’s digit before incrementing the ten’s digit,
then cycling through the ten’s digit before incrementing the hundred’s digit, and so
on.
• NOTE: Everything stored in computer memory is somehow stretched out in one-
dimensional order.
• Things not typically viewed as one-dimensional, such as images, video, databases,
maps, and three dimensional models are all actually stored by listing out the data
in one-dimensional order.
STRINGS
• A specific type of array; of char, containing a sequence of values
where a value of ‟\0‟ signifies the end of the string.
• could be of any size, but it is assumed that the valid data in the
array starts at the first cell, and ends with the first cell having a
value of ‟\0‟.
• For example:
char d[8];
d*0+=’H’; d*1+=’e’; d*2+=’l’; d*3+=’l’; d*4+=’o’; d*5+=’\0’; /* ’\0’ indicates
the end of string */
• Although the array has eight cells, only the first six are used.
• The cell containing the ‟\0‟ character is not seen during either
printing or the scanning of input. It is a nonprintable character used
to control how text data is processed.
• Any code working on a string is supposed to stop processing the
array when the ‟\0‟ character is reached.
The “\0” character
• The value of the ‟\0‟ character is zero. ‟\0‟ is simply another way
of saying zero. used to specify a specific “type” of zero.
• ‟\0‟ is a way to say zero for a char representing an ASCII symbol
that means end of string.
• Zero has another alias called NULL.
• NULL is usually used to indicate a value of zero for an address, but it
is sometimes used for the end of string character.
• Any of these aliases can be used; they all result in the same bit
pattern being placed in the cell, which is all zeros. For example, all
of the following lines of code are equally valid and do the exact
same thing:
• The syntax &x is used to identify the address of x, assume is 400. The
syntax &f identifies the address of f, which is 404,(assuming its the address
that immediately follows) and &(s[0]) identifies the address of s[0], which
is 408.
• The variable name s is simply a shorthand for writing &(s[0]).
• scanf()with %s identifier -stores a series of characters, ending it with a
value of zero.
• it must be given an address, where the storing of characters is to start.
Multidimensional Strings
• One of the common uses for multidimensional arrays is to store a list of
strings.
• Since each string is a one-dimensional array, a list of strings requires a
two-dimensional array. For
• example:
char n[2][4];
n*0+*0+=’T’; n*0+*1+=’o’; n*0+*2+=’m’; n*0+*3+=0;
n*1+*0+=’S’; n*1+*1+=’u’; n*1+*2+=’e’; n*1+*3+=0;
Strings Comparison
(meaning)
“Hello” vs. “Hello” 0 (same)
“Hello” vs. “Hellp” −1 (first string smaller)
“Hey” vs. “Hallo” 1 (second sting
smaller)
“Hillo” vs. “Hi” 1 (second sting smaller)
• We can compare two strings using the following code:
int i,a;
char s[4],t[4];
a=strcmp(s,t);
• This saves us slightly more code than the strlen() function, but like
strlen(), its real value lies in repeated use.
String Copy: strcpy()
• To copy the contents of a string to a second string variable.
int i;
char s[4],t[4];
s*0+=’S’; s*1+=’u’; s*2+=’e’; s*3+=’\0’;
i=0;
while (s*i+ != ’\0’)
t[i]=s[i];
i++;
t*i+=’\0’;
• Alternatively, by calling the strcpy() function:
int i;
char s[4],t[4];
strcpy(t,s);
• The source string -2nd in the argument list; destination
string -1st.
String Concatenate: strcat()
• To append a string (the addendum) to the end
of another string (the original).
• performed by calling the strcat() function:
strcat(s,t);
• The original string - first in the argument list;
the addendum string comes second.
• The result is placed in the original string
variable.
String Print: sprintf()
• works just like the printf() function, except that the output
“prints” into a string variable.
• can be useful for converting numeric data types into ASCII
text, or for creating long strings from multiple components.
• For example:
char a[24];
float f;
int i;
f=3.72;
i=9;
sprintf(a,"Price %f, qty %d",f,i);
printf("%s\n",a);
• The output of this code is: Price 3.720000, qty 9
• The memory map for this code is revealing; it
highlights the difference between text-storage
and value storage of numbers:
String Functions Example
Code to demonstrates several string functions, together in a program:
#include <stdio.h>
if (strcmp(test,"0") == 0)
/* for printf(), scanf() */
#include <string.h> break;
/* for strlen(), strcmp() */ if (strlen(test) < strlen(look))
main() printf("%s is too short for
{ %s\n",test,look);
char else if (strcmp(test,look) == 0)
look[80],test[80]; printf("Found one!\n");
printf("Look for: "); else if (strncmp(test,look,3) == 0)
scanf("%s",look); printf("Started the same...\n");
while (1) else
{
printf("Not what we’re looking for\n");
printf("Enter a string (0 to quit):
"); }
scanf("%s",test); }
Command Line Arguments
• anything typed at the shell prompt after the
name of the program to execute.
• typically used to provide information about
how the user wishes to run a program. For
example:
Myname@myComputer>$ ls –l -t
• This example shows two command line
arguments; it is possible to have any number.
They must be separated from each other by
one or more spaces.
The full function declaration for main
i. makes a program aware of its command line arguments.
ii. Define’s when executed, into what variables are the values for
the command line arguments placed.
• The full function declaration for main():
int main(int argc, char *argv[])
• main has two parameters, int argc and char *argv[].- are
the only parameters that are allowed in main and are used
in the following ways
– The variable argc- the argument count and passes the number
of arguments passed at the command line i.e. stores the
number of command line arguments including the name of the
program).
– char * argv is a pointer to a list of command line arguments
which may be accessed as if they were a series of strings. The
variable argv stores a list of strings, one string per command line
argument. argv can be accessed just like a two-dimensional
array.
Example
• For example, the following code prints out all the command line
arguments, one character at a time:
int i,j;
for (i=0; i<argc; i++)
{
j=0;
while (argv*i+*j+ != ’\0’)
{
printf("argument No. %d = %c\n" i,argv[i][j]);
j++;
}
printf("\n");
}
• Each string can be accessed through its own address label, so that the
code example just given can be simplified as follows:
for (i=0; i<argc; i++)
printf("argument no. %d = %s\n",i,argv[i]);
Pointers and structures
• Structures can contain pointers, even a pointer to
another instance of the same structure. In the
following example:
struct node {
struct node *next_ptr; /* Pointer to the next
node */
int value; /* Data for this node */
}
• This structure contains two fields, one named value
• The other is a pointer to another structure.
Creating nodes
• We could declare them explicitly:
struct node *node_1;
struct node *node_2;
• problem with this structure is that we can declare only a limited
number of nodes.
• We need is a procedure to which we can say, "I want a new node,"
and then have the procedure create the node for us.
• The procedure malloc does the job. It allocates storage for a
variable and then returns a pointer. It is used to create new things
out of thin air (actually out of an area of memory called the heap).
• Up to now, we've used pointers solely to point to named variables.
So if we used a statement like:
int data;
int *number_ptr;
number_ptr = &data;
the thing that we are pointing to has a name (data).
malloc
• The function malloc creates a new, unnamed variable and returns a
pointer to it.
• The "things" created by malloc can be referenced only through
pointers, never by name.
• The definition of malloc is:
void *malloc(unsigned int);
• The function malloc takes a single argument: the number of bytes
to allocate.
• If malloc runs out of memory, it returns a null pointer.
• void * is used to indicate that malloc returns a generic pointer (a
pointer that can point to any type of thing).
• Note: C uses void for two purposes:
– When used as a type in a function declaration, void indicates that the
function returns no value.
– When used in a pointer declaration, void defines a generic pointer.
Example : Allocating Memory for a
String
[#include <stdlib.h>]
main()
{
/* Pointer to a string that will be allocated
from the heap */
char *string_ptr;
string_ptr = malloc(80);
Suppose we are working on a complex database
that contains (among other things) a mailing list.
The structure person is used to hold the data for
each person:
struct person {
char name[30]; /* name of the person */
char address[30]; /* where he lives */
char city_state_zip[30]; /* Part 2 of address */
int age; /* his age */
float height; /* his height in inches */
}
Creating new
• We could use an array to hold our mailing list, but an array
is an inefficient use of memory. Every entry takes up space,
whether or not it is used. What we need is a way to allocate
space for only those entries that are used. We can use
malloc to allocate space on an as-needed basis.
• To create a new person, we use the code:
/* Pointer to a person structure to be allocated from the heap
*/
struct person *new_item_ptr;
new_item_ptr = malloc(sizeof(struct person));