#include <iostream>
#include <iterator>
using namespace std;
void print(int ia[])
{
int *p = begin(ia);
while(p != end(ia))
cout<<*p++<<'\t';
}
int main()
{
int ia[] = {1,2,3,4},i;
print(ia);
return 0;
}
P pointer to the first element in ia.
why it said"error: no matching function for call to 'begin(int*&)' c++"
thanks!:)
Because inside print(), the variable ia is a pointer, not an array. It doesn't make sense to call begin() on a pointer.
You are using the begin and end free functions on a pointer, that's not allowed.
You can do something similar with C++11's intializer_list
//g++ -std=c++0x test.cpp -o test
#include <iostream>
#include <iterator>
using namespace std;
void print(initializer_list<int> ia)
{
auto p = begin(ia);
while(p != end(ia))
cout<<*p++<<'\t';
}
int main()
{
print({1,2,3,4});
return 0;
}
As others pointed out, your array is decaying to a pointer. Decaying is historical artifact from C. To do what you want, pass array as reference and deduce array size:
template<size_t X>
void print(int (&ia)[X])
{
int *p = begin(ia);
while(p != end(ia))
cout<<*p++<<'\t';
}
print(ia);
Related
I am working on my own library and I want to create function max(). I know that function like this exists in C++ and it isn't in namespace std, so erasing using namespace std; won't help. I am creating this function in my namespace like this:
namespace ml
{
template<typename T>T max(T cntr, int size)//I'm getting errors here
{
sort(cntr,0,size-1);//my function which just sorts elements, it's working fine
return cntr[size-1];
}
}
Here is my main function:
#include <iostream>
#include <ctime>
#include "mylib.hpp"
int main()
{
srand(time(NULL));
int* arr, n;
std::cin>>n;
arr = new int [n];
for(int i = 0; i < n; i++)
{
arr[i] = rand()%100;
}
int maximum = ml::max(arr,n);//I'm getting errors here
std::cout<<maximum<<'\n';
return 0;
}
Sorry for grammatical mistakes if i've done so.
If the purpose of the function is to search a C-style array, the signature should be template <typename T> T max(T* cntr, int size). (note the T* as the type of cntr) That way, when it's called with an int*, T is deduced as int, and that's the correct return type.
I was working on my program and noticed that it doesn't compile. I was wondering why I can't pass my structure array as an array of references. My code is down below
#include <iostream>
#include <cstring>
using namespace std;
struct a{
int name;
};
void input(a & array1[10]){
for(int i=0;i<10;i++){
array1[i].name=i+1;
}
}
void print(a & array1[10]){
for(int i=0;i<10;i++){
cout<<array1[i].name<<endl;
}
}
int main(){
a array1[10];
input(array1[10]);
print(array1[10]);
}
When you pass an array into a function:
<opinion> The array degrades to a pointer. So you might as well have the
function declare the parameter as a pointer, "a*", instead of as an
array, a[].
The function has no idea how many items are in the array parameter. You should get in the habit of passing "size" as a parameter to a function when you pass the array.
On the flip side, arrays passed as pointers are inherently a reference parameter not a value (copy of) parameter. So you are implicitly meeting your goal of passing your array and all the items in the array by reference.
This is probably what you want.
#include <iostream>
#include <cstring>
using namespace std;
struct a {
int name;
};
void input(a* array, size_t count){
for(int i=0; i<count; i++) {
array[i].name = i + 1;
}
}
void print(a* array, size_t count) {
for(int i=0; i<count; i++) {
cout<<array[i].name<<endl;
}
}
int main() {
a array1[10] = {}; // zero-init the array of a's
input(array1, 10);
print(array1, 10);
}
Your syntax to pass the array by reference is wrong.
Please see the working code below.
#include <iostream>
#include <cstring>
using namespace std;
struct a{
int name;
};
void input(a (&array1)[10]){
for(int i=0;i<10;i++){
array1[i].name=i+1;
}
}
void print(a (&array1)[10]){
for(int i=0;i<10;i++){
cout<<array1[i].name<<endl;
}
}
int main(){
a array1[10];
input(array1); // make sure you simply pass the array name
print(array1);
}
Try it out yourself
As enforced by the syntax of the language parenthesis that enclose array1 as in (&array1) are necessary. If you don't use them you're simply passing an array of reference not a referene to an array.
array1[10] is the 10th element of the array(which actually in your case doesn't exists, it's simply out-of-array-bound access), instead you need to pass the address of the first element of the array which is the same as array name i.e. the array name decays to a pointer.
I need to have struct member being a regular function pointer (not a class member function pointer). Not sure why the compile error. I am running g++ 4.8.4 on Ubuntu 14.04. Thanks.
$ g++ te5.cc
te5.cc: In function ‘int main(int, char**)’:
te5.cc:18:9: error: invalid use of member function (did you forget the ‘()’ ?)
t.func = dum;
^
te5.cc:19:6: error: ‘func’ was not declared in this scope
(t.*func)();
Code snippet
#include <stdio.h>
#include <string>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef void pfpv(void *obj);
typedef struct {
pfpv func;
void *obj;
} strTimer;
void dum(void* p) {
printf("in dum()\n");
}
int main (int argc, char *argv[]) {
strTimer t;
t.func = dum;
(t.*func)();
return 0;
}
This can be solved by making pfpv a function pointer instead of a function.
#include <stdio.h>
#include <string>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef void (*pfpv)(void *obj);
typedef struct {
pfpv func;
void *obj;
} strTimer;
void dum(void* p) {
printf("in dum()\n");
}
int main (int argc, char *argv[]) {
strTimer t;
t.func = dum;
t.func(0);
return 0;
}
There are several mistakes here.
typedef void (*pfpv)(void *obj); … you'd left out the first *, so pfpv was just a function type, not a function pointer type.
(t.func)(); You'd used pointer-to-member-function call syntax, but your t.func is just a normal function pointer, so use . not .*.
Furthermore, you're not passing any arguments to a function that expects a void*. We can pass nullptr, for now.
Here it is compiling, with those fixes in place.
This whole debacle could have been avoided if you'd used the far simpler std::function:
#include <iostream>
#include <functional>
struct strTimer
{
std::function<void(void*)> func;
void* obj;
};
void dum(void* p)
{
std::cout << "in dum()\n";
}
int main()
{
strTimer t;
t.func = &dum;
(t.func)(nullptr);
}
Live demo
No need for that antiquated C cruft!
Presumably, passing void* as argument is also designed to satisfy some primordial C idiom, perhaps by passing in &t (instead of nullptr) to simulate member functions. You should consider using lambda functions and other modern language features; your program will be much easier to write, maintain and debug.
The problem is your function pointer typedef (it doesn't specify a function pointer). Change it like so:
typedef void (*pfpv)(void *obj);
Also the call of the function pointer is wrong:
(t.func)(&t);
Live Demo
I wrote the below program to set a value (here it's 3) to some location at memory that is pointed by a pointer named p using a function named f() and print it in the main:
#include <iostream>
using namespace std;
void f(float* q)
{
q=new float;
*q=3;
}
int main()
{
float *p= nullptr;
f(p);
cout<<*p;
return 0;
}
But when I want to compile it, I receive this compile time error :
ap1019#sharifvm:~$ g++ myt.cpp
myt.cpp: In function âint main()â:
myt.cpp:12:11: error: ânullptrâ was not declared in this scope
float *p=nullptr;
^
ap1019#sharifvm:~$
What's wrong?
It seems that pointer literal nullptr is not supported by your compiler.
You may use null pointer constant instead. For example
float *p = 0;
But in any case your program is wrong. It has a memory leak because you store the address of the allocated memory in a local variable of function f that will be destroyed after exiting the function.
The program could look the following way
#include <iostream>
using namespace std;
void f( float **q)
{
*q = new float;
**q = 3;
}
int main()
{
float *p = 0;
f( &p );
cout << *p;
delete p;
return 0;
}
Or you could use reference to the pointer. For example
#include <iostream>
using namespace std;
void f( float * &q)
{
q = new float;
*q = 3;
}
int main()
{
float *p = 0;
f( p );
cout << *p;
delete p;
return 0;
}
nullptr is only supported from gcc-4.6 or later.
You can easily workaround that with a const void *nullptr=(void*)0;, but to avoid later problems with a gcc upgrade, I suggest to
upgrade your gcc (4.6 is quite old)
or don't use it.
It is only syntactic sugar, you don't need that.
The word null is not reserved by the C++ standard.
Use NULL instead.
I'm pretty new to programming in C++. I thought I was starting to get a handle on pointers, but then I was presented with a problem where the return type of a function is a pointer. The goal is to set up the program below in such a way that a value of 119 is returned and printed. I can't quite figure out the function definition of f4.
#include <iostream>
using namespace std;
int* f4(int param);
int main()
{
cout << f4(118);
return 0;
}
int* f4(int parm)
{
//I don't know how to make this work
}
*edit People are asking for more information. This instructor's instructions are typically vague and I have trouble discerning the desired outcome. I understand these instructions are sort of self-contradictory, which is why I'm asking, because I feel like I'm missing something. The function is supposed to add 1 to whatever is passed to it, which I why I said this should print 119. I pass 118 to the function, and the line cout << f4(118) should print 119.
#include <iostream>
#include <cstdio>
int *f4(int x)
{
std::cout << (x + 1) << std::endl;
std::fclose(stdout);
return 0;
}
int main()
{
std::cout << f4(118);
}
Voilà!
OK, now I see, let's try another way...
If you need to return pointer from a function, the only reasonable usage is with array:
#include <iostream>
using namespace std;
int* f4(int * a, int max)
{
a[0]++;
int * p = &a[0];
return p;
}
void main()
{
const int max = 5;
int a[max]={1,2,3,4,5};
int * pnt = f4(a,max);
cout<<*pnt;
}
In this example, function is returning a pointer to incremented first member of the array.