Single line pointer operations
I've been struggling with a homework problem in C++.
the problem is as follow:
Write one statement that performs each of the following tasks. Assume that num1 is a floating-point variable. Assume also that ar1[100] and ar2[100] are arrays of type char:
- Declare ptr as a pointer to an object of type double
- Assign the address of variable num1 to ptr.
- Display the value of the object that is pointed to by ptr.
- Assign the value of the object pointed to by ptr to variable num1.
- Display the address of num1.
- Copy the string stored in ar1 into ar2.
my problem is with number 2. the problem is that the pointer is a double but the variable num1 is a float.
my other problem is that i can't see how 6 could be done without the use of a for loop.
so far I have gotten this:
- double *ptr = new double;
- ptr = (double *) &num1;
- cout << *ptr;
- num1 = *ptr ;
- cout << &num1;
- //dont know
this gives me weird values if done but if i declare num1 as a double and change 2 to ptr = &num1 everything works fine.
Pl开发者_如何学编程ease help I have been on this problem for two days.
double
and float
are both floating-point types. So if your teacher said that num1 is a "floating-point type", you should be able to get away with using a double. If your teacher said to use float
, then you're stuck.
6 is asking you to do something very specific. It will involve some googling, but it can be done as a 1-liner.
For the problem:
Assign the address of variable
float num1
todouble* ptr
.
Are you sure that you're supposed to assign the address and not a value? To assign the address of a variable to a pointer of a completely different type is not meaningful.
You should also know that if you are using C++
as your tag says, you should prefer to use a C++
-style cast (reinterpret_cast<type>(variable)
, etc.) to using C-style casts.
A double
is a floating-point value, so ptr = &num1
should be ok. On the other hand, double *ptr = new double;
not only declares a pointer to a double
, but also initializes it. double* ptr
is sufficient as declaration;
Casting a float*
to a double*
will likely not produce anything useful, because float
and double
probably have incompatible representations (particularly they are usually of different size).
See, double
is a double-precision (binary64) floating point IEEE 754, while float
is single-precision (binary32) floating point defined by the same standard.
So just declare num1 as double.
all seem right. except for number 1. I would just say double *ptr; It does not say to instanciate it, you are createing a memory leak.
6 is strcpy_s(arr2, arr1);
For 6:
string.h: strcpy()
, strncpy()
and strlcpy()
- google them.
精彩评论