passing character arrays to a function - c++

void PrintPosition (int *,int *,char* arrayLine);
This is my prototype function before int main().
char arrayLine[71]="----------------------------------------------------------------------";
PrintPosition (&Tortoise,&Hare,&arrayLine[]);
This is my int main() where I want pass down arrayLine[71] to a function called PrintPosition.
void PrintPosition (int *Tortoise, int *Hare, char *arrayLine)
{
char arrayLine[71]="----------------------------------------------------------------------";
if(*Tortoise==*Hare)
{
arrayLine[*Tortoise+0]='O';
arrayLine[*Tortoise+1]='U';
arrayLine[*Tortoise+2]='C';
arrayLine[*Tortoise+3]='H';
}
else
{
arrayLine[*Tortoise]='T';
arrayLine[*Hare]='H';
}
cout<<arrayLine<<endl;
}
This obviously doesn't compile at all.
What I am intending to do here, is to pass down the whole character array with size 71 to function, then manipulate char array at the function.
The reason why I am trying this is because I get stack frame error, buffer overrun error, stack around the variable 'arrayLine' was corrupted error. <---when I just declared arrayLine[71] in the function without passing through it.
So the question is, what is the possible method for me to pass down the whole array as I intended?

The way to pass the array to the function is:
PrintPosition (&Tortoise,&Hare,arrayLine);
This is a pass by pointer (with slightly confusing syntax). It is not possible to pass a C-style array by value.
To pass an array by value you would have to use a different sort of array, such as std::array. Using C-style arrays in C++ is discouraged because they do not behave like values.
Of course, you should remove the definition of arrayLine within PrintPosition .

Related

How do declare an array in C++ as a parameter?

I am working with propriety code in my iOS project and all I have access to is the header files for my project. How do you declare an array in C++ so that it will return an array when I make a call?
Here's the header file method,
short WI_GetIDsFromList(int32_t module, int32_t *idsArray, uint32_t *count);
How do you declare an array to received an array of in32_t? I keep getting a parameter error for returnedIdsArray when I make this call? It works perfectly fine for count? I tried making it into a pointer but it did not work?
//Array of ID's
int32_t returnedIdsArray[] = {};
// Array of ID's count
uint32_t count;
rc += WI_GetIDsFromList(mod, returnedIdsArray, &count);
Another Example
short dpCount;
//Get number of data points from the device
WI_GetDatapointCount(modIDHDS, &dpCount);
//dpCount now has returned value of method WI_GetDatapointCount
NSLog#"%d", int(dpCount);
I think Mochi's question is how to declare the array that it suits the need of the function given in the header. If I understand him right, he has no influence to the function taking the array as parameter.
Did you try:
int32_t returnedIdsArray[MaximumExpectedIds];
Maybe there is also a function in the API giving you the number of Ids that you could use to determine the array size.
You cannot pass an array in C or C++, because they will always decay to a pointer to the first element.
You can, however, pass a reference to an array. It retains its array type rather than decay to a pointer, so sizeof() will return the actual size of the array rather than the sizeof pointer, and so on.
void f(char(&charArray)[30])
{
}
Syntax is pretty ugly though. A type alias can help:
using CharArray30 = char(&)[30];
void f(CharArray30 charArray)
{
}
etc. It has restrictions, though. For example, you cannot pass arrays of a different size.
If you need your function to work with various sizes, you can use a function template with a non-type parameter for the size:
template <size_t SIZE>
void f(int32_t module, int32_t(&idArray)[SIZE])
{
// ...
}
I guess that what you are trying to do is to have the function output a set of int values where the length is not known at compile-time.
In C++ an array has a fixed size that must be known at compile-time. The concept of "runtime-sized array" is called vector in C++.
Also, it is more natural to use the return value for values being returned. Your code could look like:
std::vector<int> WI_GetIDsFromList(int32_t mod);
and the calling code could be:
auto values = WI_GetIDsFromList(mod);

Pass Array of pointers to arrays to function where malloc() will occur

I've been avoiding this situation by running malloc() outside the function, but in reality the function knows how big the arrays need to be and the outside can't know how big the arrays need to be.
What I have: uint8_t *jpg[6], which is six pointers to six jpg compressed images which will be malloc-ed by the code that reads in the files. To put it another way this is an array of six pointers to six arrays of indeterminate size.
I have been trying to figure out how to pass the pointer to the pointers into the function so it can malloc() the memory with the known sizes of the jpg data.
I have tried many things but can't get anything to compile.
My latest attempt looks like this and I don't understand why it doesn't work:
Main code:
...
uint8_t *jpg[6];
int size[6]; // returns the size of the images in bytes.
LoadJPG(&jpg, size);
...
Function:
LoadJPG(uint8_t ***jpg, int *size)
{
...
*jpg = (uint8_t *) malloc(blahblahblah);
...
memcpy(**jpg, *indata, blahblahblah);
...
}
Error points to the function call and function:
error: argument of type "uint8_t *(*)[6]" is incompatible with parameter of type "uint8_t ***"
I'm compiling with gcc 4.9.4
In C++ it is undefined behaviour to write into malloc'd space without also creating objects in it. You mention you're learning - a good way to learn is to use simple, idiomatic C++ code.
The program could look like:
#include <array>
#include <vector>
void LoadJPG( std::array<std::vector<uint8_t>, 6> &jpgs )
{
jpgs[0].resize(12345);
// use std::copy or memcpy to copy into &jpgs[0][0]
jpgs[1].resize(23456);
// etc.
}
int main()
{
std::array<std::vector<uint8_t>, 6> jpgs;
LoadJPG(jpgs);
}
For those who are confused like I was, the right way to do it with C structures (in case you're using something antiquated like CudaC and don't want to spend all eternity converting C++ structures to C structures) is really pretty obvious and I feel pretty dumb for not realizing it until this morning.
main:
uint8_t *jpg[CAMERAS];
int size[CAMERAS];
GetRawImagesFromCamera(jpg, size);
...
free(jpg[]);
function:
void GetRawImagesFromCamera(uint8_t **jpg, int *size)
...
for (i=0; i < CAMERAS; i++)
{
jpg[i] = (uint8_t *) malloc(size[i]);
memcpy((void *) jpg[i], (void *) buff[i], size[i]);
...
}
...
This works because arrays are passed by a pointer to the first element. I had convinced myself that I needed to pass a pointer to the pointers, but that's exactly what gets passed when you pass an array.

C++ pass array argument to a function

I want to pass a reference to an array from one object GameModel to another PersonModel, store reference and then work with this array inside PersonModel just like inside GameModel, but...
I have a terrible misunderstanding of passing an array process: In the class PersonModel I want to pass an array by reference in a constructor (see code block below). But the marked line throws the compile error
PersonModel::PersonModel( int path[FieldSize::HEIGHT][FieldSize::WIDTH], int permissionLevel ) {
this->path = path; //<------ ERROR here:
//PersonModel.cpp:14:22: error: incompatible types in assignment of 'int (*)[30]' to 'int [31][30]'
this->permissionLevel = permissionLevel;
}
Here is the header file PersonModel.h
#ifndef PERSON_MODEL
#define PERSON_MODEL
#include "data/FieldSize.h"
namespace game{
class IntPosition;
class MotionDirection;
class PersonModel {
protected:
int path[FieldSize::HEIGHT][FieldSize::WIDTH];
int permissionLevel;
public:
PersonModel( int path[FieldSize::HEIGHT][FieldSize::WIDTH], int permissionLevel );
void setMotionDirection ( MotionDirection* md);
void step(long time);
void reset(long time);
};
}
#endif
As I see now, I can change the int path[FieldSize::HEIGHT][FieldSize::WIDTH]; declaration to int (*path)[FieldSize::WIDTH]; but it is much more confusing.
Help me understand this topic: what is the proper way to store the passed reference to an array to work with it later, like with usual 2D array.
UPDATE:
This array is a map of game field tiles properties represented by bit-masks, so it is read-only actually. All the incapsulated objects of GameModel class should read this array, but I definitely don't want to duplicate it or add some extra functionality.
There are no frameworks just bare Android-NDK.
I think you've fallen into the classic trap of believing someone who's told you that "arrays and pointers are the same in C".
The first thing I'd do would be to define a type for the array:
typedef int PathArray[FieldSize::HEIGHT][FieldSize::WIDTH];
You then don't need to worry about confusions between reference to array of ints vs array of references to ints.
Your PersonModel then contains a reference to one of these.
PathArray &path;
and, because its a reference it must be initialised in the constructors initialization list rather than in the constructor body.
PersonModel::PersonModel( PathArray &aPath, int aPermissionLevel ) :
path(aPath),
permissionLevel(aPermissionLevel)
{
}
Of course, holding references like this is a little scary so you might want to consider using a boost::shared_ptr or something similar instead to make the lifetime management more robust.
You cannot assign arrays as you do with value types in C++
int path[x][y] resolves to the type int (*)[y]
Possible solutions are:
Using memcpy/copy
Using std::array
You can't assign to an array like that. However you can use the fact that an array is a contiguous memory area, even when having an array of arrays, and use e.g. memcpy to copy the array:
memcpy(this->path, path, FieldSize::HEIGHT * FieldSize::WIDTH * sizeof(int));
You would have to pass a pointer to the 2d-array as you cannot pass the array as you have stated in the code snippet.
I would suggest using the STL array type. Admittedly std::array is C++ '11 standard and therefore old compiler may not support it. You can also use vector which has been around longer.
vector<vector<int>>path;
You will have to resize the 2d-vector in the constructor.
Indexing would look a bit funny:
path[1].[1] ....
With vectors, you can then pass it by reference.
the name of the array is a pointer on first element
so,
you can try
PersonModel( int (*path)[FieldSize::HEIGHT][FieldSize::WIDTH], int permissionLevel );
In C++ '=' implemented for primitive types like int and double but not for array(array is not a primitive type), so you should never use '=' to assign an array to new array, instead you should use something as memcpy to copy array. memcpy copy a memory over another memory, so you can use it to copy an array over another array:
// memcpy( dst, src, size );
memcpy( this->path, path, FieldSize::HEIGHT * FieldSize * WEIGHT * sizeof(int) );

Pass character array by value and return a new character array from the function?

I apologise if I'm completely misunderstanding C++ at the moment, so my question might be quite simple to solve. I'm trying to pass a character array into a function by value, create a new array of the same size and fill it with certain elements, and return that array from the function. This is the code I have so far:
char *breedMutation(char genome []){
size_t genes = sizeof(genome);
char * mutation = new char[genes];
for (size_t a = 0 ;a < genes; a++) {
mutation[a] = 'b';
}
return mutation;
}
The for loop is what updates the new array; right now, it's just dummy code, but hopefully the idea of the function is clear. When I call this function in main, however, I get an error of initializer fails to determine size of ‘mutation’. This is the code I have in main:
int main()
{
char target [] = "Das weisse leid"; //dummy message
char mutation [] = breedMutation(target);
return 0;
}
I need to learn more about pointers and character arrays, which I realise, but I'm trying to learn by example as well.
EDIT: This code, which I'm trying to modify for character arrays, is the basis for breedMutation.
int *f(size_t s){
int *ret=new int[s];
for (size_t a=0;a<s;a++)
ret[a]=a;
return ret;
}
Your error is because you can't declare mutation as a char[] and assign it the value of the char* being returned by breedMutation. If you want to do that, mutation should be declared as a char* and then deleted once you're done with it to avoid memory leaks in a real application.
Your breedMutation function, apart from dynamically allocating an array and returning it, is nothing like f. f simply creates an array of size s and fills each index in the array incrementally starting at 0. breedMutation would just fill the array with 'b' if you didn't have a logic error.
That error is that sizeof(genome); will return the size of a char*, which is generally 4 or 8 bytes on a common machine. You'll need to pass the size in as f does since arrays are demoted to pointers when passed to a function. However, with that snippet I don't see why you'd need to pass a char genome[] at all.
Also, in C++ you're better off using a container such as an std::vector or even std::array as opposed to dynamically allocated arrays (ones where you use new to create them) so that you don't have to worry about freeing them or keeping track of their size. In this case, std::string would be a good idea since it looks like you're trying to work with strings.
If you explain what exactly you're trying to do it might help us tell you how to go about your problem.
The line:
size_t genes = sizeof(genome);
will return the sizeof(char*) and not the number of elements in the genome array. You will need to pass the number of elements to the breedMutation() function:
breedMutation(target, strlen(target));
or find some other way of providing that information to the function.
Hope that helps.
EDIT: assuming it is the number of the elements in genome that you actually want.
Array are very limited.
Prefer to use std::vector (or std::string)
std::string breedMutation(std::string const& genome)
{
std::string mutation;
return mutation;
}
int main()
{
std::string target = "Das weisse leid"; //dummy message
std::string mutation = breedMutation(target);
}
Try replacing the second line of main() with:
char* mutation = breedMutation(target);
Also, don't forget to delete your mutation variable at the end.

C++ Why is this passed-by-reference array generating a runtime error?

void pushSynonyms (string synline, char matrizSinonimos [1024][1024]){
stringstream synstream(synline);
vector<int> synsAux;
int num;
while (synstream >> num) {synsAux.push_back(num);}
int index=0;
while (index<(synsAux.size()-1)){
int primerSinonimo=synsAux[index];
int segundoSinonimo=synsAux[++index];
matrizSinonimos[primerSinonimo][segundoSinonimo]='S';
matrizSinonimos [segundoSinonimo][primerSinonimo]='S';
}
}
and the call..
char matrizSinonimos[1024][1024];
pushSynonyms("1 7", matrizSinonimos)
It's important for me to pass matrizSinonimos by reference.
Edit: took away the & from &matrizSinonimos.
Edit: the runtime error is:
An unhandled win32 exception occurred in program.exe [2488]![alt text][1]
What's wrong with it
The code as you have it there - i can't find a bug. The only problem i spot is that if you provide no number at all, then this part will cause harm:
(synsAux.size()-1)
It will subtract one from 0u . That will wrap around, because size() returns an unsigned integer type. You will end up with a very big value, somewhere around 2^16 or 2^32. You should change the whole while condition to
while ((index+1) < synsAux.size())
You can try looking for a bug around the call side. Often it happens there is a buffer overflow or heap corruption somewhere before that, and the program crashes at a later point in the program as a result of that.
The argument and parameter stuff in it
Concerning the array and how it's passed, i think you do it alright. Although, you still pass the array by value. Maybe you already know it, but i will repeat it. You really pass a pointer to the first element of this array:
char matrizSinonimos[1024][1024];
A 2d array really is an array of arrays. The first lement of that array is an array, and a pointer to it is a pointer to an array. In that case, it is
char (*)[1024]
Even though in the parameter list you said that you accept an array of arrays, the compiler, as always, adjusts that and make it a pointer to the first element of such an array. So in reality, your function has the prototype, after the adjustments of the argument types by the compiler are done:
void pushSynonyms (string synline, char (*matrizSinonimos)[1024]);
Although often suggested, You cannot pass that array as a char**, because the called function needs the size of the inner dimension, to correctly address sub-dimensions at the right offsets. Working with a char** in the called function, and then writing something like matrizSinonimos[0][1], it will try to interpret the first sizeof(char**) characters of that array as a pointer, and will try to dereference a random memory location, then doing that a second time, if it didn't crash in between. Don't do that. It's also not relevant which size you had written in the outer dimension of that array. It rationalized away. Now, it's not really important to pass the array by reference. But if you want to, you have to change the whole thingn to
void pushSynonyms (string synline, char (&matrizSinonimos)[1024][1024]);
Passing by reference does not pass a pointer to the first element: All sizes of all dimensions are preserved, and the array object itself, rather than a value, is passed.
Arrays are passed as pointers - there's no need to do a pass-by-reference to them. If you declare your function to be:
void pushSynonyms(string synline, char matrizSinonimos[][1024]);
Your changes to the array will persist - arrays are never passed by value.
The exception is probably 0xC00000FD, or a stack overflow!
The problem is that you are creating a 1 MB array on the stack, which probably is too big.
try declaring it as:
void pushSynonyms (const string & synline, char *matrizSinonimos[1024] )
I believe that will do what you want to do. The way you have it, as others have said, creates a 1MB array on the stack. Also, changing synline from string to const string & eliminates pushing a full string copy onto the stack.
Also, I'd use some sort of class to encapsulate matrizSinonimos. Something like:
class ms
{
char m_martix[1024][1024];
public:
pushSynonyms( const string & synline );
}
then you don't have to pass it at all.
I'm at a loss for what's wrong with the code above, but if you can't get the array syntax to work, you can always do this:
void pushSynonyms (string synline, char *matrizSinonimos, int rowsize, int colsize )
{
// the code below is equivalent to
// char c = matrizSinonimos[a][b];
char c = matrizSinonimos( a*rowsize + b );
// you could also Assert( a < rowsize && b < colsize );
}
pushSynonyms( "1 7", matrizSinonimos, 1024, 1024 );
You could also replace rowsize and colsize with a #define SYNONYM_ARRAY_DIMENSION 1024 if it's known at compile time, which will make the multiplication step faster.
(edit 1) I forgot to answer your actual question. Well: after you've corrected the code to pass the array in the correct way (no incorrect indirection anymore), it seems most probable to me that you did not check you inputs correctly. You read from a stream, save it into a vector, but you never checked whether all the numbers you get there are actually in the correct range. (end edit 1)
First:
Using raw arrays may not be what you actually want. There are std::vector, or boost::array. The latter one is compile-time fixed-size array like a raw-array, but provides the C++ collection type-defs and methods, which is practical for generic (read: templatized) code.
And, using those classes there may be less confusion about type-safety, pass by reference, by value, or passing a pointer.
Second:
Arrays are passed as pointers, the pointer itself is passed by value.
Third:
You should allocate such big objects on the heap. The overhead of the heap-allocation is in such a case insignificant, and it will reduce the chance of running out of stack-space.
Fourth:
void someFunction(int array[10][10]);
really is:
(edit 2) Thanks to the comments:
void someFunction(int** array);
void someFunction(int (*array)[10]);
Hopefully I didn't screw up elsewhere....
(end edit 2)
The type-information to be a 10x10 array is lost. To get what you've probably meant, you need to write:
void someFunction(int (&array)[10][10]);
This way the compiler can check that on the caller side the array is actually a 10x10 array. You can then call the function like this:
int main() {
int array[10][10] = { 0 };
someFunction(array);
return 0;
}