How does pointer work ?

Thread Starter

Parth786

Joined Jun 19, 2017
642
Hi
I need help to understand basic of pointer in embedded C Programming. In text book say "A pointer is a variable which contains the address in memory of another variable" But I don't understand how does pointer work. I know what is address and variable.
upload_2017-9-30_14-50-53.png

Declaration of pointer : Data_Type * Pointer_Name
Example :
unsigned int * Numbers ;
unsigned char * Letters ;

actual variable Declaration
unsigned int Num = 5;

Assign value to pointer
Pointer Declaration and assign value
unsigned int * Numbers = Num;

Please Help me. I want to understand basics of pointer. How does they work and when we need to use in embedded programming ?
 

simozz

Joined Jul 23, 2017
125
A pointer points to the address of a variable.
The declaration and assignment is:
C:
unsigned int *Numbers = &Num;
Now try to use it and I will try to clarify your doubts, if any.
simozz
 
Last edited:

xox

Joined Sep 8, 2017
838
You really should read a full tutorial on pointers (just google "C pointer tutorial" or some such), but here are the basics:

  • Every single byte of data used by your program is located at some unique memory address. This doesn't include registers or hard-drive data, of course, just the stuff in RAM.
  • A pointer is simply a variable that contains the address of another variable. But it's also a special kind of unsigned integer that you can perform addition and subtraction on. Except that when you, say, add an integer value X to a pointer P you get an address that is the offset of P + (X * sizeof(P)). For example:
short* P = 0;
P = P + 3;

Now P equals 6 because the size of a short (on my system) is 2 bytes and 0 + (3 * 2) = 6. The only type of pointer that you cannot perform arithmetic on is a void*, and that's because the compiler needs to know the size of the data that the pointer refers to. So if you instead had declared P as such, then you'd have to cast it to the appropriate type first:

void* P = 0;
P = (short*)P + 3;

  • You get the value (stored at the address) of a pointer by "dereferencing" it, like so:

short S = 12;
short* P = &S;
*P += 7;

Now S equals 19. However, if you had done this instead:

*(P += 7);

In that case, you would only be moving P 14 bytes forward (7 * sizeof(short)), although no alteration to the data at that address since you just dereferenced it and did nothing else. Anyway, the main reason why we perform math on pointers is to manipulate data in arrays:

short A[ ] = { 2, 1, 3, 4, 7, 11, 18, 29, 47 };
short* P = &A[0];
// Another way:
short* Q = A; // ...resolves to &A[0]
*(P + 5) = 99; // Now the array contains { 2, 1, 3, 4, 7, 99, 18, 29, 47 }

As a shortcut, you could have written that last line like this instead:

P[5] = 99;

So that's the general idea at least. And to save yourself from a whole lot of potential headaches always initialize your pointers to something - if you can't immediately assign it to a variable then just set it to NULL (0). Moreover, once you're "done" with a pointer just go ahead and set it to NULL for good measure; that way, it's much easier to track down logic errors and what have you, because any attempt to dereference a null pointer results in the sudden death of your program (which is actually a good thing, because otherwise your program might just chug along for a long while and only randomly misbehave).
 
Last edited:

Thread Starter

Parth786

Joined Jun 19, 2017
642
A pointer points to the address of a variable.
The declaration and assignment is:
C:
unsigned int *Numbers = &Num;
Now try to use it and I will try to clarify your doubts, if any.
simozz
You really should read a full tutorial on pointers (just google "C pointer tutorial" or some such), but here are the basics:

  • Every single byte of data used by your program is located at some unique memory address. This doesn't include registers or hard-drive data, of course, just the stuff in RAM.
  • A pointer is simply a variable that contains the address of another variable. But it's also a special kind of unsigned integer that you can perform addition and subtraction on. Except that when you, say, add an integer value X to a pointer P you get an address that is the offset of P + (X * sizeof(P)). For example:
short* P = 0;
P = P + 3;

Now P equals 6 because the size of a short (on my system) is 2 bytes and 0 + (3 * 2) = 6. The only type of pointer that you cannot perform arithmetic on is a void*, and that's because the compiler needs to know the size of the data that the pointer refers to. So if you instead had declared P as such, then you'd have to cast it to the appropriate type first:

void* P = 0;
P = (short*)P + 3;

  • You get the value (stored at the address) of a pointer by "dereferencing" it, like so:

short S = 12;
short* P = &S;
*P += 7;

Now S equals 19. However, if you had done this instead:

*(P += 7);

In that case, you would only be moving P 14 bytes forward (7 * sizeof(short)), although no alteration to the data at that address since you just dereferenced it and did nothing else. Anyway, the main reason why we perform math on pointers is to manipulate data in arrays:

short A[ ] = { 2, 1, 3, 4, 7, 11, 18, 29, 47 };
short* P = &A[0];
// Another way:
short* Q = A; // ...resolves to &A[0]
*(P + 5) = 99; // Now the array contains { 2, 1, 3, 4, 7, 99, 18, 29, 47 }

As a shortcut, you could have written that last line like this instead:

P[5] = 99;

So that's the general idea at least. And to save yourself from a whole lot of potential headaches always initialize your pointers to something - if you can't immediately assign it to a variable then just set it to NULL (0). Moreover, once you're "done" with a pointer just go ahead and set it to NULL for good measure; that way, it's much easier to track down logic errors and what have you, because any attempt to dereference a null pointer results in the sudden death of your program (which is actually a good thing, because otherwise your program might just chug along for a long while and only randomly misbehave).
Do we use & operator to store address of variable in embedded c Programming ?
 

Thread Starter

Parth786

Joined Jun 19, 2017
642
Look at this program. I have tested this program and its work
C:
        void main()
{
  unsigned char string[15]="This is Parth";
  char *pointer = string;
  LCD_Initialization();
  while(*pointer)
        {
         LCD_Data(*pointer++);
         Delay(60);
        }
}
I don't use any & operator to store string address. That's why I am confuse ?
 

xox

Joined Sep 8, 2017
838
Oh right, well that's because the name (or "label") of an array is also an alias of the address of its first element (also covered in my first post).

short* P = &A[0];
// Another way:
short* Q = A; // ...resolves to &A[0]
 

WBahn

Joined Mar 31, 2012
29,979
Look at this program. I have tested this program and its work
C:
        void main()
{
  unsigned char string[15]="This is Parth";
  char *pointer = string;
  LCD_Initialization();
  while(*pointer)
        {
         LCD_Data(*pointer++);
         Delay(60);
        }
}
I don't use any & operator to store string address. That's why I am confuse ?
The name of an array IS a pointer to the first element of the array.

If you wanted to use the address operator to get the value to store in your variable "pointer", then you could have used

char *pointer = &string[0];

You should also consider whether a statement like

*pointer++

is evaluated as

*(pointer++)

or

(*pointer)++

If you don't know which it is, then you shouldn't let the compiler pick for you. Use whichever one does what you intend to have happen.
 

Thread Starter

Parth786

Joined Jun 19, 2017
642
The name of an array IS a pointer to the first element of the array.

If you wanted to use the address operator to get the value to store in your variable "pointer", then you could have used

char *pointer = &string[0];

You should also consider whether a statement like

*pointer++

is evaluated as

*(pointer++)

or

(*pointer)++

If you don't know which it is, then you shouldn't let the compiler pick for you. Use whichever one does what you intend to have happen.
Thanks. I have another doubt about selection of array and pointer.
Example 1 :
store number { 1,2,3,4}
store letter { 'A' , 'B', 'C'}
number string {1234}
letter string { "ABC"}
we will use array for this type of example.

Example 2
number string {1234, 4567,6589,2154}
letter string { "ABC", "GHJ","KLM"}
We will use pointer for this type of example.

what does pointer do and what array can't do?
 

WBahn

Joined Mar 31, 2012
29,979
I can't make sense of your examples.

What is a "number string"?

In C, a string is a NUL-terminated sequence of integers, each interpreted as a character. Don't make it more complicated than it is.

So your "number string" of 1234 should be "1234" and is no different than "ABC" except the first integer stored would be 49 (the ASCII code for '1') instead of 65 (the ASCII code for 'A'). That's assuming your compiler uses ASCII, which is a pretty safe bet.

The main difference between an array and a pointer is that an array has memory allocated for it at creation and the compiler knows this. The address of the array is therefore a constant and can't be changed. A pointer, on the other hand, does not start out pointing to anything and so it is just a variable whose contents are up to you. One consequence of this is that if you use the sizeof() macro with an array name you get the number of bytes needed to store the entire array, because the compiler has this information at compile time. If you use the sizeof() macro with a pointer name you get the number of bytes needed to store the pointer, because that's all the information that the compiler has at compile time.
 

Thread Starter

Parth786

Joined Jun 19, 2017
642
I can't make sense of your examples.
.
Does it make sense for example of array and pointer
Example of array
int Array[] = {2,1,7,5,6};
char Array[] = {'P','A','R','T','H'};

Example of pointer
char *Array = {"PARTH"};
char *Array[] = {"RAM", "SHYAM", "SITA"};
int*Array[] = {"256", "392", "756"};
 

WBahn

Joined Mar 31, 2012
29,979
Does it make sense for example of array and pointer
Example of array
int Array[] = {2,1,7,5,6};
char Array[] = {'P','A','R','T','H'};
These are fine.

Example of pointer
char *Array = {"PARTH"};
Array is a pointer to a char. But you are trying to initialize it to be an array of strings. So you have a mismatch in levels of indirection.

char *Array[] = {"RAM", "SHYAM", "SITA"};
Here Array is an array of pointers, each of which is a pointer to a char (and at that address is actually an array of char values that represent NUL-terminated strings).

So this is fine. You have created an array containing three pointers. You could print out the middle name using

printf("%s". Array[1]);

int*Array[] = {"256", "392", "756"};
Here you have created an array of pointers to values of type int, but are initializing it with an array of strings.

There is fundamentally no difference between "Bob" and "123". Both are NUL-terminated strings. Both are four-element character arrays in which the first three elements are the ASCII codes for the corresponding characters and the fourth is the NUL terminator.
 

Thread Starter

Parth786

Joined Jun 19, 2017
642
I want to ask one more doubt on the use of pointer . Look at following example

Candidates Name = [Jack, Rock, Bob, Hunk, Ian ]
Candidates ID Numbers = [ 104, 102, 105, 103, 101 ]

I want to write program that will show the name of candidate in alphabetic order. So first I have to store the name of candidate. What can I use array or pointer to store the name of candidates ?
 

xox

Joined Sep 8, 2017
838
Haven't got much time to explain, so you'll just have to read through it and try to figure out as best you can how it works...anyway, hope it helps.

C:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAXIMUM_CANDIDATE_NAME_LENGTH 64

typedef struct
{
    char
        name[MAXIMUM_CANDIDATE_NAME_LENGTH + 1];
    int
        id;
}
    candidate;

int
    sort_ascending_by_name(const void* left, const void* right)
{
    candidate
        * first = (candidate*)left,
        * second = (candidate*)right;
    return strcmp(first->name, second->name);
}

int
    read_input(char* buffer, size_t maximum)
{
    fgets(buffer, maximum, stdin);
    size_t
        length = strlen(buffer);
    if(length > 0 && (buffer[length - 1] == '\n'))
    {
        buffer[length - 1] = 0;
        --length;
    }
    return length != 0;
}

#define MAXIMUM_NUMBER_OF_CANDIDATES 100

int
    main(void)
{
    candidate
        data[MAXIMUM_NUMBER_OF_CANDIDATES];
    size_t
        count = 0;
    for(count = 0; count < MAXIMUM_NUMBER_OF_CANDIDATES; ++count)
    {
        puts("Input the next candidate's name (press enter to quit)");
        if(!read_input(data[count].name, MAXIMUM_CANDIDATE_NAME_LENGTH))
            break;
        char
            id_text[16];
        puts("Now the candidate's id (press enter to use default)");
        read_input(id_text, sizeof(id_text));
        data[count].id = atoi(id_text);
        if(data[count].id == 0)
            data[count].id = (count + 1);
    }
    qsort(data, count, sizeof(candidate), sort_ascending_by_name);
    puts("Candidates (sorted by name): ");
    for(size_t index = 0; index < count; ++index)
        printf("%s : %d\n", data[index].name, data[index].id);
    return 0;
}
 
Last edited by a moderator:

Thread Starter

Parth786

Joined Jun 19, 2017
642
Haven't got much time to explain, so you'll just have to read through it and try to figure out as best you can how it works...anyway, hope it helps.

C:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAXIMUM_CANDIDATE_NAME_LENGTH 64

typedef struct
{
    char
        name[MAXIMUM_CANDIDATE_NAME_LENGTH + 1];
    int
        id;
}
    candidate;

int
    sort_ascending_by_name(const void* left, const void* right)
{
    candidate
        * first = (candidate*)left,
        * second = (candidate*)right;
    return strcmp(first->name, second->name);
}

int
    read_input(char* buffer, size_t maximum)
{
    fgets(buffer, maximum, stdin);
    size_t
        length = strlen(buffer);
    if(length > 0 && (buffer[length - 1] == '\n'))
    {
        buffer[length - 1] = 0;
        --length;
    }
    return length != 0;
}

#define MAXIMUM_NUMBER_OF_CANDIDATES 100

int
    main(void)
{
    candidate
        data[MAXIMUM_NUMBER_OF_CANDIDATES];
    size_t
        count = 0;
    for(count = 0; count < MAXIMUM_NUMBER_OF_CANDIDATES; ++count)
    {
        puts("Input the next candidate's name (press enter to quit)");
        if(!read_input(data[count].name, MAXIMUM_CANDIDATE_NAME_LENGTH))
            break;
        char
            id_text[16];
        puts("Now the candidate's id (press enter to use default)");
        read_input(id_text, sizeof(id_text));
        data[count].id = atoi(id_text);
        if(data[count].id == 0)
            data[count].id = (count + 1);
    }
    qsort(data, count, sizeof(candidate), sort_ascending_by_name);
    puts("Candidates (sorted by name): ");
    for(size_t index = 0; index < count; ++index)
        printf("%s : %d\n", data[index].name, data[index].id);
    return 0;
}
Thanks for your detailed explanations. but I haven't reach at level of structure in programming. I understand you use structure to store multiple data type. In my example there were two data type int and char so that's reason you used structure.

I think I couldn't express my question very well.

For example: following are the ID numbers
Candidates ID Numbers = [ 104, 102, 105, 103, 101 ]
What can I use array or pointer to store the name of candidates ?
I couldn't figure out where to use pointer. what pointer can do , array can't do?
 

WBahn

Joined Mar 31, 2012
29,979
I want to ask one more doubt on the use of pointer . Look at following example

Candidates Name = [Jack, Rock, Bob, Hunk, Ian ]
Candidates ID Numbers = [ 104, 102, 105, 103, 101 ]

I want to write program that will show the name of candidate in alphabetic order. So first I have to store the name of candidate. What can I use array or pointer to store the name of candidates ?
You can use either, as long as you use it appropriately.
 

WBahn

Joined Mar 31, 2012
29,979
Thanks for your detailed explanations. but I haven't reach at level of structure in programming. I understand you use structure to store multiple data type. In my example there were two data type int and char so that's reason you used structure.

I think I couldn't express my question very well.

For example: following are the ID numbers
Candidates ID Numbers = [ 104, 102, 105, 103, 101 ]
What can I use array or pointer to store the name of candidates ?
I couldn't figure out where to use pointer. what pointer can do , array can't do?
Arrays have the limitation that they have to contain data of a single, known type and the dimension has to be known at compile time (C99 does allow variable-length arrays, but we'll ignore that for this discussion). Furthermore, non-global arrays are instantiated on the stack instead of the heap and are of automatic duration. If any of those constraints are unacceptable, use a pointer.

You don't need to use a structure for the example you have given, though it is perhaps the cleanest way and this would be a good example to dip your feet into those waters (either now or down the road). You treat the two arrays as "parallel arrays" instead.
 

Thread Starter

Parth786

Joined Jun 19, 2017
642
For depth understanding. I am explaining about pointer with example . if do you find anywhere wrong please let me know

upload_2017-10-30_22-51-0.png
table
Code:
Name of variable    address      content

ptr                 0002          1008

var                 1008           2456
Program
Code:
#include <stdio.h>

int main(void)
{
    int var = 2456;
    int *ptr = &var;

    printf("The value of var is: %d \n", var);

    printf("The address of var : %p \n", &ptr);

    return 0;
}
Result
The value of var is: 2456
The address of var : 0061FF28

Q1. I always confused when I have many option and I have to select one of them. What is good in pointer. What can pointer do , which can not done by any another in programming

Note : Please don't be confuse with picture address and program address
 

WBahn

Joined Mar 31, 2012
29,979
If you want to print the address of 'var', then print the address of 'var', not the address of 'ptr'.

The following two should produce the same output:

C:
printf("The address of var : %p \n", &var);
printf("The address of var : %p \n", ptr);
In your diagram example, both should produce 1008, since that is both the address at which 'var' is stored (&var) and the value stored in the variable ptr.

Your code would print the 0002 since that is the address at which 'ptr' is stored (&ptr).
 
Last edited:
Top