Bay 12 Games Forum

Please login or register.

Login with username, password and session length
Advanced search  
Pages: 1 ... 531 532 [533] 534 535 ... 796

Author Topic: if self.isCoder(): post() #Programming Thread  (Read 882904 times)

Bumber

  • Bay Watcher
  • REMOVE KOBOLD
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7980 on: September 26, 2015, 04:29:52 am »

And C++ gives a warning when you convert int to bool.
It changed in Visual C++ 5.0 (1997), apparently. Bool only uses a single byte under that standard.

I think I was mistaken about cin's return type. It's a bool, not an int. There are a bunch of C functions (e.g. printf) that return ints. I haven't tried using them in C++ comparisons.

ponters and references are, I think, the same thing.
Pretty much. References are used only(?) in function calls. Pointers can store references (addresses) for later use.
int * p = &r
Logged
Reading his name would trigger it. Thinking of him would trigger it. No other circumstances would trigger it- it was strictly related to the concept of Bill Clinton entering the conscious mind.

THE xTROLL FUR SOCKx RUSE WAS A........... DISTACTION        the carp HAVE the wagon

A wizard has turned you into a wagon. This was inevitable (Y/y)?

RoguelikeRazuka

  • Bay Watcher
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7981 on: September 26, 2015, 04:44:34 am »

And could you please check if I understand two-demensional arrays in C correctly? For example, a 4x5 array of float numbers. Why do we need a pointer to pointer? We basically have a series of pointers to float, and ether of the pointers points to a series of float values, right?

We allocate memory for 4 pointers to float, and, as the malloc function returns a pointer to void, we convert the pointer returned into a pointer to pointer to float, so we assign an adress of a pointer to float to a pointer to pointer to float named A, right? And now A remains the address of the first pointer to float, to 'the first line' of the array, right? And these pointers to float follow each other in the memory because we've used malloc to them, right?

Code: [Select]
float **A = (float**)malloc(4*sizeof(float))
Now we need to allocate memory for the 'lines' of the array (for 5 float values in each line). Either of those lines is accessed by a pointer to the first element of the line, right? But the lines, as opposed to the pointers to these lines, are not necessarily placed in the computer's memory sequentially, only the elements (float values) of the same line are, right? And to either of the elements of A (which is naturally an array of pointers to float) we assign the address of the first element (a float value) of a line, right?

Code: [Select]
for (int i=0; i<4; i++)
{
    A[i]=(float*)malloc(5*sizeof(float))
}
 
« Last Edit: September 26, 2015, 05:14:24 am by RoguelikeRazuka »
Logged

RulerOfNothing

  • Bay Watcher
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7982 on: September 26, 2015, 04:50:27 am »

Regarding const in C++ you need to keep in mind how it modifies pointer types:
const int* is a pointer-to-const-int, that is you can change what memory address the variable points to but you can't change the value of what is being pointed at.
int* const is a const-pointer-to-int, that is you can change the value of what is being pointed at but not what address the variable points to.
const int* const naturally is a const-pointer-to-const-int which prevents both changing the address being pointed to and the value of what is being pointed at.
My way of remembering this is that the const modifier modifies what is closest to the const. You also have references-to-const (for example: const Person& p) which is used when you want to avoid copying a large data structure into a parameter but also don't want that structure to be modified in the function.

As for two-dimensional arrays in C, basically you have one-dimensional arrays which are of type T*. Then you want a one-dimensional array of one-dimensional arrays, so you want T**. As for your specific example you want
Code: [Select]
float** A = (float**)malloc(4*sizeof(float*));because A is an array of pointers to float as I stated.[/code]
Logged

Reelya

  • Bay Watcher
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7983 on: September 26, 2015, 04:52:19 am »

It's not really correct to say pointers store references when you use the "&" symbol to take an address. * and & mean different things depending on whether they're part of a type or used in a pointer maths expression.

int& a; // int reference type
int* b; // int pointer type

But if used as part of an expression * and & mean something different to when they're used in a type declaration:

a = *b; // takes a pointer, returns the literal thing it points to (which is equivalent to a reference)
b = &a; // takes a thing, returns a pointer to it.

BTW: you can actually make a c++ reference wherever you want, they just can't be left undefined and need to be set to an actual variable when declared.

EDIT: as for 2D arrays, I basically never use vanilla multi-dimensional arrays. They're not efficient. It's better to make a 1D array then write a custom method to access the cells.
« Last Edit: September 26, 2015, 05:11:15 am by Reelya »
Logged

Dutrius

  • Bay Watcher
  • No longer extremely unavailable!
    • View Profile
    • Arcanus Technica
Re: if self.isCoder(): post() #Programming Thread
« Reply #7984 on: September 26, 2015, 07:01:17 am »

I've had a look at the C# reference, and it seems that the override is in fact unnecessary.

Having said that, the compiler complains that there is already a method called ToString if I omit the override.

"'Inventory.ToString()' hides inherited member 'object.ToString()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword."

Shouldn't it be something like "public string InventoryClass::ToString()"?

You're thinking of C++. C# works slightly differently.
Logged
No longer extremely unavailable!
Sig text
ArcTech: Incursus. On hold indefinitely.

alway

  • Bay Watcher
  • 🏳️‍⚧️
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7985 on: September 26, 2015, 02:29:52 pm »

*snip*
In short, yep.
What people call a 2D array is actually this (addresses and values arbitrarily added for clarity):
Spoiler (click to show/hide)
Numbers over the first elements are the starting address of the allocated blocks of memory; numbers inside are the values.
So, when you create one of these things, you first create the first block of memory in that image (0xab78700).
So the correct operation is actually
float **A = (float**)malloc(4*sizeof(float*)); as was pointed out by the earlier post. In a 32 bit program, yours would work by coincidence, since a float is 32 bits. In a 64 bit program, it would crash, since the pointer size is 64 bits in a 64 bit program.

After that, you allocate the blocks of memory in which you are actually going to be putting your data. When you make your calls to malloc, it returns the pointer values telling you where those newly allocated blocks of memory are (0xbf749030, 0xbc974970, 0xac974310, 0x4683bc70 in this hypothetical case). So you then take those values, and store them in your first array, which essentially is serving as a ledger telling you where to find your other arrays. That's what you're doing with your mallocs in the for loop.

After that, you now have your "2D array" which contains the pointers locating your actual data blocks. You can now fill them with float values at your leisure by looking into your first array for an allocated block's pointer, then following that pointer to its block.
A[2][3] essentially is just doing:
float* B = A[2];
float C = B[3];
composed in a single line.


Something else to keep in mind: when using C++, you should generally avoid this sort of multidimensional array. Calls to malloc are expensive; doing a small number of large mallocs is almost always better than a large number of small mallocs. As implied by the diagram, the memory addresses it gives you can also be scattered around; which results in very slow access times due to cache misses (which occur when the CPU isn't able to predict where data will be coming from next, and so is unable to move it into a nearby cache level; similar to a small-scale version of loading from disk vs from RAM; code using data near other data it recently used helps performance here). For these reasons, it is usually better to do an allocation for RowSize*ColSize, allocate a 1D array, and just index into it with [x+y*width].
Logged

3man75

  • Bay Watcher
  • I will fire this rocket
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7986 on: September 26, 2015, 03:46:40 pm »

Found a problem that I just don't get.

Print a message telling a user to press the letterToQuit key numPresses times to quit. End with newline. Ex: If letterToQuit = 'q' and numPresses = 2, print:
Press the q key 2 times to quit.

Code:

#include <iostream>
using namespace std;

int main() {
   char letterToQuit = '?';
   int  numPresses   = 0;

   /* Your solution goes here  */

   return 0;
}

My solution was to add this line of code: cout << "Press the " << letterToQuit << " key " << numPresses << " times to quit.";

However, the program spits back a "Whitespace differs; see green (missing whitespace) or red (extra whitespace) boxes above."

It shows a green space (which is blank and I assume needs to be filled) under the expected answer. Any tips?

I'm working with something just called characters that are just "char variable = '3';".

The idea seems so simple but I guess not since I can't solvie this. Apparently when I put char to any variable it reserves my number/w.e I use.
Logged

jaked122

  • Bay Watcher
  • [PREFSTRING:Lurker tendancies]
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7987 on: September 26, 2015, 03:59:04 pm »


Something else to keep in mind: when using C++, you should generally avoid this sort of multidimensional array. Calls to malloc are expensive.
--snip
Or you can get a different memory allocation scheme such as the one discussed here, http://goog-perftools.sourceforge.net/doc/tcmalloc.html,
 which looks quite fast. Ultimately you have to understand that you don't want to allocate this kind of thing once, generally. You can reuse the addresses returned as much as you want.

Alternately you can reimplement something like the std::array class and build a custom addressing mechanism. It would look something like
Code: [Select]
template<int N> class m_array_addr{
   size_t args[N];
   public:
     m_array_addr(size_t *args){
        this->args = new size_t[N];
        for(int i=0;i<N;i++)
             this->args[i]=args[i];
    }
};
template<typename T, int N> class multi_array{
 private:
   T *data;
   size_t rank[N];//the number of elements in each dimension
 public:
   T& operator[](const m_array_addr<N>& indx)const{
       size_t index=0;
       for(int i=0;i<N;i++)
           index= indx.args[i]+index*rank[i];
       return data[index];
   }
   
};

I think that's right. It has been a while since I did something akin to this, and that indexing thing is horner's rule, so it ought to work with efficiency about as good as you'll get with machine sized words.

This isn't relevant but  const_cast, reinterpret_cast and static_cast are the most delightful way to smash reference control and make things mutable inside of const methods.

SaintofWar

  • Bay Watcher
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7988 on: September 26, 2015, 04:05:04 pm »

Oh, I like this thread. Since the Alien game thread kinda died, I went back to working on the prototype. but I don't have much time left to program it. Instead, when I get back in a few hours, I'll post some cool and hopefully original stuff that didn't make a feature in the thread in all it's 550 pages. Hopefully. No really.

I'll decompile some C/C++ code and post what comes out and try to figure it out. Pointers as well. Char arrays. Pointer manipulation and what happens. I figure someone will find it interesting-- I know I did years ago when I first saw the machine code and assembly output on my screen and went 'wooooah... wait wtf is this crap?'
Logged

jaked122

  • Bay Watcher
  • [PREFSTRING:Lurker tendancies]
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7989 on: September 26, 2015, 04:14:30 pm »

I'll decompile some C/C++ code and post what comes out and try to figure it out. Pointers as well. Char arrays. Pointer manipulation and what happens. I figure someone will find it interesting-- I know I did years ago when I first saw the machine code and assembly output on my screen and went 'wooooah... wait wtf is this crap?'
don't bother disassembling C or C++, it's only worth it for languages like java, c#, visual basic, or managed c++, but not often then.

Just download some C++ code, randomly, find the most obscure program with open source code, and poke around it, wondering why the person made that program, then how it works. Or start writing code for CataclysmDDA, which is what I did most recently. That was fun.

Added working street sweepers to a zombie roguelike. That makes sense, right?

miauw62

  • Bay Watcher
  • Every time you get ahead / it's just another hit
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7990 on: September 26, 2015, 04:16:27 pm »

Found a problem that I just don't get.

Print a message telling a user to press the letterToQuit key numPresses times to quit. End with newline. Ex: If letterToQuit = 'q' and numPresses = 2, print:
Press the q key 2 times to quit.

Code:

#include <iostream>
using namespace std;

int main() {
   char letterToQuit = '?';
   int  numPresses   = 0;

   /* Your solution goes here  */

   return 0;
}

My solution was to add this line of code: cout << "Press the " << letterToQuit << " key " << numPresses << " times to quit.";

However, the program spits back a "Whitespace differs; see green (missing whitespace) or red (extra whitespace) boxes above."

It shows a green space (which is blank and I assume needs to be filled) under the expected answer. Any tips?

I'm working with something just called characters that are just "char variable = '3';".

The idea seems so simple but I guess not since I can't solvie this. Apparently when I put char to any variable it reserves my number/w.e I use.
The problem says "end with newline", you did not do this.

Welcome to the wonderful world of debugging.

E: Decompiled C code contains a LOT of optimizations done by the compiler, iirc. Also, it mainly consists of a spaghetti of gotos, if the few snippets of decompiled BYOND code I've seen are anything to go off.
« Last Edit: September 26, 2015, 04:18:55 pm by miauw62 »
Logged

Quote from: NW_Kohaku
they wouldn't be able to tell the difference between the raving confessions of a mass murdering cannibal from a recipe to bake a pie.
Knowing Belgium, everyone will vote for themselves out of mistrust for anyone else, and some kind of weird direct democracy coalition will need to be formed from 11 million or so individuals.

Reelya

  • Bay Watcher
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7991 on: September 26, 2015, 05:49:51 pm »

<snip>

If you're running inside some sort of special framework that we don't know about it's also good to tell us what's actually happening on your end. Just saying "it's green" is pretty cryptic. What's green exactly? Your programs output? Luckily this time miauw62 was able to guess the context, but in general not telling us any special programs your running your output inside is going to waste people's time trying to work out why you say weird shit is happening on your end.
« Last Edit: September 26, 2015, 05:56:43 pm by Reelya »
Logged

SaintofWar

  • Bay Watcher
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7992 on: September 26, 2015, 06:47:54 pm »

I meant using some old decompiler- there's quite a few legacy ones that are still around and findable (and won't compile modern code). But if anyone remembers the good ol' book of C programming, written by the authors of C itself, many today would say about the first edition that it was horribly unoptimized. I actually pondered comparing a modern decompile of some of their code, versus one compiled with an old compiler that does only the tiniest bit of optimization.

As for the decompile itself, it's not GOTO's. Labels are just labels. No, what I meant specifically is:

Suppose you declare an array with 5 spaces. Followed by a pointer pointing to the first address space of that array. And then incremented the pointer by 1. What would happen?

Ever wondered how graphical libraries talk with your graphics card? Pure machine code? All that sort of stuff.

I know all of this already, but I figured someone might find it interesting. But maybe I am just old fashioned or something.

EDIT: 5 elements*; disassemble*

EDIT2: I am a bit under the weather, I'll post something more coherent tomorrow. But I believe many got the meaning of what I was trying to convey.
« Last Edit: September 26, 2015, 06:51:23 pm by SaintofWar »
Logged

3man75

  • Bay Watcher
  • I will fire this rocket
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7993 on: September 26, 2015, 06:52:27 pm »

If anyone has ever heard of Zybooks then its that. I go toehri for the 'online portion of my class' (In reality the majority) to do sections of chapters. Each section in the end has challenges on the concepts discussed in the chapter. Such as debugging or using a piece of code.


Basically I used the same code but added endl.

 cout << "Press the " << letterToQuit << " key " << numPresses << " times to quit.";

Thinking back it wasn't too hard..except that one bit at the end. Is it normal to 'know' a concept but have some some particle be missing in your code which stops you getting what you want for hours on end? Or am I just bad at being a new programmer?

<snip>

If you're running inside some sort of special framework that we don't know about it's also good to tell us what's actually happening on your end. Just saying "it's green" is pretty cryptic. What's green exactly? Your programs output? Luckily this time miauw62 was able to guess the context, but in general not telling us any special programs your running your output inside is going to waste people's time trying to work out why you say weird shit is happening on your end.

Will do thanks again everyone.
Logged

Reelya

  • Bay Watcher
    • View Profile
Re: if self.isCoder(): post() #Programming Thread
« Reply #7994 on: September 26, 2015, 06:55:03 pm »

There are no "labels" in machine code. There are only jumps. Which are what we call gotos. If you add labels as part of disassembly, then those are just something you made up, not part of the code.

Quote
Suppose you declare an array with 5 spaces. Followed by a pointer pointing to the first address space of that array. And then incremented the pointer by 1. What would happen?

nothing special happens. Your pointer now points to the second element (element 1) instead of element 0. Since raw C/C++ arrays don't do any garbage collection, nothing would happen.
« Last Edit: September 26, 2015, 06:59:50 pm by Reelya »
Logged
Pages: 1 ... 531 532 [533] 534 535 ... 796