• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Slavik81

Member
Yeah. That's one of the reasons I think it's a very good language for people new to programming. It ensures the visual shape of the code text reflects the semantics, and doesn't allow laying out the code deceptively.
I don't understand how so many students end up writing code that is indented randomly. There are so many questions I wish I knew the answers to.

Is it that they don't understand what proper indenting looks like? Or do they not care because they don't understand why it's helpful? Or, perhaps, is it not actually helpful for them? Do they even understand the code they wrote with crazy indents?
 

SOLDIER

Member
Trying again with a better working code:

Code:
def main():
    # Zero out the variables
    num1 = 0.0
    num2 = 0.0
    num3 = 0.0
    num4 = 0.0
    num5 = 0.0

    num1 = determine_grade()
    num2 = determine_grade()
    num3 = determine_grade()
    num4 = determine_grade()
    num5 = determine_grade()

    # Run the calc_average and determine_grade functions
    average = calc_average(num1, num2, num3, num4, num5)
    print ('The average score is'), average

def calc_average(num1, num2, num3, num4, num5):
    average_score = (num1 + num2 + num3 + num4 + num5) / 5
    return average_score

def determine_grade():
    score = int(input('Enter your test score: '))
    if score <= 60:
        print ("Your grade is an F")
    elif score <= 70:
        print ("your grade is a D")
    elif score <= 80:
        print ("your grade is a C")
    elif score <= 90:
        print ("your grade is a B")
    else:
        print ("your grade is an A")
    return score

# Call the main function
main()

I just have two problems with this one:

1. It only asks "Enter your test score" five times, where I would prefer it would say "Enter your first test score", "Enter your second test score", and so on.

2. It doesn't print out the average.
 

diaspora

Member
I have a perl file here:
Code:
http://zenit.senecac.on.ca/~int322_153sa08/cgi-bin/lab1/lab1_3cgi.plx

But when I actually go to the URL, I get:
Code:
The requested URL /~int322_153sa08/cgi-bin/lab1/lab1_3cgi.plx was not found on this server.

Which is bullshit since it is there on the server, I wrote it and saved it there using vi.
 
Trying again with a better working code:

Code:

I just have two problems with this one:

1. It only asks "Enter your test score" five times, where I would prefer it would say "Enter your first test score", "Enter your second test score", and so on.

2. It doesn't print out the average.

You should probably use a loop to ask for multiple scores and store the results in a list (unless you haven't learned about that yet, in which case it'd be okay to leave it like this). As for why the average isn't printed, you do the following:
Code:
print ('The average score is'), average
Your parentheses are wrong, you need to do print('something', value). The reason why this is not a syntax error is that this forms a tuple expression with the return value of print (which is None) and the average value. Slightly unfortunate.

Also, zeroing out the variables (num1-5) is unnecessary.
 

SOLDIER

Member
Thanks to a poster from another thread, I got a better looking (and working) code:

Code:
import bisect

def main():
	num_tests = 5
	total = 0
	for i in range(num_tests):
		score = int(input("Enter your test score: "))
		total += score
		print("Grade: ", determine_grade(score))
	print ("\nThe average score is: ", total / num_tests)

def determine_grade(a_score):
	grade = (["F", "D", "C", "B", "A"][bisect.bisect_right([60, 70, 80, 90], a_score)])
	return (grade)

main()

It should be fine as is, but I'll look into making a loop so it asks for "first test score", "second test score", etc.

I also need to create a flowchart for this in Raptor. Anyone able to help me out with that next?
 

Water

Member
I don't understand how so many students end up writing code that is indented randomly. There are so many questions I wish I knew the answers to.

Is it that they don't understand what proper indenting looks like? Or do they not care because they don't understand why it's helpful? Or, perhaps, is it not actually helpful for them? Do they even understand the code they wrote with crazy indents?
1) Some of them don't.
2) Some of them don't.
3) It would always be helpful to them.
4) Often they don't.

You'd understand if you spent enough time teaching or tutoring programming newbies one-on-one. Starting programming requires people to juggle so many things in their heads at once that it's not a simple matter of "knowing" or "not knowing", the people's heads are a mess. They may have been told by a professor or assistant how and why to indent code, but don't remember at all, or would remember when asked but will not actively notice bad indenting in their own code, or will only notice it sporadically.
 

Hypron

Member
Does anyone here has some linking expertise? I have an issue which doesn't make any sense to me and I can't seem to find anything helpful on Google.

I am trying to write a linux C++ program that uses the libsbp library.

So I compiled and installed the c library according to the instructions:
Code:
git clone https://github.com/swift-nav/libsbp.git
cd libsbp/c
mkdir build
cd build
cmake ../
make
sudo make install

Nothing special so far. I checked and a two new files were added to "/usr/local/lib/": "libsbp-static.a" and "libsbp.so" - a static and a shared library. The header files are added to "/usr/local/include/libsbp".

Then I write a short program (well, the actual program I was writing is longer but this one exhibits the same issue):
Code:
// main_test.cpp
#include "libsbp/sbp.h"

int main()
{
	sbp_state_t s;
	sbp_state_init(&s); // Whyyyy?

	return 0;
}

sbp_state_t and sbp_state_init() are defined in libsbp.h:

Code:
/** State structure for processing SBP messages. */
typedef struct {
  enum {
    WAITING = 0,
    GET_TYPE,
    GET_SENDER,
    GET_LEN,
    GET_MSG,
    GET_CRC
  } state;
  u16 msg_type;
  u16 sender_id;
  u16 crc;
  u8 msg_len;
  u8 n_read;
  u8 msg_buff[256];
  void* io_context;
  sbp_msg_callbacks_node_t* sbp_msg_callbacks_head;
} sbp_state_t;
[...]
void sbp_state_init(sbp_state_t *s);

I add everything in an eclipse project and add all the libraries, include paths and everything.

Then I hit the compile button... And I get the following:
Code:
21:27:02 **** Build of configuration Debug for project testsbp ****
make all 
Building file: ../main_test.cpp
Invoking: GCC C++ Compiler
g++ -I"/usr/local/include" -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"main_test.d" -MT"main_test.d" -o "main_test.o" "../main_test.cpp"
Finished building: ../main_test.cpp
 
Building target: testsbp
Invoking: GCC C++ Linker
g++ -L"/usr/local/lib" -o "testsbp"  ./main_test.o   -lsbp-static
./main_test.o: In function `main':
[B]/home/jeremie/workspace/testsbp/Debug/../main_test.cpp:7: undefined reference to `sbp_state_init(sbp_state_t*)'   [<----- what?][/B]
collect2: error: ld returned 1 exit status
make: *** [testsbp] Error 1

21:27:03 Build Finished (took 320ms)

I don't really get what's happening there. It's finding the libsbp-static.a file, otherwise it'd throw an error saying it can't find it. However, it still gives that "undefined reference" error. I tried using the shared library instead and still get the same error.

The build commands used by Eclipse seem right from what I can see:
Code:
g++ -I"/usr/local/include" -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"main_test.d" -MT"main_test.d" -o "main_test.o" "../main_test.cpp"
g++ -L"/usr/local/lib" -o "testsbp"  ./main_test.o   -lsbp-static

Does anyone know what could cause this issue? I've been scratching my head for the past few hours, and I can't progress until I solve this issue :/.
 
Does anyone know what could cause this issue? I've been scratching my head for the past few hours, and I can't progress until I solve this issue :/.

Instead of
Code:
#include "libsbp/sbp.h"

Use
Code:
extern "C" 
{
#include "libsbp/sbp.h"
}

You could also go through the headers files and wrap all the prototypes with extern "C" instead of doing it around your header include. It's just one of those necessities when using a C library in C++.
 
Can someone tell me why I keep getting an error on line 12?

Code:
using namespace std;

1 int main()
2 {
3    double principal, rate, endYear;
4    double t=12;
5
6    cout << "What is the principal? ";                  //get the principal
7    cin  >> principal;
8
9    cout << "What is the interest rate? ";              //get the interest rate
10  cin  >> rate;
11
12  endYear = principal * (1.0 + (rate/12))^t;

    cout << "The principal is " << principal << endl;   //principal out
    cout << "The interest rate is " << rate << endl;   //rate out
    cout << "The the interest rate was calculated " << t << " times" endl;   //t out
    cout << "The end of year total is " << endYear << endl;   //total at the end of year

   return 0;
}
 

Hypron

Member
Instead of
Code:
#include "libsbp/sbp.h"

Use
Code:
extern "C" 
{
#include "libsbp/sbp.h"
}

You could also go through the headers files and wrap all the prototypes with extern "C" instead of doing it around your header include. It's just one of those necessities when using a C library in C++.

Awesome, that worked! I'm pretty sure I read code that contained "extern "C"" before, but I never bothered to actually look up what it did. And now it comes back to bite me in the ass haha.

Thanks a lot for your help anyway :D

I can now actually start writing code instead of banging my head against the desk, which is always good.
 

Slavik81

Member
You'd understand if you spent enough time teaching or tutoring programming newbies one-on-one. Starting programming requires people to juggle so many things in their heads at once that it's not a simple matter of "knowing" or "not knowing", the people's heads are a mess. They may have been told by a professor or assistant how and why to indent code, but don't remember at all, or would remember when asked but will not actively notice bad indenting in their own code, or will only notice it sporadically.
More one-on-one time definitely sounds like it would help. That particular problem is one I never had, and it's hard to relate to.
 

NotBacon

Member
What ife do yall use for assembly? I am lost and miserable in the commsnd line.

Personally I use vim for writing and gdb for debugging.

I'd suggest getting comfortable with the command line and command line tools if you really want to dive into assembly. It depends on your target architecture, as some chips come with an environment for coding, but generally (and especially for x86) learning the command line will make your life easier.
 

leroidys

Member
I have a somewhat random question. So I know that RAM is generally volatile and your data won't persist if you lose power, but what is actually on your RAM if you access a random, unallocated block after turning the power on. Nothing? Zeros? Garbage?
 
What ife do yall use for assembly? I am lost and miserable in the commsnd line.

Vi and Emacs are great for assembler. If you're more comfortable with an IDE such as Eclipse, check it for assembler plugins. Speaking for myself, I think you should give command line a go. The only commands you will need are to edit, to assemble and to run a debugger.
 

NotBacon

Member
I have a somewhat random question. So I know that RAM is generally volatile and your data won't persist if you lose power, but what is actually on your RAM if you access a random, unallocated block after turning the power on. Nothing? Zeros? Garbage?

I believe:
The moment before you power on? Zeroes. Although you can't access them because, well, you're not powered on.
Milliseconds after you power on? Zeroes/garbage depending on the address, as RAM is being flooded with data at this point in time.
 

teiresias

Member
So I'm trying to branch out from my normal embedded coding world where I frequently live in custom IDEs, and am teaching myself some graphics-based coding and getting better acquainted with doing manual build management using make.

I'm wanting to make a simple engine that is sort of like a simple adventure game engine from first-person view (ie. no animation or sprites or scrolling at this point, just static displays drawn from tiled sources) just to get the hang of things. I'm thinking of learning SDL on Linux and also brush up on my C++ in the process (it's been a while since I've had to code a class, I tend to do embedded stuff in purely function-based code).

Would SDL be a good thing to learn for doing this? Is what I learn there going to be somewhat applicable across other things if I decide to branch out? This is strictly recreational and not for work so there's no real time pressure on it or any need to get to a certain point.
 
Would SDL be a good thing to learn for doing this? Is what I learn there going to be somewhat applicable across other things if I decide to branch out? This is strictly recreational and not for work so there's no real time pressure on it or any need to get to a certain point.

SDL is perfectly fine.

I think if your main interest is to put together a game then UDK 4 is a strong option. Unity is good too, but I like a fair amount of what UDK 4 gives you out of the box, and Unity's a ten year old game engine that, while it's done a great job of adapting to new platforms and the plugins ecosystem is quite something, shows its age in a few areas and isn't particularly efficient at what it does.

Now, if you want to get closer to metal with programming against graphics APIs, Three.js and WebGL are worth looking into, have great resources for learning, and WebGL maps pretty closely to OpenGL ES2 and a subset of modern OpenGL. Three.js provides a scene graph API and there's a pretty nice plugin infrastructure out there that you can tap into. There's also a Chrome extension that allows you to introspect that scene graph and GLSL shaders, it's pretty cool stuff.

Yes I know I mentioned a JavaScript API with the words "closer to metal". The common consensus at the last Khronos Group meeting at SIGGRAPH was that WebGL is the least painful way of getting into the -GLs out there, and it's not a big stretch to go from that to C byte buffers and EGL/EAGL hosting some version of OpenGL ES.
 

mooncakes

Member
Can we use this thread for HW? I am really stuck with some of my python HW. This is my most difficult class compared to my business classes.
 

ty_hot

Member
So I am reading about java coding, from the basics (OOP and all), then I will try to create some Android app. This is for personal projects/fun mostly :p

but for next year I should create one program (?) for my phd that collects some info online (through some existent API) and saves it in tables/excel/database. It should run 24/7 as I need all data collected in real time (the sites do not provide old data, only real time data)... it should run and collect data every 5 minutes or so (didn't decide yet but I believe this is a good number).

The database will grow quite fast, in a 5 minute gap between every data collection, and gathering info from around 420 sources I will have over 120,000 numbers per day. I've worked with an Excel file with 6000 rows and columns (36 million numbers), and it was a big pain in the ass. I will reach this number in around 300 days... So based on that it would be better to split the data in several files (even though I think keeping one big file with all data gathered wouldn't be bad, just for backup purposes).

Then I will need to analyze the data. compare data gathered in different days, find correlation etc. This analysis could happen once a day (midnight), or maybe also in 'realtime' (every x minutes/hours).

basically:
-> collect data through online API (existent) and write it in a database/excel/whatever
-> analyze all of it every x hours

Which language would best suit for this?

I heard R is good for data analysis. Is there any way I could run any of this in the cloud for free? If not, how much would it cost?
For the database itself, what is the best option? Is there any difference in the language that I should use to write the program that read the data from the online API? (I think it doesnt matter, but I am no expert in this).

i will need to do some other things but if I will do this the rest will be basically the same.
 

Droplet

Member
Can we use this thread for HW? I am really stuck with some of my python HW. This is my most difficult class compared to my business classes.

I mean, if you need help you can ask as long as you're not posting anything specific. Just specify that it's hw so people can help walk you through. But you should try googling your questions first and see if anything comes up, because 99 out of 100 times, your question's probably been answered, especially if it's a basic class. If you need more conceptual help and are unsure of what to look up, then I think asking here would be fine.

On another note, I can't decide whether I like or hate MATLAB. I find the lack of the most basic programming capabilities slightly infuriating (no default arguments, really?), but being able to just plug in a formula from a paper and have it work with little to no effort is also kind of amazing.
 

mooncakes

Member
I mean, if you need help you can ask as long as you're not posting anything specific. Just specify that it's hw so people can help walk you through. But you should try googling your questions first and see if anything comes up, because 99 out of 100 times, your question's probably been answered, especially if it's a basic class. If you need more conceptual help and are unsure of what to look up, then I think asking here would be fine.

Homework? I'd say homework is a okay as long as it's not a "do my homework" posed as question. See something like http://stackoverflow.com/help/how-to-ask

Got it. thanks guys.
 

Dereck

Member
In Java, if I have this:

Code:
y = y - x / 2;

Let's assume that y and x are both ints, do I do the subtraction of y and x first? or the division of x and 2 first?
 

Dereck

Member
Code:
	    int m = 10;
	    int p = m-1;
	    while (p > 1) {
	        if ((m % p) != 0) {
	            System.out.print(p +", "); 
	        }
	        p--;
	    }
	}
}

I'm trying to get this

m = 10
p = 9
while p is greater than 1
if m mod p does not equal 0
print p plus every number greater than 1?
p minus 1?

So, this would print out

9, because p is 9

8, 7, 6, 5, 4, 3, 2?

How does that p minus 1 affect that print?

And how does m mod p affect it, isn't m mod p 1?
 

Makai

Member
Code:
	    int m = 10;
	    int p = m-1;
	    while (p > 1) {
	        if ((m % p) != 0) {
	            System.out.print(p +", "); 
	        }
	        p--;
	    }
	}
}

I'm trying to get this

m = 10
p = 9
while p is greater than 1
if m mod p does not equal 0
print p plus every number greater than 1?
p minus 1?

So, this would print out

9, because p is 9

8, 7, 6, 5, 4, 3, 2?

How does that p minus 1 affect that print?

And how does m mod p affect it, isn't m mod p 1?
Modulo divides the two numbers and returns the remainder. 2 and 5 would not be printed because they are factors of 10 (10 % n == 0).

p-- just subtracts 1 from p and the while loop would continue infinitely without it. What you've written is equivalent to

Code:
for (int p = m - 1; p > 1; p--)
{
}

P.S. Inequality operator has low priority, so these are equivalent:

Code:
if ((m % p) != 0)

Code:
if (m % p != 0)
 

Dereck

Member
Code:
	    int g = 4;
	    for (int i=g*g; i > 1; i -= 5) {
	        System.out.print("(" + i + "," + g + ") ");
	    }
	    System.out.println();
	}
}

This prints out: (16,4) (11,4) (6,4)

g is 4

for, i is 16

i is greater than 1, i equals i - 5

So we subtracted 5 from 16 until we got to a point to where we couldn't go to 1 or below 1?
 

Koren

Member
Not sure if I understand the question, but it's like this:

g = 4

i = g*g (so i=16)

i>1 is true, enter the loop

System.out.print(16, 4)

i -= 5 (so, i=11)

i>1 is true, go on

System.out.print(11, 4)

i -= 5 (so, i=6)

i>1 is true, go on

System.out.print(6, 4)

i -= 5 (so, i=1)

i>1 is false, exit the loop
 

Dereck

Member
I'm trying to make a method that would house all of these booleans:

boolean tennis = true;
boolean hair = false;
boolean screen = true;
boolean tip = false;

The method would start out like public static boolean __________ {

Not sure what goes there.
 

vypek

Member
I'm trying to make a method that would house all of these booleans:

boolean tennis = true;
boolean hair = false;
boolean screen = true;
boolean tip = false;

The method would start out like public static boolean __________ {

Not sure what goes there.

The name of the method is what goes there.

public static boolean trueOrFalse
{
boolean tennis .....
...
...
}

Name it whatever you please as long as you think it will be fitting
 

Dereck

Member
I'm trying to figure out which of these expression return true from

boolean tennis = true;
boolean hair = false;
boolean screen = true;
boolean tip = false;

Code:
tennis && hair
		
tennis || hair || screen
		
!tip
		
(tennis || hair) && (hair || tip)
		
!tennis && (!hair || screen || tip)
		
!tennis || (!hair || screen || tip)

Just looking at it, this is what I'm coming up with:

tennis && hair = false
!tip = true
(tennis || hair) && (hair || tip) = false
!tennis && (!hair || screen || tip) = false
!tennis || (!hair || screen || tip) = false

I don't think I understand

EDIT: I'm reading this right now
 

vypek

Member
I'm trying to figure out which of these expression return true from

boolean tennis = true;
boolean hair = false;
boolean screen = true;
boolean tip = false;

Code:
tennis && hair
		
tennis || hair || screen
		
!tip
		
(tennis || hair) && (hair || tip)
		
!tennis && (!hair || screen || tip)
		
!tennis || (!hair || screen || tip)

Just looking at it, this is what I'm coming up with:

tennis && hair = false
!tip = true
(tennis || hair) && (hair || tip) = false
!tennis && (!hair || screen || tip) = false
!tennis || (!hair || screen || tip) = false

I don't think I understand

It is kind of like just doing truth tables. The evaluations will determine if the code will run a block of code or not and luckily, everything you are evaluating here is done with one or two conditions.

True and True returns true
True and False returns false
False and True returns false
False and False returns false


EDIT: Actually that page you edited in that you are reading will actually tell you what you need to know in a more robust manner.
 

Makai

Member
I made Tic Tac Toe in Haskell. Programming in a purely functional language has proven to be almost as hard as my first days of programming. I needed help from a friend to finish it.

Code:
import Data.List
import System.IO

data Team = None | X | O deriving (Eq, Show)
data Cell = Cell Team Int Int deriving (Eq)

main = do
  hSetBuffering stdout NoBuffering
  movePlayer startingCells X

size = 2

startingCells = [Cell None x y | x <- [0..size], y <- [0..size]]

movePlayer cells team = do
  drawCells cells
  print (show team ++ "'s Turn")
  cell <- getCell team
  let unchangedCells = delete (teamlessCell cell) cells
      updatedCells = cell : unchangedCells
  if legalMove cells cell
    then
      if victory updatedCells team
        then
          drawCells updatedCells >>
          putStrLn ("Winner is " ++ (show team))
        else
          movePlayer updatedCells $ otherTeam team
    else
      do
        print "Invalid Move"
        movePlayer cells team

getCell team = do
  putStr "Column: "
  column <- getInt
  putStr "Row: "
  row <- getInt
  return $ Cell team column row

getInt = do 
  line <- getLine
  return (read line :: Int)

otherTeam team
  | team == X = O
  | team == O = X

legalMove cells cell = elem (teamlessCell cell) cells

teamlessCell (Cell _ x y) = Cell None x y

victory cells team = any (\f -> f cells team) victories

victories = [horizontalVictory, verticalVictory, forwardSlashVictory, backSlashVictory]

horizontalVictory cells team = or [and [elem (Cell team x y) cells | x <- [0..size]] | y <- [0..size]]

verticalVictory cells team = or [and [elem (Cell team x y) cells | y <- [0..size]] | x <- [0..size]]

forwardSlashVictory cells team = and [elem (Cell team n (size - n)) cells | n <- [0..size]]

backSlashVictory cells team = and [elem (Cell team n n) cells | n <- [0..size]]

--  ___ ___ ___
-- | X |   |   |
--  ___ ___ ___
-- |   | O |   |
--  ___ ___ ___
-- |   |   |   |
--  ___ ___ ___

drawCells cells = do
  putStr . unlines $ getCellString cells
  putStr $ repeatString " ___" size

getCellString cells = do
  row <- [0..size]
  let rowCells = getRow cells row
  let d1 = do
        col <- [0..size]
        let cell = getColumn rowCells col
        return (drawFirstLine cell)
  let d2 = do
        col <- [0..size]
        let cell = getColumn rowCells col
        return (drawSecondLine cell)
  return (concat d1 ++ "\n" ++ concat d2)

drawFirstLine (Cell team x y) = " ___"

drawSecondLine (Cell team x y)
  | x == size = "| " ++ [drawTeam team] ++ " |"
  | otherwise = "| " ++ [drawTeam team] ++ " "

drawTeam team
  | team == None = ' '
  | team == X = 'X'
  | team == O = 'O'

getRow cells row = filter (\(Cell _ _ y) -> y == row) cells

getColumn cells column = head (filter (\(Cell _ x _) -> x == column) cells)

repeatString str 0 = str ++ "\n"
repeatString str n = str ++ repeatString str (n - 1)
 

-KRS-

Member
I'm trying to teach myself how to use sqlite in C. I've never done anything with databases before really. I'm trying to create a database that stores info about people, like their name, age, number etc. I want to get this data from user input which I then store in a struct. That part works fine, but I get a segfault when trying to concatentate the data into the char pointer that holds the SQL statement. Here's the function that adds an entry to the database.
Code:
void create_entry(struct Person *data)
{
    int i;
    sqlite3 *db;
    char *zErrMsg = 0;

    if (sqlite3_open("abook.db", &db) == SQLITE_OK) {
        /* Create table if it doesn't exist */
        char *sql = "CREATE TABLE IF NOT EXISTS PEOPLE (" \
                    "ID INT PRIMARY KEY NOT NULL," \
                    "NAME TEXT NOT NULL," \
                    "AGE INT NOT NULL," \
                    "ADDRESS TEXT NOT NULL," \
                    "ZIP INT NOT NULL," \
                    "CITY TEXT NOT NULL," \
                    "COUNTRY TEXT NOT NULL," \
                    "PHONE TEXT NOT NULL );";

        if (sqlite3_exec(db, sql, callback, 0, &zErrMsg) != SQLITE_OK) {
            fprintf(stderr, "SQL error: %s", zErrMsg);
            sqlite3_free(zErrMsg);
        }

        /* How many rows does the table have? */
        int rows = 0;
        sqlite3_stmt *stmt;
        sql = "SELECT COUNT(*) FROM PEOPLE";

        if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) == SQLITE_OK) {
            if (sqlite3_step(stmt) == SQLITE_ERROR) {
                fprintf(stderr, "Error counting rows %s", sqlite3_errmsg(db));
                exit(0);
            } else {
                rows = sqlite3_column_int(stmt, 0);
            }
        }
        sqlite3_finalize(stmt);

        /* Add entry to table */
        sql = "INSERT INTO PEOPLE (ID,NAME,AGE,ADDRESS,ZIP,CITY,COUNTRY,PHONE) " \
              "VALUES (";
        char *srows;
        sprintf(srows, "%d", rows);
        strcat(sql, srows);         strcat(sql, ", ");
        strcat(sql, data->name);    strcat(sql, ", ");
        strcat(sql, data->age);     strcat(sql, ", ");
        strcat(sql, data->address); strcat(sql, ", ");
        strcat(sql, data->zip);     strcat(sql, ", ");
        strcat(sql, data->city);    strcat(sql, ", ");
        strcat(sql, data->country); strcat(sql, ", ");
        strcat(sql, data->phone);   strcat(sql, " );");

        if (sqlite3_exec(db, sql, callback, 0, &zErrMsg) == SQLITE_OK) {
            fprintf(stdout, "Successfully added entry to database\n");
        } else {
            fprintf(stderr, "SQL error: %s\n", zErrMsg);
            sqlite3_free(zErrMsg);
        }
    } else {
        fprintf(stderr, "Error opening database: %s\n", sqlite3_errmsg(db));
        exit(0);
    }
    sqlite3_close(db);
}

I'm pretty sure that strcat isn't the right way to go about this so I'm not surprised it fails. I guess I should allocate memory with malloc or something? Pretty much I'm just wondering what's the right way to do this, as well as just asking for overall advice on the code. I'm wondering about re-using the "sql" pointer like I'm doing. I'm not sure if that's a good idea or not. Probably not. I haven't coded anything for a long time now so I've become a bit rusty. :)
 

poweld

Member
I'm pretty sure that strcat isn't the right way to go about this so I'm not surprised it fails. I guess I should allocate memory with malloc or something? Pretty much I'm just wondering what's the right way to do this, as well as just asking for overall advice on the code. I'm wondering about re-using the "sql" pointer like I'm doing. I'm not sure if that's a good idea or not. Probably not. I haven't coded anything for a long time now so I've become a bit rusty. :)

Your problem is you're trying to modify a string literal.

Code:
char *aString = "some text";
allocates the memory for that string literal, and hands you back a pointer to its read-only location. You are then attempting to append to it using
Code:
strcat
causing the exception you're seeing.

As you mentioned, you should instead allocate memory for the string and *place* the substrings inside instead.
 

poweld

Member
I made Tic Tac Toe in Haskell. Programming in a purely functional language has proven to be almost as hard as my first days of programming. I needed help from a friend to finish it.

I had the same experience. Started using Scala around 2 years ago, 5 years into my professional experience. Everything felt like it was turned on its head. The good news is that after I got more comfortable with FP, it was a euphoric experience. Adjusting logic, multithreading, working with complicated/deeply nested structures all became much easier to write and read.
 

teiresias

Member
SDL is perfectly fine.

I think if your main interest is to put together a game then UDK 4 is a strong option. Unity is good too, but I like a fair amount of what UDK 4 gives you out of the box, and Unity's a ten year old game engine that, while it's done a great job of adapting to new platforms and the plugins ecosystem is quite something, shows its age in a few areas and isn't particularly efficient at what it does.

Now, if you want to get closer to metal with programming against graphics APIs, Three.js and WebGL are worth looking into, have great resources for learning, and WebGL maps pretty closely to OpenGL ES2 and a subset of modern OpenGL. Three.js provides a scene graph API and there's a pretty nice plugin infrastructure out there that you can tap into. There's also a Chrome extension that allows you to introspect that scene graph and GLSL shaders, it's pretty cool stuff.

Yes I know I mentioned a JavaScript API with the words "closer to metal". The common consensus at the last Khronos Group meeting at SIGGRAPH was that WebGL is the least painful way of getting into the -GLs out there, and it's not a big stretch to go from that to C byte buffers and EGL/EAGL hosting some version of OpenGL ES.

I'm actually less interested in the game aspects and mainly just playing around with graphics rendering at lower levels - maybe even get to doing some low-level rendering using 3D math, that sort of thing (think like orginial Wolfenstein level pseduo-3D kind of stuff). So, I'm not even really terribly interested in hardware accelerated 3D at this point (or even 3D at all yet, I'm perfectly fine just doing 2D as simply doing graphics period is novel enough for me, haha!).
 
Top Bottom