So why does this happen?
If you try to call an explicit constructor with an implicit expression then obviously it's going to fail. That's what explicit
means.
So why does this happen?
If you try to call an explicit constructor with an implicit expression then obviously it's going to fail. That's what explicit
means.
Most likely 1,048,576 items the size of Cand is too much memory for malloc() to find and allocate in a single contiguous block. You might be able to call perror() for a more useful error message, but I'm willing to bet even if you do get a message, it'll be along the lines of what I just said.
Try allocating fewer items.
First step: check to see if malloc() failed before dereferencing ptrCand:
Cand* ptrCand = (Cand*)malloc(sizeof(Cand)*rows*cols);
if (!ptrCand)
{
cout << "malloc() failed!" << endl;
}
else
{
ptrCand[16*1024+16].status = 0.5; /* exception happens here*/
}
might be at the top of the file today and tomorrow i change that file with some other commands and now tbe ip is going to be somewhere in the middle or even at the bottem of the file...
That shouldn't matter at all. For example, just read each line and process the label accordingly:
while (getline(in, line))
{
string label = GetLabel(line);
string value = GetValue(line);
if (label == "ip")
{
...
}
else if (label == "something else")
{
...
}
else if (label == "thing")
{
...
}
else if (label == "another thing")
{
...
}
}
Obviously this approach involves a potentially long chain of if statements, but there are ways to handle the verbosity if you have more than a handful of labels with unique processing needs. One such method is the table lookup approach:
while (getline(in, line))
{
string label = GetLabel(line);
string value = GetValue(line);
options[label](value);
}
Where beforehand you set up a dictionary of labels and corresponding functions or function objects:
map<string, void(*)(string const&)> options;
options["ip"] = &SetIp;
options["something else"] = &SetSomethingElse;
options["thing"] = &SetThing;
options["another thing"] = &SetAnotherThing;
I dont know if you ever made a program that is suppose to do something and that is detirmend by command in a file.
I have, many times.
i try to read the file but i cant read it in the correct way so that i can process the string word by word so that i can easily give diffirent integers, strings, chars values speciefied in the file. thus also doing certein functions...
It completely depends on the format of the file. For a simple format, such as this one:
ip=127.0.0.1
port=80
login=fooby
password=ZG9vYnk=
If I were doing it manually, I'd read a line, split it on '=', then assign the value to the appropriate runtime setting based on the key:
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <sstream>
#include <string>
using namespace std;
class IniOption
{
public:
IniOption(string const& s, char delim = '=');
string const& Key() const { return _key; }
string const& Value() const { return _value; }
private:
string _key;
string _value;
};
IniOption::IniOption(string const& s, char delim)
{
istringstream iss(s);
if (!(getline(iss, _key, delim) && getline(iss, _value)))
{
throw runtime_error("Invalid INI format");
}
}
int main()
{
ifstream in("test.txt");
if (in)
{
string line;
while (getline(in, line))
{
try
{
IniOption ini(line);
cout << "Setting " << ini.Key() << " to '" << ini.Value() << "'" << endl;
}
catch (exception const& ex)
{
cout << ex.what() << endl;
}
}
}
}
That's obviously a naive …
I'm not sure I understand what the problem is. Can you describe it in a different way?
Why should I override my constructors or add a move/copy to this class as the compiler suggests?
As the compiler suggests? I assume you're getting a warning to that effect, what does it say?
Input using the >> operator is delimited by whitespace, so by default you'll only read the next "word" in the stream. If you want a full line, use getline().
A heap is like a binary search tree, but it isn't one. The heap property is less strict in that you can't tell from the current node whether to search the left or right subtree.
All you know is that the item in the current node is a match, couldn't possibly be in one of the subtrees (because it would have been higher than the current node), or the item exists in one of the subtrees. Therefore you have no choice but to search every node in one way or another. General search gives you an average case of O(N/2), which reduces to O(N).
while (1)
{
// All your stuff
comand.clear(); // Here
}
You don't clear command
anywhere in that snippet. If it's not cleared anywhere else, then I'm not surprised that the previous data remains. After each iteration of the outer loop you can just say command.clear()
to make it empty.
Or is this about a totally different thing?
Yes, totally different. You're thinking of fatal errors that halt execution without any chance for recovery. The return value from main() is for a graceful exit. Let's say you try to allocate memory and it fails. That's an error that can be caught and potentially recovered from, but if it can't be recovered from, exiting with an error status is reasonable:
#include <iostream>
#include <new> // For bad_alloc
#include <cstdlib> // For EXIT_FAILURE
using namespace std;
int main()
{
try
{
int* mem = new int[12345];
...
delete[] mem;
}
catch (bad_alloc const& ex)
{
cerr << "Error allocating memory: '" << ex.what() << "'\n";
return EXIT_FAILURE;
}
}
(1) means that there was something wrong.
While 1 can be an error code, the whole point of using 0 to signify success is because there's only a single success value but a large number of potential error values: anything in the range of int that's not zero.
So a more accurate description is that 0 is a success code sent to the C++ runtime while non-zero is an implementation-defined error code. The only portable values are 0, EXIT_SUCCESS (which is basically defined as 0), and EXIT_FAILURE. EXIT_SUCCESS and EXIT_FAILURE are both defined in <cstdlib>.
What if I want to go from char* to BYTE*? I'd use reinterpret_cast right?
Correct, assuming BYTE isn't defined as char.
From const char* to BYTE* I'd do:
reinterpret_cast<BYTE*>(const_cast<char*>(InitialValue.c_str()))
That's terrifying. First, casting away the const for the result of c_str() is begging for trouble, especially if you or some function you call tries to modify it. Second, the lifetime of the string returned by c_str() is questionable. You'd be much better off making a copy first, if the result is to have any significant life span.
But static_cast doesn't do this sorta thing and neither does dynamic so I'm not sure whether to reinterpret_cast or use c-style casting.
You can think of C-style casts as a god mode cast, they're essentially unrestricted. The C++ casts are restricted to their specific uses. const_cast is an ideal example: it modifies const/volatile qualifiers and nothing else.
If you're using C++ casts, then the best approach would probably be to avoid C-style casts entirely.
//See this cast?
reinterpret_cast<char*>(&lpMsgBuf)
//Why do I have to use reinterpret to cast from a pointer?
The documentation for FormatMessage() says that you need to cast to LPTSTR, not char*
. This distinction is important because LPTSTR could be defined as char*
or wchar_t*
depending on your unicode settings.
In this case, the Windows API is evil. Based on the flags from the first argument, FormatMessage() will treat the fifth argument differently. In one case it's a simple caller provided buffer …
typedef long static_cast<stringFromString>((int, char)) __cdecl;
This is completely nonsensical. Casting is a form of coercion of objects to another type. The bytes of the object are interpreted as the new type. A typedef is not an object.
SmartSetup((char*)World.c_str(), (char*)",f5", 765, 503,(char*)"");
//TO:
SmartSetup(static_cast<char*>(World.c_str()), static_cast<char*>(",f5"), 765, 503, static_cast<char*>(""));
c_str() already returns a pointer to const char, so the only use for a cast when calling SmartSetup() would be to remove the constness of the pointer if SmartSetup() is defined as:
T SmartSetup(char* a, char* b, int c, int d, char* e);
But even then, string literals have special rules that allow such a conversion without incident. It's deprecated, but still legal. ;) Anyway, since the point of the cast is to remove constness, you'd be better off using const_cast:
SmartSetup(const_cast<char*>(World.c_str()),
const_cast<char*>(",f5"),
765,
503,
const_cast<char*>(""));
memcpy(&INH, (void*)((DWORD)Buffer + IDH.e_lfanew), sizeof(INH));
TO:
memcpy(&INH, static_cast<void*>(static_cast<DWORD>(Buffer) + IDH.e_lfanew), sizeof(INH));
This looks hairy regardless of the cast. If Buffer
is already a pointer then there's no need for any cast because all pointers have an implicit conversion to void*
. If Buffer
isn't a pointer then you might be doing something exceedingly risky. I'm not sure why Buffer
is being cast to DWORD
here, and there's no context for me to figure it out. So I'll just assume that Buffer
is a pointer and all casts may be safely removed:
memcpy(&INH, Buffer + IDH.e_lfanew, sizeof(INH));
Parameter names aren't required in a function declaration, though it's generally viewed as poor style to take advantage of that (mis)feature. You can also omit the parameter name if you don't use the parameter, even if it's a definition, which can be useful every now and again to match interfaces:
// Match an expected interface of 3 arguments, but we don't use the 3rd
int add(int x, int y, int)
{
return x + y;
}
Are the DaniWeb registration passwords hashed and salted?
Yup.
When a's destructor is not virtual and either b's or c's IS virtual, the program crashes. I'm not sure why this one happens.
I don't know off the top of my head, but I'd guesstimate that this invokes undefined behavior somehow and crashing was the result.
When a's destructor virtual and b's and c's destructors are not virtual, all three destructors are called. This one is really puzzling me.
Virtualness is inherited whether you specify it or not. Because a's destructor is virtual, b and c inherited that trait and are also virtual.
Finally, is there ever a time when you would not want to define all three destructors as virtual?
If none of the classes are used polymorphically, there's no need for virtual behavior. But I'd probably question a deep inheritance hierarchy that doesn't use abstract classes as the bases.
Initially, this was a quick and dirty way to do this, and worked well, but it's turning out to be quite unwieldy now with all the if-statements. I'm sure there must be more intelligent ways of doing this.
It's funny that right as I hit the "huge list of if-statements" part of your description, my first thought was: why not a table driven approach? That's not always suitable depending on the complexity of your processing logic for each parameter, but it's generally superior in maintanability to a long chain of if statements or a switch statement with umpteen cases:
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
struct Action
{
string parameter;
string value;
Action(string const& init)
{
istringstream iss(init);
// Error checking omitted for brevity
iss >> parameter;
iss >> value;
}
};
// Set up desired actions
//
void Add(string const& value) { cout << "Adding '" << value << "'" << endl; }
void Modify(string const& value) { cout << "Modifying '" << value << "'" << endl; }
void Delete(string const& value) { cout << "Deleting '" << value << "'" << endl; }
// Set up a table of actions and conditions
//
struct ActionLookup
{
const char* parameter;
void (*run)(string const&);
};
ActionLookup lookup[] =
{
{"add", &Add},
{"modify", &Modify},
{"delete", &Delete},
};
const int nLookup = sizeof lookup / sizeof *lookup;
int main()
{
ifstream in("test.txt");
string line;
while (getline(in, line))
{
Action action(line);
// …
My theory is that those libaries are needed for those 'built-in' functions and that those libaries do not exist on my system.
Yup. Your only two options are to find libraries that implement the functions being called, or simulate the functionality by writing definitions for those functions manually.
Sounds good to me.
So, I understand your code. But, how would I implement the member functions?
By how, I mean do I create my own implementation or use the implementation provided in the adaptee class?
You say you understand my code, but your question suggests otherwise. Clearly the member functions are implemented by calling relevant functions from the adaptee. Usually this is just a simple call as in my code. Sometimes it's multiple calls, but you're not rewriting anything that the adaptee already does.
An adapter is really nothing more than a wrapper around another class that exposes a specialized interface. So at its simplest, a stack might be implemented like so:
template <typename T>
class Stack
{
public:
bool empty() const { return _data.empty(); }
void push(T const& x) { _data.push_back(x); }
void pop() { _data.pop_back(); }
T const& top() const { _data.back(); }
T& top() { _data.back(); }
private:
list<T> _data;
};
bool Contains(const char* LiteralType, bool CaseSensitive = true);
This declaration doesn't need to exist at all. const char*
is already handled in your specialization of the overload for T
. So remove that entirely and the compile time error will go away. However, you'll still have a runtime error from this:
std::vector<std::string> TempData; for (size_t I = 0; I < TypeData.size(); I++) TempData[I] = TypeData[I];
Notice how the vector is never properly resized, yet you still try to access an index. Replace that with a call to push_back() and you'll be golden.
I can't reproduce the error because too many things are missing. Can you boil it down into a small and complete program that's compilable as-is? Also, what compiler are you using?
I couldn't reproduce the error on dev and had to sherlock the fix. Are you sure strict warnings are enabled?
I've committed a fix to our code repository. It should make it to production pending Dani's approval. Thanks for the report. :)
First, why does this not cause a stack overflow?
I'd wager that the empty function call was optimized away. You might be able to turn off all optimization switches in your compiler and get it to overflow.
Two, What is the difference between the two below?
The first is direct recursion and the second is indirect recursion. Direct recursion is when a function calls itself, and indirect recursion is where a function is called recursively by a different function that it calls. They're still both recursion, and can still both overflow the stack if not capped by a base case.
erm i learn new thing, its a bad idea to use "using directive" inside a class declaration, because this can leads to ambiguous functions/statements inside the main program.
That argument only applies if you reuse standard library names, which generally isn't a good idea in the first place. While I don't disagree entirely with the advice to limit using directives, I think you should avoid the underlying problem instead of Band-Aid it.
the question is, is it okay to use "using declaration" inside a class declaration?
It's better in that you have more control over which names from the library are exposed. The using declaration lets you choose names onesie twosie while the using directive will pull in everything whether you want it or not.
You pretty much nailed it for a simple class. It gets quite a bit more complex when construction, destruction, inheritance, polymorphism, and especially multiple inheritance enter the picture.
A good book covering the topic is this one.
Well, today in Opera 11.64 I discovered that when text is selected and then clicking the editor, the pasting appears stuck in a loop (pasting 63 quotes).
I was able to reproduce the issue and pushed a fix to our staging environment. It's now pending Dani's approval.
Technically the only thing C supports is pass by value. You can simulate pass by reference using a pointer and dereferencing it, but the pointer itself is still passed by value.
@Deceptikon: Back in the days of Turbo C, I remember folks saying never put an array in the arguments, and instead use its pointer AND the same thing about struct's.
While it's true for struct instances, arrays have always been passed "by pointer", even in the prehistory of C. When you pass an array to a function, a pointer to the first element is created and sent by value, so the only thing that gets copied is an address. Note also that these three declarations of the parameter are completely identical in every functional way:
void foo(int *a);
void bar(int a[]);
void baz(int a[N]);
The latter two declarations are a convenience and under the hood will be treated as if they were the first. In the last declaration, the size of the first dimension is allowed syntactically, but ignored semantically. You can verify this with a simple program that would give at least a warning if the size were meaningful:
void foo(int a[10]) { }
int main(void)
{
int arg[5];
foo(arg); /* Size mismatch? */
return 0;
}
The folks who were saying that an array parameter could be passed by value were mistaken.
I'm tempted to say that if you pass an array of specific size to a function expecting a specific size, it will pass by value, but I don't know.
That's quite impossible if we're talking about a conforming C compiler because passing by value would break the guaranteed …
set_union() assumes that the output iterator points to a collection with enough existing space to hold all of the results. If you're planning on using an empty vector or have set_union() grow the vector then you'll want to do it through a back inserter.
Dani and I have been discussing it furiously for the last couple of days. Hopefully we'll have an idea of what's causing it soon.
I'm writing it so that I don't have to worry about deleting anything everytime I allocate.
While writing your own smart pointer is a good exercise, it shouldn't be preferred over the ones already available in C++11 and Boost. I'd recommend studying the interface for those and how they work for ideas on ways to improve your own Memory class.
Is it possible to overload one operator more than once?
Yes, but only if the parameter types are unique. Operator overloading is no different from regular function overloading in that the signature (not including the return type) must be different for overload resolution to be unambiguous.
I was able to reproduce the issue on Chrome Beta 20.0.1123.27. Clearing the cache corrected it. If you're affected, please try clearing your browser's cache and let us know if the problem persists.
I'm going to go into pedantic mode for a bit. Apologies if either of you are offended in the process.
#include <conio.h>
C is a widely portable language, which means it's possible to take code and compile it on a multitude of operating systems and compilers without any changes. But that doesn't mean code is always portable; it's the job of the programmer to make sure that code is as portable as possible while still doing what needs to be done.
Now, that said, conio.h is not a portable library. Even if a compiler supports it, the functions that are supported within can vary greatly. One excellent example is the clrscr() function which is only supported (to the best of my knowledge) by Borland compilers, yet it's very commonly--and unnecessarily--included as a first step in many example programs:
#include <stdio.h>
#include <conio.h>
int main(void)
{
clrscr(); /* Not needed and not portable! */
printf("Hello, world!\n");
return 0;
}
On a side note, I'll be happy to explain the issues with clrscr() in another reply if you're interested. The result is that these example programs are only compilable without change on the same compiler used to test them (assuming they were even tested). The closing getch() is another example shown in this thread:
#include <stdio.h>
#include <conio.h>
int main(void)
{
printf("Hello, world!\n");
printf("Press any key to continue . . .");
fflush(stdout);
getch(); /* Not portable and only conditionally needed! */
return 0;
}
Using getch() …
numPerms[ii] = str;
str
is a pointer, that pointer holds the address of word
from main(). After RecursivePermute() runs to completion, every pointer in numPerms
points to the same address.
Given that you've already allocated memory to each element in main(), you can fix both the problem and the obvious memory leak by copying the contents of str
instead of assigning pointers:
strcpy(numPerms[ii], str);
One line changed, problem solved. :) There are other issues with the code, but I won't confuse things by pointing them out.
The short answer is you can't. The long answer is you can if you aren't pedantic about it.
An array can be copied by value by wrapping the array in a structure and then passing an instance of that structure. When the structure instance is copied, the array goes with it as a data member. Technically you're not passing the array by value, you're passing the structure instance by value, but the effect is the same:
#include <stdio.h>
struct foo { int a[10]; };
void bar(struct foo arg)
{
/* Notice how the sizeof trick works */
for (int i = 0; i < sizeof arg.a / sizeof *arg.a; i++)
{
printf("%d ", arg.a[i]);
++arg.a[i]; /* Won't affect the original array in main() */
}
}
int main(void)
{
struct foo x =
{
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
};
bar(x);
putchar('\n');
for (int i = 0; i < sizeof x.a / sizeof *x.a; i++)
{
printf("%d ", x.a[i]);
}
putchar('\n');
return 0;
}
Well, you could take advantage of the way the numbers are patterned. Notice how your triangle fits perfectly if you replace everything less than or equal to N with asterisks, where N starts at 6:
int j;
int x = 6;
for (int i = 1; i < 6; i++, x--)
{
for(j = 1; j < 5; j++)
{
if (j >= x)
{
System.out.print("*");
}
else
{
System.out.print(j);
}
}
for(int k = j; k > 0; k--)
{
if (k >= x)
{
System.out.print("*");
}
else
{
System.out.print(k);
}
}
System.out.println();
}
Obviously this won't work without the incrementing and decrementing number pattern.
When I use Chromium, I am unable to login.
Today I tried my luck with Firefox and it worked.
But I am not sure what the problem with Chromium is..
This is mostly for my own curiosity, but it could also benefit troubleshooting: have you tried Chrome and gotten the same results?
"isDuplicate" is declared in "getScores", so it should be defined first.
I think you're confused. Can you point out exactly what you're referring to?
Shouldn't the boolean "isDuplicate" go before the integer "getScores", so there aren't initialization errors?
The only requirement is that it's declared before use. The given code was only a snippet, which suggests that something along the lines of the following was assumed:
bool isDuplicate(int* student_ids, int head_count, int id);
int getScores(int* student_ids, int* scores, int max_students);
...
int getScores(int* student_ids, int* scores, int max_students)
{
...
}
bool isDuplicate(int* student_ids, int head_count, int id)
{
...
}
I'm not sure I understand the requirement. It looks like start and finish are related, in which case sorting by finish time would be more meaningful like this:
#include <stdio.h>
#include <stdlib.h>
struct ElapsedTime
{
int start, finish;
};
int compare_elapsed(void const* a, void const* b)
{
struct ElapsedTime const* pa = a;
struct ElapsedTime const* pb = b;
return pa->finish - pb->finish;
}
int main(void)
{
struct ElapsedTime times[] =
{
{1, 5},
{5, 11},
{3, 4},
{1, 2},
{5, 9},
};
int n = sizeof times / sizeof *times;
qsort(times, n, sizeof(times[0]), compare_elapsed);
for (int i = 0; i < n; ++i)
{
printf("%d, %d\n", times[i].start, times[i].finish);
}
return 0;
}
The difference being that it's an array of structs where each struct has only a single pair of times, then the array is sorted according to the finish time. This design strikes me as more reasonable, but I am making an assumption based on experience rather than what your actual requirements are.
some one correct my program and let me continue my execution .............
I did take a look at the code, and you're clearly dereferencing null pointers. Here's one example:
a=a->next;
a=malloc(sizeof(struct node));
a->name=c;
a->next=NULL;
The first a = a->next
makes a
a null pointer. Why? Because a
is equivalent to g
from main(), and while g
is a valid node object, g->next
is NULL
. So what you need to do is allocate memory to a->next
, then move to the new node.
But this still doesn't fix the problem because you're basically throwing away all references to the objects you're creating by modifying a
directly and then returning it to be assigned to g
.
The following gins() at least allows the program to run to completion for a very simple test.
struct node* gins(struct node* a)
{
struct node* p = a;
char c;
do
{
printf("\n enter vertex else a space\n");
scanf("%c", &c);
fflush(stdin);
if (c != ' ')
{
p->next = malloc(sizeof(struct node));
p = p->next;
p->name = c;
p->next = NULL;
}
}
while(c != ' ');
return a;
}
Learn to do that yourself. It's very important, and I'm not going to do it for you a second time. You strike me as exceptionally lazy and helpless, and your presumptuous attitude about deserving freebies is irritating as well.
When you display $num_result to the page, what's the value?
echo var_dump($num_result), '<br />';
According to the documentation, the first parameter represents the previous result of the function. In the case of the first call, you'd seed it to "null":
unsigned long checksum = /* Saved checksum */
FILE* fp = fopen("file.txt", "r");
if (fp)
{
unsigned long sum = adler32(0, 0, 0);
char buf[BUFSIZ];
while (fgets(buf, sizeof buf, fp))
{
sum = adler32(sum, buf, strlen(buf));
}
fclose(fp);
if (sum != checksum)
{
panic("Invalid checksum");
}
}
I'm not sure the first parameter is needed unless it refers to the modulus, but that's a fixed number, IIRC. What library are you using? Do you have the source code? If so, what does the body of that function look like?