Bay 12 Games Forum

Please login or register.

Login with username, password and session length
Advanced search  
Pages: 1 [2] 3

Author Topic: A question (or more) to the C++ programmers about pointers  (Read 3252 times)

florian

  • Bay Watcher
    • View Profile
Re: A question (or more) to the C++ programmers about pointers
« Reply #15 on: October 18, 2009, 08:49:54 am »

I'm not sure what you want to accomplish, anyway, see this:
Code: [Select]
#include <stdio.h>
#include <stdlib.h>

#define H 10
#define W 10

typedef struct {
    unsigned int type : 1;
} tile;

#define TYPE_WALL   1
#define TYPE_EMPTY  0

tile ** mkWorld (void)
{
    int i, j;
    tile ** world = (tile **)malloc(H * sizeof(tile *));
    for (i = 0; i < H; i++) {
        world[i] = (tile *)malloc(W * sizeof(tile));
        for (j = 0; j < W; j++) {
            world[i][j].type = TYPE_WALL;
        }
    }
    return world;
}

int main (int argc, char const *argv[])
{
    int i, j;
    tile ** world = mkWorld();
    for (i = 0; i < H; i++) {
        for (j = 0; j < W; j++) {
            if (world[i][j].type == TYPE_WALL) {
                printf("#");
            } else {
                printf(".");
            }
        }
        printf("\n");
    }
    printf("Now what?");
    getchar();
    return 0;
}
This code includes several things which you most likely know nothing about, such as: (a) typedefs, (b) structs, (c) bit fields, (d) pointers-to-pointers, (e) malloc and (f) liberal use of preprocessor defines. It's also pure C.

But, it allocates a 10-by-10 world of tiles which are either empty or walls, all of which are walls right now and prints it. Which apparently is what you want.

If you are thoroughly confused by now, I would suggest that you ask questions whenever you need to and read further through your book.

Also, to answer your originial question, you need pointers for dynamic allocation and for call-by-reference.
Logged

Jetlaw

  • Bay Watcher
    • View Profile
Re: A question (or more) to the C++ programmers about pointers
« Reply #16 on: October 18, 2009, 10:34:38 am »

Thanks for the replies. I got this segment of code working at least.

Code: [Select]
#include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
   char szString[101]; // 101 char array.
   char* pszString = &szString[0]; // Pointer for the array.

   // The following loop is intended to fill the entire array with # characters.
   for(int n = 0; n <= 100; n++)
   {
      *(pszString + n) = '#';
      // Then zero-terminate the array.
      if(n == 100)
      {
         *(pszString + n) = '\0';
      }
   }

   // Then print all one hundred "#" characters to the screen with no formatting.
   while(*pszString++)
   {
      cout << *(pszString - 1);
     
   }

   cout << endl;
   
   cout << endl;
   
   // wait until user is ready before terminating program
   // to allow the user to see the program results
   system("PAUSE");
   return 0;
}

It'll just display a string of 100 '#' characters, but that's all I wanted it to do for now.

If pointers are the most speed-efficient way of doing things then I intend to learn then and apply them in as many programs as possible regardless of if they're the easiest to implement or not; if it's advised as an okay programming habit to have that is.
Logged

Normandy

  • Bay Watcher
    • View Profile
Re: A question (or more) to the C++ programmers about pointers
« Reply #17 on: October 18, 2009, 12:58:49 pm »

That's not what pointers are for, speed. That's a common misconception. They decrease the speed of certain operations (such as passing an object), but otherwise they are not designed to specifically increase the speed of your code. It's a very bad programming habit to be throwing pointers around willy-nilly. Use pointers when they are necessary - e.g. passing references, dealing with arrays, dynamically allocating memory. Don't use them otherwise.

As a small note, it's a common misconception that passing a pointer to an int is faster than passing the int itself, as well. A pointer itself is a block of memory - hence, when passed, it must be allocated, copied, etc... That's a common misconception perpetuated by far too many books with unclear or misleading language.

Only when passing objects larger than an int are pointers any faster than passing by value.

Here is the simplest possible implementation of what you are seeking.

Code: [Select]
#include <iostream>

using namespace std;

#define HEIGHT 10
#define WIDTH 10

int main(int argc, char *argv[])
{
char pBoard[HEIGHT*WIDTH];
for (int n = 0; n < 100; ++n)
{
// Simplest way to do it; recommended way to
pBoard[n] = '#';
// Exactly the same, but less idiomatic. Not reommended
//*(pBoard+n) = '#';
}

for (int y = 0; y < HEIGHT; ++y)
{
for (int x = 0; x < WIDTH; ++x)
{
cout << pBoard[y*WIDTH + x];
}
cout << endl;
}

return 0;
}

A small note: null-terminated strings are only for, well, strings. When you're working with non-strings (e.g. things that are not strings), you don't need to null-terminate them.

More or less, if you want to store text, like readable, printable, normal words-and-spaces text, that is when you would use null termination on an array. Otherwise, when simply dealing with data, this is not necessary.
« Last Edit: October 18, 2009, 01:00:45 pm by Normandy »
Logged

G-Flex

  • Bay Watcher
    • View Profile
Re: A question (or more) to the C++ programmers about pointers
« Reply #18 on: October 18, 2009, 01:02:40 pm »

Keep in mind that C++ is designed such that you're supposed to be able to AVOID using pointers explicitly most of the time.

Hell, you hardly even need to use arrays themselves, at all.

However, pointers are such a fundamental concept that a lot of those higher-level features you'll use will still internally rely on them.
Logged
There are 2 types of people in the world: Those who understand hexadecimal, and those who don't.
Visit the #Bay12Games IRC channel on NewNet
== Human Renovation: My Deus Ex mod/fan patch (v1.30, updated 5/31/2012) ==

Outcast Orange

  • Bay Watcher
  • [SOMETIMES_SQUID]
    • View Profile
    • The Outcast Orange
Re: A question (or more) to the C++ programmers about pointers
« Reply #19 on: October 18, 2009, 01:07:27 pm »

Hell, you hardly even need to use arrays themselves, at all.

I don't know what you're programming without arrays,
but I heavily rely on them myself.

I never found out what pointers were actually.
Are they just references to an array?
If so, I use those heavily as well.
Logged
[7:53:55 PM] Armok, why did you demand that I don't eat you?
[7:54:34 PM] [Armok]: woooooo

Burried Houses - Platform Explorer Demo H - Cloud Scream

G-Flex

  • Bay Watcher
    • View Profile
Re: A question (or more) to the C++ programmers about pointers
« Reply #20 on: October 18, 2009, 04:48:56 pm »

You don't need to directly use arrays in C++ for the most part because the standard library gives you a truckload of dynamic data structures, which (in most cases) are a better idea anyway. This isn't to say that direct use of arrays by the programmer is always a bad thing; sometimes they're still a good idea, especially if you don't need to do anything fancy with the data and know how many elements you're going to have.

Pointers just reference a location in memory.

The way arrays work is that the array name itself (say, foo) is a pointer to the location of the first element. Using an index (say, foo[2]) uses pointer arithmetic to increment the pointer over two more spaces to point to the third element, as well as dereferencing it to get the value (as opposed to the pointer).

So if you say foo[2], you're saying "take the memory address at the start of foo, and increment it by two to get the address of the third element, then return whatever that value is".

That's one reason why C++ has no clue where your arrays actually end (foo[6] may very well be attempted for reading/writing at runtime even if you declare it with only two elements); that information simply isn't there, and it's up to you not to try to index into it (which is just incrementing a pointer) further than actually belongs to that array.
Logged
There are 2 types of people in the world: Those who understand hexadecimal, and those who don't.
Visit the #Bay12Games IRC channel on NewNet
== Human Renovation: My Deus Ex mod/fan patch (v1.30, updated 5/31/2012) ==

Mr Tk

  • Bay Watcher
  • Would you like a mint? It's only waffer thin.
    • View Profile
Re: A question (or more) to the C++ programmers about pointers
« Reply #21 on: October 18, 2009, 06:47:58 pm »

Go dynamic data structures.

Something like a vector is good because it doesn't have to have a specified size during compile time. You can simply put stuff into in and things come out.

But structures such as linked lists are based off the ability to use pointers. This starts getting into time complexity issues (Big O notation) which is a bit beyond you at this point. But let me just say it's far faster to insert an item into the middle of a linked list (just change where the pointers are pointing to for three items in the list at most) compared to inserting in an array (you put one new item into the front of the array and you have to shuffle all the rest of the elements down).
Logged
First ten minutes of play I ate my loincloth and then got some limbs torn off by a super friendly rat. Thumbs up from me.

G-Flex

  • Bay Watcher
    • View Profile
Re: A question (or more) to the C++ programmers about pointers
« Reply #22 on: October 18, 2009, 06:51:14 pm »

Oh, vectors internally use pointers too. You just don't need to bother with them as much yourself because you're doing more random-access stuff.
Logged
There are 2 types of people in the world: Those who understand hexadecimal, and those who don't.
Visit the #Bay12Games IRC channel on NewNet
== Human Renovation: My Deus Ex mod/fan patch (v1.30, updated 5/31/2012) ==

qwertyuiopas

  • Bay Watcher
  • Photoshop is for elves who cannot use MSPaint.
    • View Profile
    • uristqwerty.ca, my current (barren) site.
Re: A question (or more) to the C++ programmers about pointers
« Reply #23 on: October 18, 2009, 07:09:52 pm »

An array IS a pointer. However, i[3]  is basically *(i+(3*{size of each element})). However, the compiler knows it is an array and can make optimizations.

It is likely that a vertor is just an user-friendly array, that keeps it's size and when you add or remove things automatically resizes.
Logged
Eh?
Eh!

G-Flex

  • Bay Watcher
    • View Profile
Re: A question (or more) to the C++ programmers about pointers
« Reply #24 on: October 18, 2009, 07:26:59 pm »

An array IS a pointer. However, i[3]  is basically *(i+(3*{size of each element})). However, the compiler knows it is an array and can make optimizations.

I know. I just explained most of that myself. Sorry if I was unclear there, I guess.

Quote
It is likely that a vertor is just an user-friendly array, that keeps it's size and when you add or remove things automatically resizes.

Sort of, yeah. It's like an array in the sense that it's a good random-access container and internally probably uses a dynamically-allocated array in order to store the actual data, but it's also a lot more in the sense that it's a full-fledged C++ template container class and provides all kinds of functions to manipulate them.
Logged
There are 2 types of people in the world: Those who understand hexadecimal, and those who don't.
Visit the #Bay12Games IRC channel on NewNet
== Human Renovation: My Deus Ex mod/fan patch (v1.30, updated 5/31/2012) ==

Eagleon

  • Bay Watcher
    • View Profile
    • Soundcloud
Re: A question (or more) to the C++ programmers about pointers
« Reply #25 on: October 19, 2009, 11:52:33 pm »

Oh god pointers... <3 pointers. I used to hate them, thought they were pointless. Eheh. Pointers are wonderful wonderful things, but yeah, avoid using them directly if possible. Read, if they aren't useful. They're all kinds of headache for memory management. They might not be useful for you, but...

I absolutely despise C++ and refuse to use it except in a linked library, so I'm not a lot of help with the code itself. Maybe C++ really doesn't need them. The optimization for linked lists versus arrays sounds useful at least.

In Freebasic, at least, they're necessary if you want an object that can grow its own components. One of the few things that bug me about the language (and this is tangental and not really relevant to C++) is that you can't have dynamic arrays inside user-defined-types (which are basically Freebasic's objects). Fortunately, it's possible to make a pointer in the object, store a size variable saying how large the 'array' is, allocate an appropriate amount of memory determined by whatever type the pointer is pointing to times the size of the array, and deallocate/allocate more + change the size variable as necessary.

Yes, using C++ would solve all of this. Yes, FreeBasic's OOP implementation is funky and incomplete. I don't have to deal with pointless semicolon omission errors and unreadable/barely type-able awkward code. So nyah :D Not sure what the point of this post is, except maybe one explanation for why they might be actually essential to use in any particular language O.o And I was feeling wordy, hehe. Sorry.
« Last Edit: October 19, 2009, 11:54:40 pm by Eagleon »
Logged
Agora: open-source, next-gen online discussions with formal outcomes!
Music, Ballpoint
Support 100% Emigration, Everyone Walking Around Confused Forever 2044

Outcast Orange

  • Bay Watcher
  • [SOMETIMES_SQUID]
    • View Profile
    • The Outcast Orange
Re: A question (or more) to the C++ programmers about pointers
« Reply #26 on: October 20, 2009, 12:24:04 am »

I've only been programming in C++ for a few months and all of the syntax feels natural already.
My pinkies are bracket-building machines!
Logged
[7:53:55 PM] Armok, why did you demand that I don't eat you?
[7:54:34 PM] [Armok]: woooooo

Burried Houses - Platform Explorer Demo H - Cloud Scream

qwertyuiopas

  • Bay Watcher
  • Photoshop is for elves who cannot use MSPaint.
    • View Profile
    • uristqwerty.ca, my current (barren) site.
Re: A question (or more) to the C++ programmers about pointers
« Reply #27 on: October 20, 2009, 06:44:27 am »

Actually, Eagleon, that is how you do it in C, too. If you want an array of structs of unknown length, you use an array of pointers and a length variable(Unless you use some other method, such as a zero terminated array? That would be at least a bit odd).

This is because the compiler needs to know the exact size of the type, for arrays and memory allocation, and a resizable data structure inserted directly would be a problem. So, you put the resizable parts outside, and keep a fixed-size pointer, so that the computer can predict the size.
Logged
Eh?
Eh!

Alexhans

  • Bay Watcher
  • This is toodamn shortto write something meaningful
    • View Profile
    • Osteopatia y Neurotonia
Re: A question (or more) to the C++ programmers about pointers
« Reply #28 on: October 20, 2009, 06:45:57 am »

Quote
I absolutely despise C++ and refuse to use it except in a linked library, so I'm not a lot of help with the code itself. Maybe C++ really doesn't need them.
Am I allowed to laugh? :P  Depends on what you're trying to do.  But yeah, they're inmensely useful.

It's really hard to grasp the concept of pointers until you actually find them useful.  Tutorials are surprisingly lame regarding them. 

anyway... check out my sig.  I think that they did a pretty decent job explaining things over there.
Logged
“Eight years was awesome and I was famous and I was powerful" - George W. Bush.

Jetlaw

  • Bay Watcher
    • View Profile
Re: A question (or more) to the C++ programmers about pointers
« Reply #29 on: October 20, 2009, 09:44:55 am »

I don't see any point in starting a new thread and this is "slightly" related, so here goes.

Code: [Select]
char *szMainMenuChoices[] = {
                              "Start Game",
                              "Quit Game",
                              "Debug String 1",
                              "Debug String Two",
                              "Debug String OVER NINE THOUSAND"
                            };

This is stored in memory in my program as such; {'S', 't', 'a', 'r', 't', ' ', 'G', 'a', 'm', 'e', '\0', 'Q', ...} etc. until {... 'T', 'w', 'o', '\0', '\0', '\0', 'D', ...} - There are three null characters between "Debug String Two" and "Debug String OVER NINE THOUSAND".

I was trying to get a dynamically sized main menu so I have a function that...

Code: [Select]
Input:
char* szString[] = {
                              "Start Game",
                              "Quit Game",
                              "Debug String 1",
                              "Debug String Two",
                              "Debug String OVER NINE THOUSAND"
                            };

int nStrings = (sizeof(szString) / sizeof(char *));

int getCharStringBiggest(char* szString[], int nStrings)
{
   char* pszString;
   pszString = *&szString[0];
   
   int nNumber = 0;
   int nBiggestString = 0;
   int nCurrentString = 0;
     
   while(nStrings != 0)
   {
      if(*((pszString+nNumber)+1) == '\0')
      {
         nStrings--;
         nNumber += 2;
         if(nCurrentString > nBiggestString)
         {
            nBiggestString = nCurrentString;
         }
         nCurrentString = 0;
      }
      else if(*(pszString+nNumber) != '\0')
      {
         nCurrentString++;
         nNumber++;
      }
   }
   
   return nBiggestString;
}

eats each individual character until it reaches the end of the string (a '\0' character) and counts them, eventually spitting out the biggest string of characters before a '\0' is encountered.

Unfortunately this function fails to give the expected return for nBiggestString which is 31 (Debug String OVER NINE THOUSAND) as there are three null characters preceding it.

Now I CAN fix the function to give an additional check that if it hasn't read the final string yet it'll just go through all the null characters until it finally does reach a non-null character and continue as normal.

Before I do this fix I have two questions. Number one is: Can this array be assigned in such a way that it is purely "String" NULL "String" NULL "String" instead of "String" NULL "String" ... "String" NULL NULL NULL "String"?

If not, is there any danger in telling my function to keep jumping over null characters until it finally hits what I expect to be the next part of a string?



For reference, here is the "to be modified" version that will jump over multiple null characters just incase anyone can spot anything blaringly dangerous with my code. It's been tested and works just fine, but that doesn't necessarily mean it will always work or work on someone else's machine.

Code: [Select]
int getCharStringBiggest(char* szString[], int nStrings)
{
   char* pszString;
   pszString = *&szString[0];
   
   int nNumber = 0;
   int nBiggestString = 0;
   int nCurrentString = 0;
   bool bNull;
     
   while(nStrings != 0)
   {
      if((*((pszString+nNumber)+1) == '\0') && bNull == 0)
      {
         bNull = 1;
         nStrings--;
         nNumber += 2;
         if(nCurrentString > nBiggestString)
         {
            nBiggestString = nCurrentString;
         }
         nCurrentString = 0;
      }
      else if(*(pszString+nNumber) != '\0')
      {
         if(bNull == 1)
         {
            bNull = 0;
         }
         nCurrentString++;
         nNumber++;
      }
      else if(bNull == 1 && nStrings != 0)
      {
         nNumber++;
      }
   }
   
   return nBiggestString;
}
Logged
Pages: 1 [2] 3