#include <iostream>
#include <string.h>
using namespace std;
class A
{
private:
int a;
int b;
public:
A():a(10),b(20){};
A(int ad,int bd):a(ad),b(bd){};
void printvalues()
{
cout<<a << " " <<b<<endl;
}
};
int main()
{
A a(5,12);
memset(&a,sizeof(A),0);
a.printvalues();
return 0;
}
memsetting the object to 0, do not seem to have any effect on the object. Can anyone help me understand this behavior.
output:
5 12
You have the arguments to memset the wrong way round. It's memset(addr, value, number).
Note: In C++, memset is usually avoided.
You got the memset wrong:
void * memset ( void * ptr, int value, size_t num );
it should be:
memset(&a,0,sizeof(A));
In your example, you're setting 0 bytes of a to sizeof(A), so, obviously, no change.
The correct syntax of memset is memset(&a,0,sizeof(A)) because the first parameter is the array or the variable, the second is the value and the third parameter is the number of bytes.
For more details about memset visit http://www.cplusplus.com/reference/clibrary/cstring/memset/.
You have misplaced the arguments to memset. At first I thought this is stunning!
Write this:memset(&a,0,sizeof(A));
And all will be as expected.
Related
I know there are other ways of implementing this or using containers. This is just to satisfy my curiosity. Suppose I have the following code:
void byref(int (&a)[5]);
int main()
{
int a[5];
byref(a);
}
An advantage of passing a C-style array by reference is that sizeof will work on it, as will std::end. But now it is only possible to pass an array of exactly this size.
Is it possible to pass a subset of a larger array to this function by reference? For example, I'd like to do:
int main()
{
int a[10];
byref(a + 1);
}
Is there any way to make this work?
I got it to build and run, giving expected values in VS2015, but of course the code looks very dodgy:
byref(reinterpret_cast<int(&)[5]>(*(a + 1)));
I have only an idea of wrapping the bad looking cast into a function:
#include <iostream>
#include <cassert>
void byref(int (&a)[5])
{
std::cout << "Hello!" << std::endl;
}
template <size_t M, class T, size_t N>
T (&subarray(T (&a)[N], size_t start))[M]
{
assert(start < N && start + M <= N);
return reinterpret_cast<T(&)[M]>(a[start]);
}
int main()
{
int a[5], b[8];
byref(a);
byref(subarray<5>(subarray<6>(b, 0), 1));
}
With this prototype, I fail to see another way to proceed than casting.
Typically, I see this one too: byref((int(&)[5])*(b + 5));, but of course it's the same and less safe than yours.
So, I don't see any clear and pretty way to do it (except for a macro maybe). I will upvote your question however, in order to see if you are missing something here!
What should be the proper way of doing this? Here's an example code of what I tried.
main
const int SIZE = 10;
char a[10][SIZE]; //assume this array already hold some character strings
fnc(a[2][SIZE]);
function
void fnc(char a[SIZE]){
cout << a;
}
I feel that I might be close, but I couldn't get it to work. Any help would be appreciated!
the function call in main should not be:
fnc(char a[2][SIZE]);
i am guessing you want to print the string at a[2]. Hence your function call should be:
fnc(a[2]);
Ok you want to pass an element from 2d char array to a function. So just pass two arguments to your function which indicate the position of your element.void fnc(int p1,int p2)
Your whole code will look like this.
const int SIZE = 10;
char a[10][SIZE];
fnc(2,0);
function
void fnc(int p1,int p2){
cout << a[p1][p2];
}
Hope this helps
You can pass 2D array like this:-
char array[10][10];
void passToFunc(int a[][10])
{
// ...
}
passToFunc(array);
Sorry for mis-interpretation:-
You can do it by :-
void passElement( char x )
{
//do something with x.
}
passElement( arr[1][1] ); //assume you want to pass 2nd element of 2nd 1-dimensional array.
Hope that helps :)
Your application never initializes the strings so there may be garbage being printed out. Here is an example that I did that works for me. Its a C++ app written using visual studio 2013.
Note that I initialized the strings to only 9 places in a 10 place array.
That is to account for the null terminator required for each string.
I hope this helps.
// TestApp.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string.h>
#include <iostream>
#include <windows.h>
using namespace std;
const int xSIZE = 10;
void fnc(char*);
int _tmain(int argc, _TCHAR* argv[])
{
char a[10][xSIZE];
strcpy(a[1], "012345678");
strcpy(a[2], "abcdefghi");
fnc(a[2]);
return 0;
}
void fnc(char a[])
{
cout << a<<endl;
}
#include <iostream>
#include <conio>
#include <math>
using namespace std;
void main()
{
double b[1000], mxrs[1000],mnrs[1000], ls[1000]; int t, i;
clrscr();
cin>>t;
for(i=0;i<t;i++)
cin>>b[i]>>ls[i];
for(i=0;i<t;i++)
{
mxrs[i]=sqrt(ls*ls+b*b);
mnrs[i]=sqrt(ls*ls-b*b); cout<<mnrs[i]<<' '<<mxrs[i]<<'\n';
}
getch();
}
I get 4 errors in this code...
main.cpp|16|Error E2087 : Illegal use of pointer in function main()|
main.cpp|16|Error E2087 : Illegal use of pointer in function main()|
main.cpp|17|Error E2087 : Illegal use of pointer in function main()|
main.cpp|17|Error E2087 : Illegal use of pointer in function main()|
||=== Build finished: 4 errors, 0 warnings ===|
Please help me in correcting the errors, it would be helpful even if you told me only reason of errors. Thanks in advance!
When you write double b[1000], you can access the array elements either by writing b[n] or *(b + n), taking care to keep n within the bounds of the array.
So *b and b[0] are equivalent. In other words, b is a pointer to the zeroth element of the array. Writing b * b is an attempt to multiply two pointers and that makes no sense. This is what the compiler is telling you.
To multiply elements of the array, use b[n] * b[m] or *(b + n) * *(b + m).
(And fix the return type of main: it should be int.)
ls,bs refers to the base address of the array. so they are addresses not values. I think this is what you intend to do.
#include <iostream>
#include <conio>
#include <math>
using namespace std;
void main()
{
double b[1000], mxrs[1000],mnrs[1000], ls[1000]; int t, i;
clrscr();
cin>>t;
for(i=0;i<t;i++)
cin>>b[i]>>ls[i];
for(i=0;i<t;i++)
{
mxrs[i]=sqrt(ls[i]*ls[i]+b[i]*b[i]);
mnrs[i]=sqrt(ls[i]*ls[i]-b[i]*b[i]); cout<<mnrs[i]<<' '<<mxrs[i]<<'\n';
}
getch();
}
let's take an simple example to understand the concept:
int a[5]={1,2,3,4,5};
cout<<*a; //prints the value at base address which is 1 as a refers to a[0]
cout<<a[0]; //prints 1
cout<<*(a+1); //prints 2 ... as a+1 refers to the address next to its base which is a[1] and which is 2
cout<<a[1];//prints 2
You put #include <math>, it should have been #include <math.h>. Same thing for <iostream> and <conio>. You forgot .h on all of them.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sizeof an array in the C programming language?
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
string a[] = {"some", "text"};
void test(string a[])
{
int size_of_a = sizeof(a) /sizeof(a[0]);
cout << size_of_a;
}
int _tmain(int argc, _TCHAR* argv[])
{
test(a); //gives 0
int size_of_a = sizeof(a) /sizeof(a[0]);
cout << size_of_a; //gives 2
return 0;
}
as u can see in the comment test(a) gives 0 instead of 2 as i would expect. Could someone explain why and how could i correct it? thanks
When you pass an array to a function, it decays to a pointer to the first element of the array and so within your test(string a[]) function
sizeof(a);
actually returns the size of a pointer and not the size of your array.
To prevent array decaing to pointer, you can pass reference to array to the function. But it causes types of array of function formal argument and actual argument must coincide (including their sizes). So you need to use template to make your function work with an array of any size:
template <int N>
void foo(const string (&a)[N])
{
int size_of_a = sizeof(a) /sizeof(a[0]);
cout << size_of_a;
}
In C/C++, how do I determine the size of the member variable to a structure without needing to define a dummy variable of that structure type? Here's an example of how to do it wrong, but shows the intent:
typedef struct myStruct {
int x[10];
int y;
} myStruct_t;
const size_t sizeof_MyStruct_x = sizeof(myStruct_t.x); // error
For reference, this should be how to find the size of 'x' if you first define a dummy variable:
myStruct_t dummyStructVar;
const size_t sizeof_MyStruct_x = sizeof(dummyStructVar.x);
However, I'm hoping to avoid having to create a dummy variable just to get the size of 'x'. I think there's a clever way to recast 0 as a myStruct_t to help find the size of member variable 'x', but it's been long enough that I've forgotten the details, and can't seem to get a good Google search on this. Do you know?
Thanks!
In C++ (which is what the tags say), your "dummy variable" code can be replaced with:
sizeof myStruct_t().x;
No myStruct_t object will be created: the compiler only works out the static type of sizeof's operand, it doesn't execute the expression.
This works in C, and in C++ is better because it also works for classes without an accessible no-args constructor:
sizeof ((myStruct_t *)0)->x
I'm using following macro:
#include <iostream>
#define DIM_FIELD(struct_type, field) (sizeof( ((struct_type*)0)->field ))
int main()
{
struct ABC
{
int a;
char b;
double c;
};
std::cout << "ABC::a=" << DIM_FIELD(ABC, a)
<< " ABC::c=" << DIM_FIELD(ABC, c) << std::endl;
return 0;
}
Trick is treating 0 as pointer to your struct. This is resolved at compile time so it safe.
You can easily do
sizeof(myStruct().x)
As sizeof parameter is never executed, you'll not really create that object.
Any of these should work:
sizeof(myStruct_t().x;);
or
myStruct_t *tempPtr = NULL;
sizeof(tempPtr->x)
or
sizeof(((myStruct_t *)NULL)->x);
Because sizeof is evaluated at compile-time, not run-time, you won't have a problem dereferencing a NULL pointer.
In C++11, this can be done with sizeof(myStruct_t::x). C++11 also adds std::declval, which can be used for this (among other things):
#include <utility>
typedef struct myStruct {
int x[10];
int y;
} myStruct_t;
const std::size_t sizeof_MyStruct_x_normal = sizeof(myStruct_t::x);
const std::size_t sizeof_MyStruct_x_declval = sizeof(std::declval<myStruct_t>().x);
From my utility macros header:
#define FIELD_SIZE(type, field) (sizeof(((type *)0)->field))
invoked like so:
FIELD_SIZE(myStruct_t, x);