Understanding pointers in C

  • (2 Pages)
  • +
  • 1
  • 2

17 Replies - 1793 Views - Last Post: 25 October 2008 - 05:35 AM Rate Topic: -----

#1 Boyan   User is offline

  • D.I.C Regular

Reputation: 4
  • View blog
  • Posts: 254
  • Joined: 09-September 07

Understanding pointers in C

Post icon  Posted 23 October 2008 - 03:27 AM

The pointers in C were always the biggest problem for me. After reading a lot, I'm still being confused at some point. So, can anyone provide a simple program which explains the practical use of pointers? Like in arrays or something, then printing the pointed element...

I'd be very grateful. Thanks.
Is This A Good Question/Topic? 0
  • +

Replies To: Understanding pointers in C

#2 Linkowiezi   User is offline

  • D.I.C Regular

Reputation: 58
  • View blog
  • Posts: 316
  • Joined: 07-October 08

Re: Understanding pointers in C

Posted 23 October 2008 - 04:17 AM

I hope you will find this little program useful, I made it as a training exercise trying to educate myself:
/*
 * Author: Linkowiezi
 *
 * Description:
 * Calculates the average
 * of a user defined set of scores
 * for a user user defined set of tests.
 */

//  Include declarations
#include <iostream>

//  Namespace declarations
using namespace std;

//  Class declarations
#ifndef __TESTSCORE__   //  If __TESTSCORE__ is not defined(witch in this particular case isn't really necessary to define)
#define __TESTSCORE__   //  Define __TESTSCORE__(but we define it anyway)
class TestScore         //  The TestScore class
{
  private:              //  Private class members
    float *score;                                       //  Declaration of pointer score witch will be used as a new float array
    int nS;                                             //  Declaration of integer nS that will store the number of scores

  public:               //  Public class members
    TestScore();                //  Constructor
    ~TestScore();               //  Destructor

    void initScore( int nScores );                      //  Function that allocates memory for the new float score array
    void setScore( int nScore, float newScore );        //  Function that set a value of a specific score
    float getScore( int nScore );                       //  Function that get the value of a specific score
};
//  Constructor
TestScore::TestScore()
{
}
//  Destructor
TestScore::~TestScore()
{
    delete []score;  //  Free memory allocation for score
}
//  Function that allocates memory for the new float score array
void TestScore::initScore( int nScores )
{
  nS = nScores;                 //  Set nS to nScores witch should be the total number of scores
  score = new float [nS];       //  Allocate memory for the score array
}
//  Function that set a value of a specific score
void TestScore::setScore( int nScore, float newScore )
{
  *(score+nScore) = newScore;   //  Pass the value of newScore to be stored where the value of the specifically defined score is stored
}
//  Function that get the value of a specific score
float TestScore::getScore( int nScore )
{
  return *(score+nScore);       //  Return the value stored in the specifically defined score
}
#endif                  // Here we end the "if" we used in "ifndef" above

//  Function declarations
void getTestScores( float *score, TestScore &ts, int test, int nScores );       //  Function that gets all test scores of a specific test
float calcAverage( float *score, int test, int nScores );                       //  Function that calculates the averages of the scores in a specific test
void displayAverages( float *average, int nTests );                             //  Function that displays the averages of the scores in all tests

//  Main function
int main( int argc, char **argv[] )
{
  //  Declaration of variables used within the main function
  int nTests = 0, nScores = 0;

  //  While the user has not given us a value higher than 0...
  while( nTests < 1 )
  {
    //  ...we will keep asking him to enter the number of tests
    cout << "Please enter number of tests: ";
    cin >> nTests;
  }
  //  While the user has not given us a value higher than 0...
  while( nScores < 1 || nScores > 3 )
  {
    //  ...we will keep asking him to enter the number of scores for each test
    cout << "Please enter number of scores: ";
    cin >> nScores;
  }

  //  Declaration of more variables used within the main function
  float tempFloat;              //  This is a temporary float variable and could have been declared earlier
  float score[nTests*nScores];  //  This is our score variable and could not have been declared earlier because we didn't know how many tests and scores the user wanted
  float average[nTests];        //  The same goes for this variable witch is the average result for each test...

  TestScore ts[nTests];         //  ...and this witch is the class where we wil store our scores in.

  //  Set scores
  cout << "Please enter score for..." << endl;
  for( int i1 = 0; i1 < nTests; i1++ )
  {
    //  First we initialize each test...
    ts[i1].initScore( nScores );
    for( int i2 = 0; i2 < nScores; i2++ )
    {
      //  ...then we ask the user to give us the values of the scores...
      cout << "Test " << i1+1 << "  Score " << i2+1 << ": ";
      cin >> tempFloat;
      ts[i1].setScore( i2, tempFloat ); //  ...and store them in the TestScore class array
    }
  }
  //  Get scores
  for( int i = 0; i < nTests; i++ )
    getTestScores( score, ts[i], i, nScores );          //  Here we call the getTestScores function for each test

  //  Calculate averages
  for( int i = 0; i < nTests; i++ )
    average[i] = calcAverage( score, i, nScores );      //  Here we call the calcAverage function for each test

  //  Display averages
  displayAverages( average, nTests );                   //  Here we call the displayAverages function

  //  Since main is an int, we return 0 to let the OS know it ran successfully
  return 0;
}

//  Function that gets all test scores of a specific test
void getTestScores( float *score, TestScore &ts, int test, int nScores )
{
  //  For each score we pass the value from the getScore() function in our TestScore class...
  //  ...to the value stored in the memory where the score pointer points to
  for( int i = 0; i < nScores; i++ )
    *(score+(test*nScores+i)) = ts.getScore(i);
}

//  Function that calculates the averages of the scores in a specific test
float calcAverage( float *score, int test, int nScores )
{
  //  First we declare a float to make life easier for us
  float result = 0;

  //  Then for each score we add the value stored in memory where the score pointer points to
  for( int i = 0; i < nScores; i++ )
    result += score[test*nScores+i];

  //  And finally reurn the result...
  //  ...divided by the number of scores to get the average score
  return result/nScores;
}

//  Function that displays the averages of the scores in all tests
void displayAverages( float *average, int nTests )
{
  //  For each test, we display the average score
  for( int i = 0; i < nTests; i++ )
    cout << "The average score for test " << i+1 << " is: " << average[i] << endl;
}

Was This Post Helpful? 1

#3 Boyan   User is offline

  • D.I.C Regular

Reputation: 4
  • View blog
  • Posts: 254
  • Joined: 09-September 07

Re: Understanding pointers in C

Posted 23 October 2008 - 04:28 AM

It's a bit advanced for my C knowledge, but thank you. Here's what I did. It's very simple.

#include <stdio.h>

int main()

{
	int p = 5, q, *ptr;	
	q = p+5;
	ptr = &q;
	printf("%d %d %d\n", p, q, *ptr);
	system ("pause");
	
}



This is simple, now I'm trying to get into "heavier" stuff.
Was This Post Helpful? 0
  • +
  • -

#4 Linkowiezi   User is offline

  • D.I.C Regular

Reputation: 58
  • View blog
  • Posts: 316
  • Joined: 07-October 08

Re: Understanding pointers in C

Posted 23 October 2008 - 04:56 AM

Ok, what my program really does is allocate memory for something we don't know how big it is from the begining and makes some calculations and prints out of that and does so with the use of a class.
But it could be a little bit easier, like this in short:
#include <iostream>

using namespace std;

int main()
{
  //  Declare pointer
  float *fPointer;

  //  Declare integer used for array size
  int aSize;
  
  //  Get user input for array size
  cin >> aSize;
  
  //  Allocate memory for the array
  fPointer = new float[aSize];
  
  //  Now input numbers into the array
  for( int i = 0; i < aSize; i++ )
    cin >> fPointer[i];
  
  //  Now print the whole array
  for( int i = 0; i < aSize; i++ )
    cout << fPointer[i] << endl;
  
  //  Now free memory allocation
  delete []fPointer;
  
  return 0;
}

And you can change cin and cout to scanf and printf
And I also uses some different kind of ways to print the pointer in my program and I if you want to give it a try and go trough my code I don't think it will be to hard to follow the code as long as you read the comments in it.
Hope this was of any help in your pointer hunting ;)
Was This Post Helpful? 0
  • +
  • -

#5 David W   User is offline

  • DIC supporter
  • member icon

Reputation: 298
  • View blog
  • Posts: 1,839
  • Joined: 20-September 08

Re: Understanding pointers in C

Posted 23 October 2008 - 05:12 AM

Recall that in C or C++ arrays are automatically passed by reference, i.e. the address to the first element of the array is passed.
#include <iostream>
using namespace std;

void show( int a[], int num ) // or ... // void show( int * a, int num )
{
    int i;
    for (i=0; i<num; ++i)
        cout << a[i] << " ";
    cout << endl;
    for (i=0; i<num; ++i)
        cout << *a++ << " ";
}

int main()
{
    int ints5[] = {1,2,3,4,5};
    show( ints5, 5 );

    cin.get();
    return 0;
}

This post has been edited by David W: 23 October 2008 - 05:19 AM

Was This Post Helpful? 0
  • +
  • -

#6 NBULCHANDANI   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 10-October 08

Re: Understanding pointers in C

Posted 23 October 2008 - 05:13 AM

View PostBoyan, on 23 Oct, 2008 - 03:27 AM, said:

The pointers in C were always the biggest problem for me. After reading a lot, I'm still being confused at some point. So, can anyone provide a simple program which explains the practical use of pointers? Like in arrays or something, then printing the pointed element...

I'd be very grateful. Thanks.

Was This Post Helpful? 0
  • +
  • -

#7 Boyan   User is offline

  • D.I.C Regular

Reputation: 4
  • View blog
  • Posts: 254
  • Joined: 09-September 07

Re: Understanding pointers in C

Posted 23 October 2008 - 05:19 AM

Thanks guys, but aren't those in C++? Except for the iostream lib, I don't know anything about C++.

What's cin.get?
Was This Post Helpful? 0
  • +
  • -

#8 David W   User is offline

  • DIC supporter
  • member icon

Reputation: 298
  • View blog
  • Posts: 1,839
  • Joined: 20-September 08

Re: Understanding pointers in C

Posted 23 October 2008 - 05:20 AM

Or in C ...

#include <stdio.h>

void show( int a[], int num ) // or ... // void show( int * a, int num )
{
    int i;
    for (i=0; i<num; ++i)
        printf("%d ", a[i]);
    printf( "\n" );
    for (i=0; i<num; ++i)
        printf("%d ", *a++);
}

int main()
{
    int ints5[] = {1,2,3,4,5};
    show( ints5, 5 );

    getchar();
    return 0;
}

Was This Post Helpful? 0
  • +
  • -

#9 Linkowiezi   User is offline

  • D.I.C Regular

Reputation: 58
  • View blog
  • Posts: 316
  • Joined: 07-October 08

Re: Understanding pointers in C

Posted 23 October 2008 - 06:43 AM

Yes, it is written in C++, but the differance isn't all that great(except for classes) and it might be a good learning experience to try to rewrite it to C while you read trough it and google any expression you encounter that you are not fammiliar with.
A few examples are:
cin >> integer; = scanf( "%d", integer );
cout << integer << endl; = printf( "%d\n", integer );
cin.get(); = getchar();

So as I said not that big of a differance exept for one thing.
Classes...
...you might wanna skip the "class" since that is not really c and c++ was at first called 'c with classes'.
Just tear it appart and maybe toss it in functions or a struct...

And memory allocation in pure C might look a more like this:
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  int n;
  char *buffer;

  printf ("How long do you want the string? ");
  scanf ("%d", &n);

  buffer = (char*) malloc (n+1);

  for ( int i=0; i<n; i++)
    buffer[i] = getchar();
  buffer[n]='\0';

  printf ("Your input was: %s\n",buffer);
  free (buffer);
  
  return 0;
}


If you have any more questions don't hesitate to ask.
I'm no C expert but I can always give a try at throwing out an explanation :)
Was This Post Helpful? 0
  • +
  • -

#10 Boyan   User is offline

  • D.I.C Regular

Reputation: 4
  • View blog
  • Posts: 254
  • Joined: 09-September 07

Re: Understanding pointers in C

Posted 23 October 2008 - 06:52 AM

Thank you so much, people. Now some things are much clearer to me. I just hope I'm not bothering anyone with this. :)

Here's a question, but first the code I wrote:

#include <stdio.h>

int main()

{
int x, a, *ptr1, *ptr2;
printf("Enter a value for x\n");
scanf("%d", &x);
ptr1 = &x;
a = ++x;
ptr2 = ptr1 + 5;
printf("%d %d %d %d\n", x, a, *ptr1, *ptr2);
system("pause");
}



In line 11, you might see what I want to do. I want my out put to be the same for the first three ints printed, except for the last one which I want to be 'the value + 5'. I'm trying to figure out how's this works.

But here's what happens. For example I enter 5 for x, and got this:

6 6 6 4008456


Where's my problem?

Thank you.
Was This Post Helpful? 0
  • +
  • -

#11 Linkowiezi   User is offline

  • D.I.C Regular

Reputation: 58
  • View blog
  • Posts: 316
  • Joined: 07-October 08

Re: Understanding pointers in C

Posted 23 October 2008 - 07:04 AM

A pointer points to a place in the memory and if you do this:

Quote

ptr2 = ptr1 + 5;

You actually point to 5 memry slots after where ptr1 points to.
Like an array ptr1[5];.
And as you have no array... it points to whatever is stored there anyway witch might be... anything.

EDIT:
If you want to print out the value +5 you might wanna do this instead:
ptr2 = ptr1;
printf("%d %d %d %d\n", x, a, *ptr1, *ptr2+5);

This post has been edited by Linkowiezi: 23 October 2008 - 07:11 AM

Was This Post Helpful? 0
  • +
  • -

#12 Boyan   User is offline

  • D.I.C Regular

Reputation: 4
  • View blog
  • Posts: 254
  • Joined: 09-September 07

Re: Understanding pointers in C

Posted 23 October 2008 - 07:10 AM

So, is there a way to just add plus 5 to ptr2?

EDIT: I saw your edit. Thank you. :)

This post has been edited by Boyan: 23 October 2008 - 08:58 AM

Was This Post Helpful? 0
  • +
  • -

#13 David W   User is offline

  • DIC supporter
  • member icon

Reputation: 298
  • View blog
  • Posts: 1,839
  • Joined: 20-September 08

Re: Understanding pointers in C

Posted 23 October 2008 - 06:08 PM

Quote

So, is there a way to just add plus 5 to ptr2?


/*
    So, is there a way to just add plus 5 to ptr2?
*/

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *pc= NULL;
    printf("%p, ",pc);
    pc=(char*)realloc(pc, sizeof(char));
    printf("%p, ",pc);
    pc=pc+1; /* note address is increased by 1 */
    printf("%p\n\n",pc); 
    
    int *pi= NULL;
    printf("%p, ",pi);
    pi=(int*)realloc(pc, sizeof(int));
    printf("%p, ",pi);
    pi=pi+1; /* note address is increased by 4, since type 'int' is 4 bytes long */
    printf("%p",pi);      
    getchar();
    return 0;
}

This post has been edited by David W: 23 October 2008 - 06:14 PM

Was This Post Helpful? 0
  • +
  • -

#14 NickDMax   User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2255
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: Understanding pointers in C

Posted 23 October 2008 - 09:23 PM

What are pointers:

vaguely: A variable that holds the memory address of another variable (or just some point in memory).

More specific: Pointers are memory addresses, but they also have a defined size. This allows for "pointer arithmetic" -- so if pointer p points to an integer, then pointer p + 1 will point to the next integer after p (not the next memory address).


So for example:

int var[3] = {1, 2, 3};
int *ptr = &var; //ptr = address of var
*ptr = 2;  //var[0] = 2
*(ptr + 1) = 9; //var[1] (the next integer in memory) = 9
*(ptr + 2) = 5; //var[2] = 5;



So in C we don't really say that the pointer has a "size" rather that it points to a specific type. an int* is a pointer to an int and it's size is the size of an int, a long* is a pointer to a long, and may have a slightly larger size, a char[10]* is a pointer to an array of 10 characters and will have a size of 10.

Pointers are of great value. First of all they allow us to refer to data rather than coping it all the time. For example if I want to search a large text file I don't want to pass the entire text, I can just pass a pointer to it and the function can search the text where it is.

Pointers also for the basis of many memory structures. For example a linked list is a dynamic memory structure that works kind of like an array, except that the elements don't have to be contiguous as they are in an array. This means (among other things) that I can re-order the list without moving all the elements in the list, just rearranging the order of the pointers (often making for some faster algorithms than with arrays).

pointers have many many many uses... but they are a little tricky to master. Play with a few examples, look at the pictures in the books until you feel the click of understanding.
Was This Post Helpful? 0
  • +
  • -

#15 David W   User is offline

  • DIC supporter
  • member icon

Reputation: 298
  • View blog
  • Posts: 1,839
  • Joined: 20-September 08

Re: Understanding pointers in C

Posted 24 October 2008 - 01:13 PM

In a 32 bit environment, pointers always hold a 32 bit address ...

so there ... they will ALWAYS have size 4, i.e. 4 bytes = 32 bits.

But as was attempted to be pointed out above, (pun intended), the type of pointer is 'known' in C and C++ ... So when you code char c[] ="12345"; // ... then c[0] and c[1] are one byte apart; but if one codes int i[] = {1,2,3,4,5}; // ... then i[0] and i[1] are 4 bytes apart.

For some free help with beginning computer programming, you might also like to see ...

http://developers-he...index.php/topic,46.0.html

Shalom shalom and Shabat Shalom,

David

This post has been edited by David W: 24 October 2008 - 01:34 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2