Reputation: 30635
I have extracted the contents of a file mapped into memory, into an array which looks like:
char* const arr = static_cast<char *>(file.get_address());
whilst iterating through the array I wish to be able to call:
for(int i=0; i<file.get_size(); i++){
atoi(arr[i]);
}
however, atoi requires type const char* and arr[i] is type char* const. How may I resolve this?
Upvotes: 0
Views: 514
Reputation: 7873
First of all, I question your use of const
in...
char* const arr = static_cast<char *>(file.get_address());
In this case, the const
applies to the pointer, not to what it points at. So, via your arr
pointer, you could do this...
arr[0] = 'a';
...which I think is not what you're trying to protect against. Instead, I think what you really want is:
const char* arr = static_cast<const char *>(file.get_address());
...which resolves what your question was posted about. In this way, you have a pointer that points to characters that can't be changed (at least not directly through that pointer).
Then, in your loop, you're calling atoi() on each character of the whole file, which I doubt is what you really want to do. Are you expecting a whole bunch of single-digit decimal (base 10) numbers, with no separators? That's the only use case for looping the way you are. For the sake of argument, let's suppose that's what you really want. OK, then, where do you want the results to go? You're not assigning the returned value of atoi() to anything. You're converting the single-digit (presumably ASCII) numbers from text into numeric form, but throwing away the results.
But I think that's probably not what you really want anyway.
Let's rewrite your code so that it will convert the file's first textual value (assuming it's not preceded by garbage) into an integer, and then print it. As in your example, we'll assume the file is already read into some object named file
and that we can get its data buffer by calling file.get_address()
. Here's what you'd want:
const char* arr = static_cast<const char *>(file.get_address());
int firstNumericValue = atoi(arr);
std::cout << "firstNumericValue = " << firstNumericValue << "\n";
...and that's all, no looping required! If you want to read in multiple values from the file, of course you could use looping, but you'll want to look into more advanced functions, such as sscanf()
or strtol()
. If you use strtol(), its second argument lets you get a pointer to the next place to begin converting for any subsequent calls. But examples for these abound, and you can research them yourself.
Upvotes: 3
Reputation: 26633
atoi(&(arr[i]));
will do the trick.
The &
operator gives you a pointer to the char and the extra parentheses ensure that you are getting a pointer to the i
-th element.
atoi doesn't care about the const on the array declaration, so it isn't relevant here.
Upvotes: 2