Hello,

Could anyone assist me in starting out with pointers. I know that pointers direct to the memory location where a value is stored, but I am having some issues with understanding the concept with arrays.

Could you suggest a simple startup code, where a pointer points to a memory location where array values are stored. How can i access those values by using the pointer and standard C commands and functions?

Thank you.

Array variables are converted to pointers for value operations. You do not need to do anything special if you already have a pointer. The syntax is basically the same as with an array variable except you have more options with pointer arithmetic:

#include <stdio.h>

int main()
{
    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int const* p = &a[0];
    size_t const sz = sizeof a / sizeof *a;
    size_t x;

    /* loop with indexes on the array */
    for (x = 0; x < sz; ++x) printf("%d%s", a[x], x < sz - 1 ? " " : "\n");

    /* loop with indexes on the pointer */
    for (x = 0; x < sz; ++x) printf("%d%s", p[x], x < sz - 1 ? " " : "\n");

    /* loop with pointer arithmetic */
    for (; p != &a[sz]; ++p) printf("%d%s", *p, p + 1 != &a[sz] ? " " : "\n");

    return 0;
}

thank you very much for the reply. Could it be possible to access a value using the pointer itself as it stores the memory address of the value, without using the actual array variable during the printf command. E.g. like storing the value from the memory address pointed by a pointer into a separate array without using the original array in the code. I'm trying out the memcpy command, but to no avail.

Array variables are converted to pointers for value operations. You do not need to do anything special if you already have a pointer. The syntax is basically the same as with an array variable except you have more options with pointer arithmetic:

#include <stdio.h>

int main()
{
    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int const* p = &a[0];
    size_t const sz = sizeof a / sizeof *a;
    size_t x;

    /* loop with indexes on the array */
    for (x = 0; x < sz; ++x) printf("%d%s", a[x], x < sz - 1 ? " " : "\n");

    /* loop with indexes on the pointer */
    for (x = 0; x < sz; ++x) printf("%d%s", p[x], x < sz - 1 ? " " : "\n");

    /* loop with pointer arithmetic */
    for (; p != &a[sz]; ++p) printf("%d%s", *p, p + 1 != &a[sz] ? " " : "\n");

    return 0;
}

I do not understand the question. In my example the last two loops do not use the array at all for accessing values. In the third loop the array is only used to get a pointer to the end for stopping the loop. Post the code you are trying to write, maybe that will help me understand what you want.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.