Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
First of all I have searched a lot and also tried many things but unfortunately no solution for my problem.
Below, I tried to compare two char* values. But I do not understand why this does not work. What my intention is that this function performs the sendCommand() only when temp does not equal IDMilight.
Temp values will be different if there is an adjustment to the database.
So if there issn't any adjustment it must delay for 2sec and check again.
I'm pretty new to C++ so I hope someone can help me with this
static char *IDMilight = new char;
static char *temp = new char;
void mysql_query_connection(){
if (!mysql_query(mysql1, "SELECT IDMilight, Hex FROM Milight ORDER BY IDMilight DESC LIMIT 1"))
{
MYSQL_RES* result = mysql_store_result(mysql1);
MYSQL_ROW row = mysql_fetch_row(result);
temp = row[0];
if (*temp != *IDMilight) {
IDMilight = row[0];
hexCode = row[1];
sentCommand();
}
}
}
The following if statments i also tried, but unfortunately that does not work either:
if (temp != IDMilight)
if (&temp != &IDMilight)
And if I print the value's they are not equal to each other.
Since you are pretty new to C++, the right answer is this:
Don't use char*. Try to avoid pointers at all and if you have to use them, use pointer classes like unique_ptr. One simple reason, for example, is that you have to manage memory if those pointers don't simply point at some other variables that exist within some scope. Thus, memory leaks are quite easy to produce if you use pointers. (That said, you can use pointers, but usually you do this in some controlled environment, like wrapped within some class, like a linked list class, or in a very small scope in which you need polymorphy - although again, in such a case you could use unique_ptr or shared_ptr)
Pointers that are essentially arrays like the typically used char* should be replaced by something that wraps arrays. In this case, clearly std::string, which can be used just like char*. In other cases, for example instead of int* or int[] arrays, you'd use std::vector.
Now, you have some function from outside that you need for SQL, that's ok, but try to limit the time in which something stays a char*. Transform char* to string simply by putting it in the constructor: std::string my_string(functions_that_returns_char());, then compare simply by string_1 == string_2. You can access single letters as usual by my_string[some_index]. Take a look yourself for more functionality:
http://www.cplusplus.com/reference/string/string/
That said, I can only second the comment from Baum mit Augen, get a book or read through some tutorials. And be aware that C-style is totally not C++-style, C-programmers will use pointers a lot, for instance.
As for your original question, a pointer that is essentially an array points to the first element of that array. Dereferencing produces that element, not the array. No need to use a pointer here anyway if you could simply directly use the actual array, right?
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Here, in this question, it's stated that there is no realloc-like operator or function in c++. If you wish to resize an array, just just std::vector instead. I've even seen Stroustrup saying the same thing here.
I believe it's not hard to implement one. There should be a reason for not implementing one. The answers only say to use std::vector but not why it's not implemented.
What is the reason for not implementing realloc-like operator or function and preferring to use std::vector instead?
What is the reason for not implementing realloc-like operator or function and preferring to use std::vector instead?
Save time. Don't chase bugs in your own code for a problem that has long been solved. Idiomatic C++ and readability. Get answers to your questions easily and quickly. Customize the realloc part by an allocator.
I believe it's not hard to implement one
That heavily depends on what you need from the template you intend to write. For a general-purpose std::vector-like one, have a look at the source code (libcxx's 3400 line vector header is here). I bet you will revise you initial assumption on the low complexity of such construct.
There's several advantages.
Vector keeps track of its size and capacity, which means you don't have to do this yourself.
Because the current size is part of the vector object itself, you can pass a vector (by reference or by value) without needing an additional size parameter. This is especially useful when returning a vector as the caller doesn't need to receive the size through some side-channel.
When reallocating, vector will add more capacity than is needed to add just the element(s) requested to be added. This sounds wasteful but saves time as fewer reallocations are needed.
Vector manages its own memory; using vector lets you focus on the more interesting parts of your program instead of the details of managing memory, which are relatively uninteresting and tricky to get exactly right.
Vector supports many operations that arrays don't natively support, such as removing elements from the middle and making copies of an entire vector.
realloc's expectation that there might be sufficient free space after the current allocation just does not fit well with modern allocators and modern programs.
(There's many more allocation going on, many allocation sizes go to a dedicated pool for that size, and the heap is shared between all the threads in a program.)
In most cases, realloc will have to move content to a completely new allocation, just like vector does. But unlike vector<T>, realloc does not know how to move elements of type T, it only knows how to copy plain data.
Well, as the other answers have explained nicely about the reason for using vectors, I will simply elaborate on why realloc was not implemented. For this, you need to take a look at what realloc actually does. It increases the size of the memory by intelligently using malloc() and free(). You need to understand, that though it seems to simply increase the size, it does not actually increase the size, but instead allocates another block of memory with the required size (That explains the name realloc).
Take a look at the following lines:
int* iarr = (int*)malloc(sizeof(iarr)*5);
iarr = (int*)realloc(6,sizeof(iarr)); //this is completely discouraged
//what you're supposed to do here is:
int* iarr2 = (int*)realloc(iarr,1 + sizeof(iarr)); //copies the old data to new block implicitly
//this not only saves the previous state, but also allows you to check if realloc succeeded
In C++, this can be (if it is must) achieved, by writing:
int* iarr = new int[5];
int* iarr2 = new int[6];
for(int i = 0; i < 5; i++) {
iarr2[i] = iarr[i];
}
delete[] iarr;
The only use of realloc was to increase the memory capacity; as C arrays did not do that automatically they had to provide a mechanism to do so; which has been implicitly implemented in most of the containers, making the reason for having a realloc in the first place, moot.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Are there any advantage of using normal arrays over array of pointers(and vice-versa)?
When should I use array of pointers and when should I avoid it?
In college, everyone seems to be crazy about pointers. I know std::vector is an easy way out, but it is prohibited to use in college. We're asked to solve stuff without STL for now.
I got an answer from SO (link), but the answer went way over my head.
For example: Is using int array[] better or is int* parray[] better?
int array[] is an array of an int. What it means is it will hold a collection of multiple integer numbers. Imagine it as a place holder that holds a number of integers. When you use int array[] in C++, you must give it a fixed size before you use it:
int array[5]
and the size will be put inside the square bracket [], otherwise it won't compile and will give you error. The disadvantage of using this normal array is you have to know the size of the array first, otherwise the program won't run. What if your estimation size is different from actual use ? What if your estimation is much much larger than the real value ? It will cost you a lot of memory.
int *array[] is not valid in C++. If you want to do a pointer to an array without knwoing the size of the array at run time. Do this:
int *p;
int size;
cout << "How big is the size ?";
cin >> size;
p = new int[size];
That way, you don't need to know the value of size before run time, thus you won't waste memory.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I would like to know which pointer values are invalid so i would not have to allocate new memory just to mark special chunk states(Memory consumption is critical). So i could use them for special states like
0x00000000 - would mean chunk is not loaded
0x00000001 - would mean chunk is empty
0x00000002 - chunk is full. And when some real stuff needs to be saved to the memory i would do new Chunk(...);
I would suggest just using a struct that contains a pointer and an enum. But if for some reason that's inconvenient, just allocate some small structures and use their addresses just to indicate magic pointer values. (Of course, don't ever free them.)
You can also use the address of static objects. Like this:
static int chunk_not_loaded_i, chunk_empty_i, chunk_full_i;
void *chunk_not_loaded = &chunk_not_loaded_i;
void *chunk_full = &chunk_full_i;
if (some_chunk == chunk_not_loaded)
...
Assigning exact values to the pointer is quite unstable and error-prone. That way, your code would be tight to exact hardware architecture(s). For example, some platforms have 0x00000000 as absolutely valid address.
So the fact that address is assigned or not is not related to numeric value of the pointer (at common case).
0x00000000 is equivalent to NULL, which should be replaced by nullptr in C++11 (which does not have a specified numerical value - though, most implementations treat it as 0 to make backwards compatibility easy - that is not guaranteed, though).
It is the only "special" pointer value. All other values are treated as valid pointer values (meaning attempting to use them would attempt to dereference the pointer - and likely will have bad consequences for values like 0x00000001 or 0x00000002). It sounds like you need a container (e.g. pool) that has a state (which could be an enum or some other value you desire). Alternatively, you could use boost::optional<T> or std::pair<T*, bool> to mark pointers as valid or invalid.
Update 2:
Well I’ve refactored the work-around that I have into a separate function. This way, while it’s still not ideal (especially since I have to free outside the function the memory that is allocated inside the function), it does afford the ability to use it a little more generally. I’m still hoping for a more optimal and elegant solution…
Update:
Okay, so the reason for the problem has been established, but I’m still at a loss for a solution.
I am trying to figure out an (easy/effective) way to modify a few bytes of an array in a struct. My current work-around of dynamically allocating a buffer of equal size, copying the array, making the changes to the buffer, using the buffer in place of the array, then releasing the buffer seems excessive and less-than optimal. If I have to do it this way, I may as well just put two arrays in the struct and initialize them both to the same data, making the changes in the second. My goal is to reduce both the memory footprint (store just the differences between the original and modified arrays), and the amount of manual work (automatically patch the array).
Original post:
I wrote a program last night that worked just fine but when I refactored it today to make it more extensible, I ended up with a problem.
The original version had a hard-coded array of bytes. After some processing, some bytes were written into the array and then some more processing was done.
To avoid hard-coding the pattern, I put the array in a structure so that I could add some related data and create an array of them. However now, I cannot write to the array in the structure. Here’s a pseudo-code example:
main() {
char pattern[]="\x32\x33\x12\x13\xba\xbb";
PrintData(pattern);
pattern[2]='\x65';
PrintData(pattern);
}
That one works but this one does not:
struct ENTRY {
char* pattern;
int somenum;
};
main() {
ENTRY Entries[] = {
{"\x32\x33\x12\x13\xba\xbb\x9a\xbc", 44}
, {"\x12\x34\x56\x78", 555}
};
PrintData(Entries[0].pattern);
Entries[0].pattern[2]='\x65'; //0xC0000005 exception!!! :(
PrintData(Entries[0].pattern);
}
The second version causes an access violation exception on the assignment. I’m sure it’s because the second version allocates memory differently, but I’m starting to get a headache trying to figure out what’s what or how to get fix this. (I’m currently working around it by dynamically allocating a buffer of the same size as the pattern array, copying the pattern to the new buffer, making the changes to the buffer, using the buffer in the place of the pattern array, and then trying to remember to free the—temporary—buffer.)
(Specifically, the original version cast the pattern array—+offset—to a DWORD* and assigned a DWORD constant to it to overwrite the four target bytes. The new version cannot do that since the length of the source is unknown—may not be four bytes—so it uses memcpy instead. I’ve checked and re-checked and have made sure that the pointers to memcpy are correct, but I still get an access violation. I use memcpy instead of str(n)cpy because I am using plain chars (as an array of bytes), not Unicode chars and ignoring the null-terminator. Using an assignment as above causes the same problem.)
Any ideas?
It is illegal to attempt to modify string literals. Your
Entries[0].pattern[2]='\x65';
line attempts exactly that. In your second example you are not allocating any memory for the strings. Instead, you are making your pointers (in the struct objects) to point directly at string literals. And string literals are not modifiable.
This question gets asked several times every day. Read Why is this string reversal C code causing a segmentation fault? for more details.
The problem boils down to the fact that a char[] is not a char*, even if the char[] acts a lot like a char* in expressions.
Other answers have addressed the reason for the error: you're modifying a string literal which is not allowed.
This question is tagged C++ so the easy way to solve your problem is to use std::string.
struct ENTRY {
std::string pattern;
int somenum;
};
Based on your updates, your real problem is this: You want to know how to initialize the strings in your array of structs in such a way that they're editable. (The problem has nothing to do with what happens after the array of structs is created -- as you show with your example code, editing the strings is easy enough if they're initialized correctly.)
The following code sample shows how to do this:
// Allocate the memory for the strings, on the stack so they'll be editable, and
// initialize them:
char ptn1[] = "\x32\x33\x12\x13\xba\xbb\x9a\xbc";
char ptn2[] = "\x12\x34\x56\x78";
// Now, initialize the structs with their char* pointers pointing at the editable
// strings:
ENTRY Entries[] = {
{ptn1, 44}
, {ptn2, 555}
};
That should work fine. However, note that the memory for the strings is on the stack, and thus will go away if you leave the current scope. That's not a problem if Entries is on the stack too (as it is in this example), of course, since it will go away at the same time.
Some Q/A on this:
Q: Why can't we initialize the strings in the array-of-structs initialization? A: Because the strings themselves are not in the structs, and initializing the array only allocates the memory for the array itself, not for things it points to.
Q: Can we include the strings in the structs, then? A: No; the structs have to have a constant size, and the strings don't have constant size.
Q: This does save memory over having a string literal and then malloc'ing storage and copying the string literal into it, thus resulting in two copies of the string, right? A: Probably not. When you write
char pattern[] = "\x12\x34\x56\x78";
what happens is that that literal value gets embedded in your compiled code (just like a string literal, basically), and then when that line is executed, the memory is allocated on the stack and the value from the code is copied into that memory. So you end up with two copies regardless -- the non-editable version in the source code (which has to be there because it's where the initial value comes from), and the editable version elsewhere in memory. This is really mostly about what's simple in the source code, and a little bit about helping the compiler optimize the instructions it uses to do the copying.
Greetings everyone. This is my first question here at stackoverflow so please bear with me.
My programming class this semester is Java; last semester was C++. My Java teacher feels (justifiably, I think) that it is very important for we students to understand the mechanics of memory management.
Since Java has automatic garbage collection, he has seen fit to give us an assignment in which we must write a very basic program in C++ that creates a two-dimensional array using pointers. Specifically, we are to first create an array of pointers; each pointer in the first array should reference its own array of integers. Then we must deallocate the memory associated with the two arrays.
This assignment is supposed to consist of two functions: one to allocate the 2-D array, and a second to deallocate. I just want to make sure that the following code is logically sound before I proceed.
I'm sure this all seems very simple, but the hitch is that my C++ teacher spent all of two days on pointers. While I somewhat understand the mechanics, I am pretty clueless on implementation. That being said, the following is a very rough start. Is this logically sound? Am I completely off the mark? My most profound thanks in advance for any help.
EDIT: I have created a new question with updated code. You can view it by clicking Here.
When you use
int* i = new int;
you pair it with
delete i;
and when you use
int* i = new int [12];
you pair it with
delete [] i;
If there are brackets in the new, there should be brackets in the delete. Otherwise, your program looks reasonable to me, except that you haven't implemented those two functions that your prof wants you to.
Looks correct to me, with one exception - when you delete arrays you need the following syntax:
delete [] arrayName;
That's a well-asked question.
I don't think I'd call it a "2-D array": it's an array of arrays, not a 2-D array.
I think I'd call my index i or iColumn or iRow instead of nCount (your nRows and nColumns are logically const and used as fencepost/high-water-mark values, whereas your nCount is a loop index).
For bonus points, think about how to test your solution. You can run it to see if it faults ... but the converse, i.e. not faulting, isn't proof that it's correct. What O/S are you running it on? If you're using Linux then a worthwhile test is to run your code using valgrind (because when you run it valgrind can automatically detect a lot of the ways in which it's possible to misuse memory).
You need to use delete [] instead of just delete.
It looks sound(logically).
By the way - it's ok to run a program and have it fail. :-)