>> Now I'll work on the fibonacci function.
You need to initialize j
before using it - since it's an automatic variable, it is NOT initialized to zero by the compiler.
>> Now I'll work on the fibonacci function.
You need to initialize j
before using it - since it's an automatic variable, it is NOT initialized to zero by the compiler.
You are probably just doing something wrong or having a configuration issue. You might refer to Eclipse's Help and/or post in a dedicated Eclipse forum.
Maybe I'm misunderstanding the problem .. but if not, then you might store the points clicked in a container (e.g. vector<point>). So that upon drawing, you iterate over the container, drawing every point stored thus far.
If you have MS Word, then open the document in Word and do a Find/Replace, replace two adjacent spaces with a single space.
>> Well, does'nt dereferencing unallocated memory lead to memory access violation
Not necessarily. Simply don't expect anything, that would indicate that something is seriously wrong, to happen.
>> Run-Time Check Failure #2 - Stack around the variable 'a' was corrupted
>> What exactly does the above error mean?
When you build a Debug configuration with /RTCs option on, the compiler inserts code that tries to detect stack corruption - this time you did an out-of-bounds write, which got detected.
>> how can get path of specified exe file?
What does specified mean here?
If you need to know the path of your running program, then use GetModuleFileName().
>> was so clear. nonetheless
Not to me, at least. Generally, just stating that something "does not work" is too vague and is likely to decrease the number of people who are willing to have a closer look at a given problem.
But that aside, what happens when you write to the file, i.e.
file<<name<<""<<surname<<""<<no<<"\n";
Does that match with how you are later reading the file's content? If you open the student.txt in an editor, you'll probably figure out what's wrong.
Some things..
#include <iomanip>
...
char buffer[SOME_SIZE_HERE] = "";
cin >> setw(sizeof(buffer)) >> buffer;
Apparently you are accessing memory to which you have read-access. Generally, there are no built-in safety nets with regards to e.g. reading/writing out of array bounds and other things alike - you just have to be careful.
>> searching does not work pls help
You should be much more specific as to what is not working. You might read Narue's Read This Before Posting - especially the section Describe your problem clearly and fully!.
I think it goes along the lines of ..
// Get current style
LONG dwStyle = GetWindowLong(hWnd, GWL_STYLE);
// Drop WS_SYSMENU
dwStyle &= ~WS_SYSMENU;
// Apply current style
SetWindowLong(hWnd, GWL_STYLE, dwStyle);
and immediately after that, use SetWindowPos() speficying the SWP_FRAMECHANGED flag.
Although, note that this also gets rid of the window's system menu (as implied by the style name).
Person person = *p1;
This is copying the pointer address to the first 4 bytes of firstName in the newly created instance of Person, and then completely undone by line 27:
Sorry, but that is actually not so. Person person = *p1; does a struct assignment, i.e. copying sizeof(Person)
bytes over to the local destination struct person
- hence yielding two identical, distinct person
structs.
The following tries to demonstrate this behaviour ..
#include <stdio.h>
#include <string.h>
#undef NDEBUG
#include <assert.h>
typedef struct
{
char firstName[50];
char lastName[50];
int age;
} Person;
int main()
{
/* Three person structs ... */
Person John = { "John", "Doe", 99 },
clone_1 = { "?", "?", 1 },
clone_2 = { "?", "?", 2 };
/* A pointer to John */
Person * ptr = &John;
/* Initial output */
printf("%s\t%s\t%d\n", John.firstName, John.lastName, John.age);
printf("%s\t%s\t%d\n", clone_1.firstName, clone_1.lastName, clone_1.age);
printf("%s\t%s\t%d\n", clone_2.firstName, clone_2.lastName, clone_2.age);
/* Clone John into clone_1, a struct assignment ... */
clone_1 = John;
/* The two structs are identical */
assert(memcmp(&clone_1, &John, sizeof(Person)) == 0);
/* Clone John into clone_2 dereferencing the pointer, effectively the same as above */
clone_2 = *ptr;
/* The two structs are identical */
assert(memcmp(&clone_2, &John, sizeof(Person)) == 0);
/* Final output */
printf("%s\t%s\t%d\n", John.firstName, John.lastName, John.age);
printf("%s\t%s\t%d\n", clone_1.firstName, clone_1.lastName, clone_1.age);
printf("%s\t%s\t%d\n", clone_2.firstName, clone_2.lastName, clone_2.age);
return 0;
}
/* Output ...
John Doe 99
? ? 1
? ? 2
John Doe 99
John Doe 99
John Doe 99
*/
>> regarding latest c std
You might be interested in the latest draft
Perhaps also see C - Approved standards
In your first case, pDerived
ends up being a NULL pointer. When you call TestD()
through it, the this pointer will also be NULL (inside TestD()
) - hence the crash.
In the latter case, you are trashing memory worth of two ints approximately where your allocated Base object is stored - so, it certainly is not working by any means. Rather just bad luck that it is not crashing also.
>> problem is getting the filename from the switch function back into the main
In order to do that, you need to pass in the address of the pointer (filename) that you will be setting inside this setup() function. C passes arguments by value, i.e. generally arguments passed to a function are copies of the original ones. It's a basic concept you need to wrap your head around.
Maybe you'll understand better if you run the below code.
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
static void setup(int, char **, char **);
int main(int argc, char ** argv)
{
/* Simulate arguments to the program ... */
char * local_argv[] = { "prog.exe", "-f", "foobar", "-c", "file.txt", NULL };
/* Number of them, excluding the terminating NULL */
int local_argc = sizeof(local_argv)/sizeof(*local_argv) - 1;
char *filename = NULL;
/* Pass in the address of the 'filename' pointer ... */
setup(local_argc, local_argv, &filename);
/* Did we get it? */
if(filename)
printf("filename [%s]\n", filename);
return EXIT_SUCCESS;
}
static void setup(int argc, char **argv, char ** arg_filename)
{
/* Only recognize c and f */
const char *optstring = "c:f:";
char option;
while ((option = getopt(argc, argv, optstring)) != EOF)
{
switch (option)
{
case 'c':
/* This modifies the 'filename' pointer inside main() */
*arg_filename = optarg;
break;
default:
printf("skipping [%c] [%s]\n", option, optarg);
break;
}
}
}
P.S. You could use the Preview Post button to see that you've e.g. gotten the CODE tags right.
Line 40 is wrong, what happens there when i == 0
?
Don't set m_pMainWnd
to point to the dialog object, because during the execution of DoModal()
, MFC does a PostQuitMessage()
via the dialog's OnNcDestroy()
(if m_pMainWnd
points to the window being destructed). So, the program terminates as soon as the posted WM_QUIT
gets extracted from the message queue, even though you've created the frame window.
Then, it's not necessary to allocate the dialog object on the heap .. I think the following should work ..
BOOL CBankApp::InitInstance()
{
CLoginDialog Dlg;
if(Dlg.DoModal() != IDOK)
return FALSE;
CBankFrameWnd *pWnd = new CBankFrameWnd();
m_pMainWnd = pWnd;
pWnd -> ShowWindow(m_nCmdShow);
pWnd -> UpdateWindow();
return TRUE;
}
>> i am not receiving any output i pressed ctrl+f9
If you are saying that CodeLite actually fails to run the compiler altogether, then it's probably best to post in CodeLite forum.
dynamic_cast<CTriangle*>(ppoly1)
gives you a NULL pointer, through which the call gets made. If you were to modify the (non-existent) object's state inside the triFunc()
, then you would get a run-time error, but because you just return the constant value (5), it appears to 'work'.
>> The last output to the screen is the prompt to enter the name of the output file.
Once you've gotten out of the initial while() loop, I believe you use Ctrl+Z to stop entering coordinates, cin
has eof bit set, which you must clear() before trying to get any other input (otherwise cin remains non-functional).
>> Then a MS alter window pops up with the message of an unhandled exception.
The exception gets thrown by the error()
function because oname
remains what it is initialized to (" "), look into std_lib_facilities.h for details. You might wrap the code in a try/catch block, i.e.
int main () try
{
< all your code here >
}
catch(std::exception & e)
{
// What does it say?
cout << e.what() << endl;
}
>> How do I check if a member of a struct is null?
Just like you are doing, i.e.
// Is it a NULL pointer?
if(ErrorInfo->TestName != NULL)
{
// No it isn't ...
}
>> debug shows it as 0xccccccc, "")
This value 0xccccccc
tells you that you are dealing with an automatic ErrorInfo
variable, whose TestName
member has NOT been initialized by you - it's an uninitialized variable. The value you see, is set by the Microsoft's debugging runtime library - a handy feature for spotting uninitialized variables.
So, what you need to do, is to initialize the variables. Either write a constructor which initializes the pointers to NULL, or if you are actually writing C instead of C++ ..
struct ErrorInfo errInfo;
errInfo.TestName = NULL;
// Initialize the rest of the members ..
P.S. An overview regarding various fill patterns and such Win32 Debug CRT Heap Internals.
>> I'm now off to learn how to compile to dll in C++, maybe it will hook me
Assuming you have some version of Visual Studio, you might go through MSDN's Walkthrough: Creating and Using a Dynamic Link Library. It's close to the simplest console app/dll configuration that one can have.
P.S. I think you should not underestimate the cheat team's capability/motivation to hack the protection (due to their young age) - there are lots of resources on internet to aid in just that - in other words, be sure to give this a good go ;)
>> when I iterate through login_times, all of them have the same time value
asctime() uses a single static buffer and returns a pointer to this buffer every time you call it. In other words, all pointers that you store in the login_times
array, point to the very same location in memory - hence the behaviour.
How about storing the time_t values inside the login() function and only use localtime()/asctime() when you need a string representation of the times? I.e.
/* Somewhere you'd have ... */
time_t login_times[NUMOFEMPLOYEES] = {0};
int login()
{
...
scanf("%d", &id);
if ( (id < NUMOFEMPLOYEES) && (id >= 0) )
{
...
/* Store the time of login ... */
login_times[login_counter] = time(NULL);
...
and use later ..
printf("login time: %s\n", asctime(localtime(&login_times[ <some valid index here> ])));
>> the compiler is about a year or 2 old.
>> Its a C++/C compiler. gcc
Most likely the code is not a compiled as C, but C++ instead. In C, you don't need to cast return value from malloc(), and moreover, you shouldn't do that.
>> how i will "pass the following switches to the compiler
In the Dev-C++ IDE, there probably is something along the lines Project Options / Compiler Options, where you can specify these additional switches. If you cannot find anything like that, maybe ask your teacher.
I think kes166 pointed out your problems.
I'd just suggest that when you compile your programs, pass the following switches to the compiler (via Dev-C++ IDE) -Wall -Wextra -pedantic
That will enable most of the warnings and generally also warns about (some) non-standard code (like variable length arrays, which you are using).
Also, why not switch from Dev-C++ to say Code::Blocks, which comes with probably ~5 years more recent compiler (and IDE too).
Since this is MFC, see CComboBox::AddString() GetDlgItem()
returns a CWnd *
, meaning that you need a typecast to CComboBox *
.
For example
CComboBox * pCombo = (CComboBox *) GetDlgItem(IDC_COMBO1);
pCombo->AddString("Text");
perror() might come in handy, so perhaps try
void uloz2D(char nazevsouboru[])
{
// You don't need the NAZEVPR2 variable here
printf("%s\n", nazevsouboru);
FILE *soubor2 = fopen(nazevsouboru, "w");
if(soubor2)
{
fprintf(soubor2,"A");
fclose(soubor2);
}
else
{
// Failed, what's the reason?
perror(nazevsouboru);
}
}
Are you sure about your last argument to GetWindowText()
, that is the count of characters that fit in the input buffer. In other words,
char retezec[32] = "";
GetWindowText(GetDlgItem(hwnd, IDB_TEXTBOX1), retezec, sizeof(retezec));
or maybe
TCHAR retezec[32] = _T("");
GetWindowText(GetDlgItem(hwnd, IDB_TEXTBOX1), retezec, sizeof(retezec)/sizeof(*retezec));
I compiled using GCC v4.5.1
I'm having hard time in believing that 4.5.1 would come with the pre-standard file <iostream.h>. Are you sure that your compiler/IDE configurations are OK?
Would be nice to know if Visual Studio 2010 also behaves like this, anyone care to test?
>> Your answer would require to include an additional header file <cstdlib>
My test works fine without this header.The only header I have to include is iostream.h for 'cout'
Your compiler is not standards-compliant then, exit()
needs the <cstdlib>
header. Maybe try out a modern compiler and see if your old code compiles?
>> i find answer
Your answer would require to include an additional header file <cstdlib>, and you cannot do that, given that you only are allowed to modify the function()
function.
I think that the general problem setup suggests something else.
>> then i will tell you that answer
By all means, post back with the answer when you have it.
>> then you will sorry from me
I don't quite understand what that means .. though you sort of sound as having been insulted, if so, how come?
Ok ... I'll admit, I'm lost. I used #defines to declare token strings. I'm not seeing how that will do anything?
You #define
d wrong things then :)
How about us letting this thread get some rest and see if the OP returns?
>> This very much looks like a 'trick' question of some sorts.
Good lord, I see what you mean.. If the teacher actually gave this assigment (s)he should be fired for encouraging this abomination of a code...
--- wait --- see my above post about the possible good outcomes of this problem .. let's not fire the teacher yet, right? ;)
Hunh????? :-O :-/ :confused:
In this case, let's just put aside the non-standard code presented by the OP plus the seemingly 'impossible' basic requirements. It's quite obvious that the "void main()" etc. is not the key topic here, at least from the OP's viewpoint.
Again, like I wrote above, a simple #define solves this 'problem' in 100% standard and portable C++ code. As far as I can see, the only good outcome of this exercise for the OP would be to realize the possible dangers of using macros (e.g. using #defines carelessly).
@OP
It would actually be nice to know how come you are facing this dilemma, would you care to share that with us?
This very much looks like a 'trick' question of some sorts. So assuming that the requirements are that 1) the output must be zero (0) and 2) only the comment block is to be modified .. it can be done in standard C++, here's a hint, replace
void function(int arg)
{
char chars[10];
/*
some statments
*/
}
with
void function(int arg)
{
char chars[10];
#define <something here>
}
So, "<something here>" needs to be replaced with something.
>> ...When i try to get that date back again in the Actor class
>> by the code inception = dateInception.getCharacteristics();
>> I get a result that is like 123441234/1234234234/1234234.
By looking at the code (your first post), this line you mention, only exists within the Actor's constructor, meaning that it returns the newly constructed dateInception
's data - do you have false expectations here? Date::getCharacteristics()
does not work as you have intended ..
Change
string Date::getCharacteristics()
{
...
out >> dateString;
to
string Date::getCharacteristics()
{
...
// Stuff the stringstream content into the string
dateString = out.str();
return dateString;
}
or maybe drop dateString
altogether and simply
string Date::getCharacteristics()
{
...
// Return the string
return out.str();
}
[EDIT]
Just noticed that Actor::getCharacteristics()
also has similar faulty usage of stringstream.
Looks like the troubles start from line #35 onwards.
You could shorten the comparison like so ..
bool operator() (const PdpNetworkLocalKey& lhs, const PdpNetworkLocalKey& rhs) const
{
if(lhs.ip == rhs.ip)
// Todo: Use lhs.isLocal and rhs.isLocal here to order the items as you like
return ???;
else
// Order by ip
return lhs.ip < rhs.ip;
}
>> dude, i'm creating win32 console application......
Ancient Dragon's suggestion will work provided that you #include <windows.h>
If you don't want to pull in the windows.h header, a more lightweight solution would be to use C run-time function _chmod(). To use that function, you need to #include <io.h>
.
Look into the sample's .rc file, especially the three dialog resources; IDM_TEST_BITMAP_BUTTON1, IDM_TEST_BITMAP_BUTTON2 and IDM_TEST_BITMAP_BUTTON3. These are used in conjunction with the CBitmapButtons, in other words, it's pretty much about what you are doing with your dialog editor now.
This is not a simple topic, so take some time to try to understand how it works.
MFC has CBitmapButton class which probably does what you are looking for.
If you don't have the Visual Studio's CTRLTEST Sample installed, you can download it from here. Though depending on which Visual Studio version you have, the downloaded code may need some tweaking in order to compile. Anyway, you need to look into the bbutton.cpp file to get an idea how CBitmapButton is used.
Also, you might search for "CBitmapButton tutorials".
Assuming this is on Windows, you can load the bitmap with LoadBitmap()/LoadImage(), and then set it using the BM_SETIMAGE Message.
The button needs the BS_BITMAP style bit set, but I believe your dialog editor takes care of that.
.. but I don't know how. I will research it and try to fix my question.
The code tag instructions in the link seem to be a bit out-of-sync. Here's a version which should work as of this writing ...
Use code tags!
The easiest way to do this is to select all of your code and then click the [code] button on the message editor. This will automatically wrap the selected text in code tags.
You can also manually type in the tags, like so
[code]
... Your code here ...
[/code]
When you write to the file, sizeof(m_data)
gives sizeof(deque<double>)
. Instead you need sizeof(double)
.
You can split a string literal to multiple lines like so ..
// A single string literal
cout << "This program will "
"add, subtract, multiply, or "
"divide two numbers inputted "
"by the user."
<< endl;
>> This compiles, but it is not working.
The loop condition is backwards (has !
).
You are complicating the reading, to read a double
at a time ..
ifstream myfileIN("data2.bin", ios_base::binary);
double dub;
// As long as sizeof(double) bytes is read ..
while(myfileIN.read(reinterpret_cast<char*>(&dub), sizeof(dub)).gcount() == sizeof(dub))
{
dq.push_back(dub);
}
PS. If you'll be using strtod()
, the buffer must be '\0'-terminated, like nbaztec noted.
A suggestion, you might use stringstream
for extracting the two fields, that would work for both TAB and SPACE -separated fields.
That would be along the lines of ..
#include <sstream> // for stringstream
// Function to perform lookup in provided MAC to hostname file
string search_eaddr(const string & search, const string & hostfile)
{
ifstream in(hostfile.c_str());
if(!in)
{
// Error, do something here ...
}
string line;
while (getline(in,line))
{
// Stuff the line into the stream
stringstream ss(line);
string mac, host;
// Extract, note that any trailing whitespace will NOT end up in 'host'
if(ss >> mac >> host)
{
if(mac == search)
return host;
}
}
return ""; // If no match found, will return an empty string
}
Then a couple of things .. this
if (argc < 2 || argc > 3) // Checks the number of arguments entered by user
{
// If too many or too few arguments provided, program usage will be displayed.
printf("\n Usage: %s <dump_filename> (host_filename) \n\n", argv[0]);
return 1;
}
if (argc == 3) // Checks if MAC to hostname file provided
{
...
could be simplified to
// Checks the number of arguments entered by user
if(argc != 3)
{
// complain here and return
return 1;
}
Then instead of
input2 = fopen(argv[2], "r"); // Verifies that MAC to hostname file exists and can be opened.
if(fopen == NULL)
{
printf("Cannot open host list\n");
return 1;
}
you definitely want to have
…>> I go menu->settings->build settings->select gnu-g++ in the left tree->switch->
>> and change the -l to the -lmapi32
Those are general build settings, shouldn't you rather add the mapi32 library to the current project's configuration? That would be; from the menu, select Workspace / Open active project settings / Linker, then enter mapi32
in the Libraries: field.
That should do it, assuming that you have libmapi32.a in the lib directory.
All the three lines of code below have undefined behaviour and are to be avoided
digit[curpos] = ((digit[curpos]++) % 10);
p = (p++) % 10; // doesn't work
x = (++x) % 10; // works
>> i tried the following statements they also give same output
printf() discards the excess arguments, hence the output is identical in all the three cases.
By the way, please write in full English to make it easier to understand what you are saying.
[EDIT]
I think your code snippet would be better written as e.g.
#include <stdio.h>
/* Instead of 'scanf' use e.g. my_string */
#define my_string "%s is char"
/* main() returns an 'int', explicitly */
int main()
{
printf(my_string, my_string);
return 0;
}