This has to do with what is known at compile time in C. Unless you are using C99 or C++, char *ptr[bufflen] won't compile. In C89/90, the array size must be a compile time constant, meaning that it is either a number or a macro like so:

#define BUFF_LEN 20

// in funcion or global scope
char *ptr_array[20];
char *ptr_array[BUFF_LEN];

If you are writing C89/90, your code is compiling due to a compiler extension. I'm not sure of the rationale behind not allowing VLA (variable length array) initializers, but, since it is only allowed as a compiler extension in C89, all you need to know is the compiler doesn't like it. As for char *strings_line_tokens[503] = {0};, this is standard C code (as far as I know). As a side note, if you write this at global scope, it gets 0 initialized for you, so you dont need the = {0} part.

The work aroung for this is malloc/calloc. Before I go further, I want to make sure you know what you are allocating. char *ptr[20]; is an array of 20 pointers to char. Thus, its size is sizeof(char*)*20 not buflen*buflen*sizeof(char). Since you seem to want to initialize your array with zeros, you should consider using calloc instead of malloc, as it will do it for you:

char *ptrs = (char*)calloc(bufflen, sizeof(char*));
/* use it */
free(ptrs); /* free it */

Calloc takes the number of things you want to allocate as its first parameter and the size of each individual thing as its second one.
For learning purposes, here is what it would look like if you were to initialize it manually:

char *ptrs = (char*)malloc(bufflen * sizeof(char*));
memset(ptrs, 0, bufflen * sizeof(char*));
/* use it */
free(ptrs); /* free it */

If you are intentionally using VLAs (either through an extension or with C99/C++), you could use memset on it the same way:

char* ptrs[bufflen];
/* Since, "ptrs" is an array (not a pointer), sizeof(ptrs) is the same as sizeof(bufflen * sizeof(char*)) */
memset(ptrs, 0, sizeof(ptrs)); 
/* no need to free "ptrs" */

The only difference is that you are using an array on the stack, so you don't have to free it. You do, however, have to free the pointers you get from malloc and calloc, as they are on the heap. Keep in mind, though, that if you store any pointers in your array that point to memory on the heap, you will need to keep track of those pointers ouside of the function or free them before the function returns. Otherwise, you will leak memory.

The last thing I want to mention is that in char *ptrs[20]; "ptrs" is an array while inchar* ptrs = (char*)calloc(20, sizeof(char*)); "ptrs" is a pointer that points TO an array on the heap. Thus, sizeof(ptrs) will evaluate to 20*sizeof(char*) in the array version and sizeof(char*) in the calloc version.

I hope this helped!


My function below is part of a program that compiles and runs. The core of the program is in the function below. The issue is that the variable named "PNL" below as well as "CumLoss" and "CumProfit" don't reset to 0 when the loop "L" restarts. So the output in the output file ends up being a cumulative PNL and cumulative CumLoss and CumProfit instead of the PNL for each individual run of Loop "L".

So the output looks like this:

262.75 60.7542 0.832699 1.28905
735.5 61.9823 0.875953 1.42811
1074.5 62.2238 0.857014 1.41165

Focus on the first column above only, which is the PNL column. What it should look like is this:

472.75 (which is 735.5 - 262.75)
339 (which is 1074.5 - 735.5)

So as you can see the current output is cumulative, instead of outputting each individual run of Loop L (I've set to 3 loops only here to simplify)

Any ideas what I've got wrong in the code below?

Thanks much!

    int BackTest (PriceList& pl, std::vector <Metrics>& R, std::vector <unsigned>& ra, std::vector <unsigned>& h )


                for( size_t i = 1; i < pl.size(); ++ i )

                            if (random conditions)
                                h.push_back (pl[i].Index);

                    int WinCount = 0;
                    int LossCount = 0;
                    double CumLoss = 0;
                    double CumProfit = 0;
                    double PNL = 0;

                for (size_t L = 0; L < 3; ++L) // Monte Carlo loop starts

                    // set variables to 0 for each loop
                    PNL = 0;
                    CumLoss = 0;
                    CumProfit = 0;

                //randomize the vector of prices

                std::random_shuffle (h.begin(), h.end());

                for (size_t r = 0; r < 717; ++ r )

                    ra.push_back (h[r]);
                    std::sort (ra.begin(), ra.end() );


                for (std::size_t i=1; i< ra.size(); ++i) 

                    unsigned r = ra[i];

                    for (unsigned z=1; z<6; ++z)


                        if ( r+z < pl.size() )  

                                double SEntry = (pl[r-1].Low - 0.5);
                                double StopPrice = (pl[r-1].High + 0.5);

                                if (pl[r+z].High >= StopPrice) 
                                        double Loss = SEntry - StopPrice;
                                        CumLoss+= Loss;



                                        if((pl[r+z].High < StopPrice) && (abs(SEntry - pl[r+z].Close) >= 0) )

                                else // else 1   
                                    if((pl[r+z].High < StopPrice) && (abs(SEntry - pl[r+z].Close) >= 0) )

                                        double Profit = abs(SEntry - pl[r+z].Close);
                                        CumProfit+= Profit;

                                    else // else 2
                                        if( (pl[r+z].High > StopPrice) )

                                            double Loss = SEntry - StopPrice;
                                            CumLoss+= Loss;


                                    } //else2

                                } //else1

                            } //if r+z

                        } //for (unsigned z=1; z<6; ++z)

                } // for (std::size_t i=1; i< ra.size(); ++i)

                    PNL = CumLoss + CumProfit;
                    double numerator = (double) WinCount + LossCount;
                    double WinLoss =  (double) WinCount / numerator * 100;
                    double WL = (double) WinCount / numerator;
                    double AvgWin = CumProfit / WinCount;
                    double AvgLoss = abs(CumLoss / LossCount);
                    double Payoff = AvgWin/AvgLoss;
                    double ProfitFactor =( (WL*AvgWin)/ ((abs(1-WL))*AvgLoss) );

                    std::cout << PNL << std::endl;
                    std::cout << CumLoss << std::endl;
                    std::cout << CumProfit << std::endl;

                    R.push_back (Metrics ( PNL, WinLoss, Payoff, ProfitFactor));

                    std::ofstream fout( "BackTestResults.txt");

                    for( size_t i = 0; i < R.size(); ++ i )
                        fout << R[i].PNL << "\t" << R[i].WinLoss << "\t" << R[i].Payoff << "\t" << R[i].ProfitFactor << std::endl;

             } //big Loop ends (intended for monte carlo sim)

                return 0;   

I am trying to pass the address of strings_line_tokens to split_string. I would think I would need the "&" for the address then one of these methods would work.

static void split_string(const char *buffer, size_t buflen, char ***strings_line_tokens)
static void split_string(const char *buffer, size_t buflen, char **strings_line_tokens)
static void split_string(const char *buffer, size_t buflen, char **strings_line_tokens[])
static void split_string(const char *buffer, size_t buflen, char ***strings_line_tokens[])

Here is my declaration and where I try to pass the address to the function.

char *strings_line_tokens[503] = {0};
split_string(line, strlen(line)+1, &strings_line_tokens);

I keep getting some variation of this error.

warning: passing argument 3 of 'split_string' from incompatible pointer type
main.c:73: note: expected 'char **' but argument is of type 'char * ()[503]'

You have written the array of data to a text file, so loading it is a question of
Reading each line from the text file (see any tutorial for reading lines from a text file)
Splitting that line into fields using the tabs as separators (see String's split method)
Storing the fields into your data array

Doing something every 5 seconds (if that is really waht you want) can be done with a java.util.Timer (see the API doc) which will call your save method every 5,000 miliiSecs

Brilliant, thanks! I will try it tomorrow (It's 10 PM local) and I will keep you updated.

Yes I did read these two posts.

My case is a bit different because I'm using char * ptr[buflen]. This is what I have tried:

char  *ptr[buflen] = {0};  //This gave me the variable sized object error. 

char  *ptr[buflen];
memset( ptr, 0, buflen*buflen*sizeof(char)); //I figured this would work with looking at the previous examples. 

//This seemed to work but I am curious if I need to use free or malloc
after looking at the previous examples. I don't want this to seg fault later
in the program and have no clue what is causing it. 
char  *ptr[buflen]; 
memset(ptr, 0, sizeof ptr);

char *strings_line_tokens[503] = {0}; //Why does this work but the above won't work? 

In my deisgn I have three classes derived (Der1,Der2,Der3)from a common class (Base1)
in 2/3 of these classes have same implementation forvirtual function f1().
i.e f1() shares same implementaion for Der1, Der2 . and NO IMPLEMENTATION for Der3.
so I kept f1() implementation in base class Base1, and in Der3 I overrided thsi implementation with NULL IMPLEMTNATION ( {} )
Is this OK ?

Dear all,

I was told to write an application for my assignment that would keep track of contracts. The problem is, I have no clue how I can make this application write JTable into txt file every 5 seconds and wheever application would open, it would read the txt file and display the data in JTable in the correct order.

Here is my code that I am working on currently. Please note that I am still a beginner and this is my first application, so sorry about the untidiness.

import java.awt.*;
import java.awt.event.*;
import java.util.TimerTask;
import javax.swing.*;
import javax.swing.table.TableModel;
public class Main extends JFrame
    // Instance attributes used in this application
    private JPanel topPanel;
    private JTable table;
    private JScrollPane scrollPane;
    // Constructor of main frame
    public Main() throws Exception
        // Set the frame characteristics
        setTitle( "Contract TRACKER" );
        setSize( 900, 800 );
        setBackground( Color.gray );
        //Adding save button
        JButton save = new JButton("Save");
        // Create a panel to hold all other components
        topPanel = new JPanel();
        topPanel.setLayout( new BorderLayout() );
        getContentPane().add( topPanel );
        // Create columns names
        String columnNames[] = { "Contract", "Description", "Deadline", "Contact(s)" };
        // Create some  test data
        String dataValues[][] =
        //    { "12", "234", "67", "122" },
         //   { "-123", "43", "853", "122" },
        //   { "93", "89.2", "109", "fdf" }
        // Create a new table instance
        table = new JTable( dataValues, columnNames );
        //Adding save button
        // Add the table to a scrolling pane
        scrollPane = new JScrollPane( table );
        topPanel.add( scrollPane, BorderLayout.CENTER );

        BufferedWriter bfw = new BufferedWriter(new FileWriter("Core_DATA.txt"));
        for(int i = 0 ; i < table.getColumnCount() ; i++)
        for (int i = 0 ; i < table.getRowCount(); i++)
            for(int j = 0 ; j < table.getColumnCount();j++)
        // Main entry point for this example
        public static void main(String args[] ) throws Exception
            // Create an instance of the test application
            Main mainFrame = new Main();
            mainFrame.setVisible( true );

I would really appreciate it if you could help.

Many thanks,

No, sorry, can't see any problems their either. This is baffling!

ps: I see you are defining local constrants to save typing KeyEvent. All the time
Do you know about import static?

import static java.awt.event.KeyEvent.*;

Then you can just use the public static members from that class without needing to qualify them. eg case VK_UP;

It's not just the save of time/space. You shoiuld assume that somene treading yur code knows the relevant Java, so VK_SPACE will be recognised but CLEAR could be anything.

Nice tip with the static, I do know it so I'm not sure why I didn't bother using it.

"I'm sure tiger86 had been sitting in front of their computers for four years just waiting for your response. Good Job."

It makes me laugh even this will be the second time around.

credits to WaltP, his original post:

"I'm sure Ahmed and Vicky had been sitting in front of their computers for two years just waiting for your response. Good Job."

Hi all!!

I want to play multiple audio file from a folder, but I only play the first file
This is my code :

List<string> wavlist = new List<string>();
wavlist.Add(Application.StartupPath + "\\mp3\\1.mp3");
wavlist.Add(Application.StartupPath + "\\mp3\\2.mp3");
wavlist.Add(Application.StartupPath + "\\mp3\\3.mp3");
wavlist.Add(Application.StartupPath + "\\mp3\\4.mp3");

foreach (string file in wavlist)
WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
wplayer.URL = file;;

Please help me!
Thanks and best regards.