ezoic

Thursday, November 17, 2016

The interaction between a pointer and an array in C language.

C language is an old language. It is fast and effective.

We need to know some data structures in it, such as array, struct, stack, queue, heap, hash, tree etc in C.

In C, the array starts with index 0.

And we initialize an array like below:

type_specifier array_name[size1]...[sizeN] = {value_list};

value_list is delimited by ','.

On dimension array is defined as:

type_specifier array_name[size] = {value_list};

Here is an example:

char hello[12] = {’H’,’e’,’l’,’l’,’o’,’,’,’ ’,’w’,’o’,’r’,’l’,’d’,’\0’};

'\0' is a must here. It tells C, that's an end of an array. If you define a string, you do not need the '\0'.

Equivalently, you can define equivalent string like below:

string hello = "Hello, world"

But you need to add 'string.h' at the beginning.

Or, you can declare like this:

char *hello = "Hello, world"; or char hello[] = "Hello, world";

And you got the char pointers array.  And you do not need to define the size as below:

char hello[] = {’H’,’e’,’l’,’l’,’o’,’,’,’ ’,’w’,’o’,’r’,’l’,’d’,’\0’};

You can use a loop to go through every item in an arrayL

 [...]

  int i;

  char hello[12] = {’H’,’e’,’l’,’l’,’o’,’,’,’ ’,’w’,’o’,’r’,’l’,’d’,’\0’};

  [...]

  for(i = 0; i < 12; i++){

  printf("%c",hello[i]);

  }

  printf("\n");

  [...]

One thing we need to remember, we can not make i to 12 since the index starts from 0.

sizeof(tyep_specifier)



1 comment:

  1. Pointers in C are used to efficiently access array elements, as array elements are stored in adjacent memory locations. If we have a pointer pointing to a particular element of array in C, then we can get the address of next element by simply incrementing the pointer.

    ReplyDelete

looking for a man

 I am a mid aged woman. I live in southern california.  I was born in 1980. I do not have any kid. no compliacted dating.  I am looking for ...