C Language Review In-depth Study: Arrays and Pointers

Posted by axiom82 on Sat, 18 Jan 2020 02:40:05 +0100

C Array

Arrays are sequential collections that store a series of variables of the same type.All arrays consist of contiguous memory locations.

Declare Array

You need to specify the type and number of elements

type arrayName [ arraySize ];

Initialize Array

//The number of values between braces {} cannot be greater than the number of elements specified in square brackets [] when the array is declared.
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
//The size of the array is omitted, and the size of the array is the number of elements at initialization.
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
//Assigning a value to an element in an array
balance[4] = 50.0;

Array elements can be accessed by indexing the array name.

Multidimensional Array

The general form of a multidimensional array declaration is as follows:

type name[size1][size2]...[sizeN];

A two-dimensional array, essentially, is a list of one-dimensional arrays that are declared and initialized:

int a[3][4] = {  
 {0, 1, 2, 3} ,   /*  Initialize row with index number 0 */
 {4, 5, 6, 7} ,   /*  Initialize row with index number 1 */
 {8, 9, 10, 11}   /*  Initialize row with index number 2 */
};
//Nested brackets inside are optional, and the following initialization is the same as above
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Pass an array to a function

To pass an array as a parameter in a function, you must declare the function parameter in three ways.The result of these three declarations is the same, because each tells the compiler that it will receive an integer pointer.

1. A formal parameter is a pointer:

void myFunction(int *param) 
{ 
body of function
 }

2. A formal parameter is an array of defined sizes:

void myFunction(int param[]) 
{ 
body of function
 }

3. A formal parameter is an array of undefined sizes:

void myFunction(int *param) 
{ 
body of function
 }

Return Array from Function

To return a one-dimensional array from a function, you must declare a function that returns a pointer,:

int * myFunction()
{
 body of function
}

C does not support returning the address of a local variable outside of a function unless a local variable is defined as a static variable.

Example:

/*
Returns an array of 10 random numbers from a function
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
/* Functions to generate and return random numbers */
int * getRandom( )
{
  static int  r[10];
  int i;
 
  /* Set Seed */
  srand( (unsigned)time( NULL ) );
  for ( i = 0; i < 10; ++i)
  {
     r[i] = rand();
     printf( "r[%d] = %d\n", i, r[i]);
 
  }
 
  return r;
}
 
/* To call the main function of the function defined above */
int main ()
{
   /* A pointer to an integer */
   int *p;
   int i;
 
   p = getRandom();
   for ( i = 0; i < 10; i++ )
   {
       printf( "*(p + %d) : %d\n", i, *(p + i));
   }
 
   return 0;
}

Pointer to array

The array name is a constant pointer to the first element in the array.

double *p;
double balance[10];

p = balance;

Balance is a pointer to &balance[0], the address of the first element of the array balance.Assign p to the address of the first element of balance.It is legal to use array names as constant pointers and vice versa.Therefore, * (balance + 4) is a legitimate way to access balance[4] data.

Be careful:

1. *p+4 is the pointer to the first address of the balance array (&balance[0]), *p is the element value of the first address (*to the right of the assignment symbol and in the expression), and adding 4 is balance[0] +4.

2. *(p+4) means that P is the pointer to the first address of the balance array (&balance[0]), p+4 means the address plus 4, * and then p+4, so * (p+4) means balance[4] (the value of the fifth element).

 

C Enumeration

Enumeration is a basic data type in C.Enumeration grammar is defined in the following format:

enum enumName {enum1,enum2,......};

You can change the value of an enumerated element when defining an enumeration type. An enumerated element with no specified value has the value of the previous element plus 1.The default value of the first enumerated member is 0 of integer type, and the value of subsequent enumerated members is added 1 to the previous member.

Definition of enumeration variable

There are three ways to define an enumeration variable

1. Define the enumeration type before defining the enumeration variable

enum DAY
{
      MON=1, TUE, WED, THU, FRI, SAT, SUN
};
enum DAY day;

2. Define both enumeration types and enumeration variables

enum DAY
{
      MON=1, TUE, WED, THU, FRI, SAT, SUN
};
enum DAY day;

3, omit the enumeration name and define the enumeration variable directly

enum
{
      MON=1, TUE, WED, THU, FRI, SAT, SUN
} day;

In C, enumeration types are treated as ints or unsigned int s, so it is impossible to traverse them according to the C language specification.However, in some special cases, conditional traversal is possible when the enumeration type is continuous.

Example (use for to traverse enumerated elements):

#include<stdio.h>
 
enum DAY
{
      MON=1, TUE, WED, THU, FRI, SAT, SUN
} day;
int main()
{
    // Traverse Enumeration Elements
    for (day = MON; day <= SUN; day++) {
        printf("Enumeration Elements:%d \n", day);
    }
}

The enumeration type is not continuous and cannot be traversed. Example:

enum
{
    ENUM_0,
    ENUM_10 = 10,
    ENUM_11
};

 

C. Pointer

It is necessary to learn the pointer of C language.It not only simplifies tasks, but also allows dynamic memory allocation, which cannot be performed without a pointer.Variables have memory locations, and variables define addresses that can be accessed using hyphens (&) operators.

What is a pointer?

A pointer is a variable whose value is the address of another variable, the direct address of the memory location.So the value of the pointer is the address of the variable it points to.

The general form of a pointer variable declaration is:

type *var-name;

All pointers have the same type of value, which is a hexadecimal number that represents the memory address.The data type of the variable or constant pointed to by the pointer is different.

How to use the pointer?

1. Define a pointer variable

2. Assign variable addresses to pointers

3. Access the value of the address available in the pointer variable.

These return the value of a variable at the address indicated by the operand by using the unary operator *.Examples are as follows:

#include <stdio.h>
 
int main ()
{
   int  var = 20;   /* Declarations of Actual Variables */
   int  *ip;        /* Declaration of pointer variable */
 
   ip = &var;  /* Store var's address in pointer variable */

   /*Use variable address & */
   printf("Address of var variable: %p\n", &var  );
 
   /* Address stored in pointer variable */
   printf("Address stored in ip variable: %p\n", ip );
 
   /* Use pointer access values (* is the value for the corresponding memory address) */
   printf("Value of *ip variable: %d\n", *ip );
 
   return 0;
}

NULL pointer in C

When declaring pointer variables, it is a good programming practice to assign a NULL value to pointer variables without an exact address.A pointer assigned a NULL value is called a null pointer, and the address that the null pointer points to is 0x0.

A null pointer is a constant with a value of zero defined in the standard library.On most operating systems, programs do not allow access to memory with address 0 because it is reserved by the operating system.

However, memory address 0 is particularly important because it indicates that the pointer does not point to an accessible memory location.By convention, however, if the pointer is Null (Null), it is assumed that it does not point to anything.

pointer arithmetic

The C pointer is a numeric address.Therefore, you can perform arithmetic operations on the pointer.Four arithmetic operations can be performed on the pointer: ++, --, +, -.

ptr++

Assume that ptr is an integer pointer to address 1000 and a 32-bit integer. Each time ptr is added, it will point to the next integer position. If ptr points to a character with address 1000, the operation above will cause the pointer to point to position 1001, because the next character position is at 1001.

Incremental or Decreasing Variable Pointer

Access each element in the array:

/*Pointer incremental traversal*/
#include <stdio.h>
 
const int MAX = 3;
 
int main ()
{
   int  var[] = {10, 100, 200};
   int  i, *ptr;
 
   /* Array address in pointer */
   ptr = var;
   for ( i = 0; i < MAX; i++)
   {
 
      printf("Storage address: var[%d] = %x\n", i, ptr );
      printf("Stored value: var[%d] = %d\n", i, *ptr );
 
      /* Move to Next Location */
      ptr++;
   }
   return 0;
}

/*Pointer descending traversal*/
#include <stdio.h>
 
const int MAX = 3;
 
int main ()
{
   int  var[] = {10, 100, 200};
   int  i, *ptr;
 
   /* The address of the last element in the pointer */
   ptr = &var[MAX-1];
   for ( i = MAX; i > 0; i--)
   {
 
      printf("Storage address: var[%d] = %x\n", i-1, ptr );
      printf("Stored value: var[%d] = %d\n", i-1, *ptr );
 
      /* Move to Next Location */
      ptr--;
   }
   return 0;
}

Pointer comparison

Pointers can be compared using relational operators, such as==, <and>.Direct pointer comparison is address size comparison.You need to compare the values of the variables pointed to by the pointer. You can use the * sign to make the comparison.Modify the code above for incremental access to array elements, and increment the variable pointer by pointing to an address less than or equal to the address of the last element of the array &var[MAX-1], as follows:

#include <stdio.h>
 
const int MAX = 3;
 
int main ()
{
   int  var[] = {10, 100, 200};
   int  i, *ptr;
 
   /* Address of the first element in the pointer */
   ptr = var;
   i = 0;
   while ( ptr <= &var[MAX - 1] )
   {
 
      printf("Address of var[%d] = %x\n", i, ptr );
      printf("Value of var[%d] = %d\n", i, *ptr );
 
      /* Point to the previous location */
      ptr++;
      i++;
   }
   return 0;
}

Pointer Array

Declarations of pointer arrays:

type *pointerArrayName[size];

//For example, declare an array of 10 pointers to integers:
/*int *ptr[10];*/

The following example uses three integers, which are stored in an array of pointers as follows:

#include <stdio.h>
 
const int MAX = 3;
 
int main ()
{
   int  var[] = {10, 100, 200};
   int i, *ptr[MAX];
 
   for ( i = 0; i < MAX; i++)
   {
      ptr[i] = &var[i]; /* Addresses assigned to integers */
   }
   for ( i = 0; i < MAX; i++)
   {
      //ptr[i] is the pointer in the pointer array, which is the address of an integer; * fetch the value for the address where the pointer points to an integer
      printf("Value of var[%d] = %d\n", i, *ptr[i] );
   }
   return 0;
}

You can also store a list of strings with an array of pointers pointing to the characters as follows: (A little questionable, follow-up)

#include <stdio.h>
 
const int MAX = 4;
 
int main ()
{
   const char *names[] = {
                   "Zara Ali",
                   "Hina Ali",
                   "Nuha Ali",
                   "Sara Ali",
   };
   int i = 0;
 
   for ( i = 0; i < MAX; i++)
   {
      //Names[i] is an element in the pointer value *names[], a character pointer, and the address of the variable referred to by names[i] stores a value that is the first letter of the string
      printf("Value of names[%d] = %s\n", i, names[i] );
   }
   return 0;
}

Pointer to pointer

A pointer contains the address of a variable.When we define a pointer to a pointer, the first pointer contains the address of the second pointer and the second pointer points to the location containing the actual value.A pointer variable pointing to a pointer must be declared with two asterisks in front of the variable name:

type **pointerName;

When a target value is indirectly pointed to by one pointer to another, two asterisk operators are required to access the value:

#include <stdio.h>
 
int main ()
{
   int  var,*ptr, **pptr;
   var = 3000;
   /* Get the address of var */
   ptr = &var;
   /* Use Operator &Get Address of Pointer ptr to Variable */
   pptr = &ptr;
   printf("Value of var = %d\n", var );
   printf("Value available at *ptr = %d\n", *ptr );
   /* Get value using **pptr */
   printf("Value available at **pptr = %d\n", **pptr);
   return 0;
}

Pass Pointer to Function

C allows you to pass a pointer to a function by simply declaring the function parameter as a pointer type.

#include <stdio.h>
#include <time.h>
 
void getSeconds(unsigned long *par);

//You can also pass an array name to a function as a pointer, which is the first address of the array.

int main ()
{
   unsigned long sec;
   getSeconds( &sec );//Pass pointer to function, is the address passed
   /* Output Actual Value */
   printf("Number of seconds: %ld\n", sec );
   return 0;
}
void getSeconds(unsigned long *par)
{
   /* Get the current number of seconds */
   *par = time( NULL );//The value stored in the sec address pointed to by the par pointer is assigned to the current number of seconds in time
   return;
}

Return pointer from function

C allows you to return a pointer from a function.To do this, you must declare a function that returns a pointer, as follows:

int * myFunction()
{
body of function
}

In addition, C does not support returning the address of a local variable when a function is called unless a local variable is defined as a static variable.:

Because local variables are stored in the stack area of memory, the memory address they occupy is released when the function call ends, so when the function is executed, the variable in the function no longer has that memory address, so its pointer cannot be returned.

Unless its variable is defined as a static variable, the value of the static variable stored in the static data area in memory is not cleared as the function is executed, so it returns its address.

160 original articles published. 90% praised. 50,000 visits+
Private letter follow

Topics: Programming C less Asterisk