This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
2D arrays with C++
Hi, I'm trying to copy a pointer to a matrix that i'm passing in to a function in C++. here's what my code is trying to express
#include <iostream>
using namespace std;
void func( char** p )
{
char** copy = p;
cout << **copy;
}
int main()
{
char x[5][5];
x[0][0] = 'H';
func( (char**) &x);
return 0;
}
However, this gives me a Seg Fault. Would someone please explain (preferrably in some detail) what underlying mechanism i'm missing out on? (and the fix for it)
Thanks much in advance :)
A pointer to an array of 5 arrays of 5 char (char x[5][5]) has the type "pointer to array of 5 arrays of 5 chars", that is char(*p)[5][5]. The type char** has nothing to do with this.
#include <iostream>
using namespace std;
void func( char (*p)[5][5] )
{
char (*copy)[5][5] = p;
cout << (*copy)[0][0];
}
int main()
{
char x[5][5];
x[0][0] = 'H';
func(&x);
return 0;
}
Of course there are many other ways to pass a 2D array by reference or pointer, as already mentioned in comments. The most in-detail reference is probably StackOverflow's own C++ FAQ, How do I use arrays in C++?
char** is a pointer to a pointer (or an array of pointers). &x is not one of those - it's a pointer to a two-dimensional array of chars, which can be implicitly converted to a pointer to a single char (char *). The compiler probably gave you an error, at which point you put in the cast, but the compiler was trying to tell you something important.
Try this instead of using a char**:
#include <iostream>
using namespace std;
void func( char* &p )
{
char* copy = p;
cout << copy[0];
}
int main()
{
char x[5][5];
x[0][0] = 'H';
func(&x[0]);
return 0;
}
Related
This question already has answers here:
Passing an array as an argument to a function in C
(11 answers)
Closed 7 years ago.
I read here:
C: differences between char pointer and array
that char pointers and char arrays are not the same. Therefore, I would expect these to be overloading functions:
#include <iostream>
using namespace std;
int function1(char* c)
{
cout << "received a pointer" << endl;
return 1;
}
int function1(char c[])
{
cout << "received an array" << endl;
return 1;
}
int main()
{
char a = 'a';
char* pa = &a;
char arr[1] = { 'b' };
function1(arr);
}
Yet upon building I get the error C2084: function 'int function1(char *)' already has a body. Why does the compiler seem to consider a char pointer to be the same as a char array?
Because when you pass an array into a function, it magically becomes a pointer.
Your two functions, then, are the same.
The following are literally* identical:
void foo(int arr[42]);
void foo(int arr[]);
void foo(int* arr);
(* not lexically, of course :P)
This historical C oddity is the major reason lots of people mistakenly think that "arrays are pointers". They're not: this is just a bit of an edge case that causes confusion.
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;
}
This question already has answers here:
How do I use arrays in C++?
(5 answers)
What is array to pointer decay?
(11 answers)
Closed 8 years ago.
As far as I know, in C++ when you pass a non-pointer object to a method, it makes a copy of it to work with in the method. However in my program below, I pass a copy and yet my method actually edits the original character array. Why is this working? :/
#include <iostream>
#include <string>
void Reverse(char s[], int sizeOfArray)
{
for (int i = 0 ; i < sizeOfArray; i++)
{
s[i] = 'f';
}
}
int main()
{
char c[3] = {'g','t','r'};
Reverse(c,3);
for (int t = 0 ; t < 3; t++)
{
std::cout << c[t];
}
return 0;
}
NOTE:
The output is fff
You cannot copy arrays by passing them to functions. The array "decays" into a pointer. Check for yourself by printing the variables' typeid:
#include <iostream>
#include <string>
void Reverse(char s[], int sizeOfArray)
{
std::cout << typeid(s).name() << "\n";
for (int i = 0 ; i < sizeOfArray; i++)
{
s[i] = 'f';
}
}
int main()
{
char c[3] = {'g','t','r'};
std::cout << typeid(c).name() << "\n";
Reverse(c,3);
for (int t = 0 ; t < 3; t++)
{
std::cout << c[t];
}
return 0;
}
Result:
char [3]
char *
Moral of the story:
Use std::vector.
Edit: I should mention that the exact result of the typeid name is implementation-defined. "char [3]" and "char *" is what I get with VC 2013. But the underlying issue is the same on every compiler, of course.
void Reverse(char s[], int sizeOfArray)
Reverse(c,3);
>call by value
>call by reference
here you are doing call by reference operation that means you are passing address of c to int s[]
you are passing a reference of c to reverse function. this is called call by reference not call by value. thats why reverse function overriding your original input
Because char s[] is actually char * pointing to the first element of array.
It means your function Reverse gets the first arg pointer but not copy of array.
If you want to get copy you should use memcpy first and pass new (copy) array to function.
C-array cannot be passed by copy.
It may be passed by reference as void Reverse(char (&a)[3])
or by its decayed pointer as you do void Reverse(char a[], int size)
(which is the same as void Reverse(char* a, int size)).
You may use std::array (C++11) to have a more intuitive behaviour.
if you declare an array then the variable holds the base address of that array, so here char c[3] means c holds the base address of the array c[3].
so, when you are passing Reverse(c,3); actually you are passing the base address.
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
void f(char **x)
{
(*x)++;
**x = 'a';
}
int main()
{
char str[]="hello";
f(&str);
cout << str << endl;
return 0;
}
Please tell me why this program is giving compilation Error.I am using the g++ compiler
Error :temp1.cpp:16:8: error: cannot convert ‘char (*)[6]’ to ‘char**’ for
argument ‘1’ to ‘void f(char**)’
Arrays can be implicitly converted to pointers, but that doesn't mean that the implicit "pointer equivalent" already exists.
You are hoping that f(&str); will implicitly create both a pointer to str and a pointer to that pointer.
This small (working) change illustrates this point:
int main()
{
char str[]="hello";
char *pstr = str; // Now the pointer extists...
f(&pstr); // ...and can have an address
cout << str << endl;
return 0;
}
You are passing pointer of constant char to the function but in function you are taking it as pointer of pointers. That is the problem. I commented out below where the problem lies.
[Off topic but N. B. : Arrays and pointers are different concept.]
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
void f(char **x) //**x is pointer of pointer
{
(*x)++;
**x = 'a';
}
int main()
{
char str[]="hello";
f(&str); //You are passing pointer of constant char.
cout << str << endl;
return 0;
}
You're going to run into a serious problem with your function f since &str and &str[0] both evaluate to the same value ... as other posters have pointed out, these operations point to different types, but the actual pointer r-value will be the same. Thus in f when you attempt to double-dereference the char** pointer x, you're going to get a segfault even if you attempted something like a cast to massage the type differences and allow compilation to happen with errors. This is because you are never getting a pointer-to-pointer ... the fact that &str and &str[0] evaluate to the same pointer value means that a double-dereference acually attempts to use the char value in str[0] as a pointer value, which won't work.
Your problem is that you're treating arrays as pointers, when they're not. Arrays decay into pointers, and in this case, it doesn't. What you're passing in is a char (*)[6] when it expects a char **. Those are obviously not the same.
Change your parameter to char (*x)[6] (or use a template with a size parameter):
template <std::size_t N>
void f(char (*x)[N])
Once inside, you try to increment what x is pointing to. You can't increment an array, so use an actual pointer instead:
char *p = *x;
p++;
*p = 'a';
All put together, (sample)
template <std::size_t N>
void f(char(*x)[N])
{
if (N < 2) //so we don't run out of bounds
return;
char *p = *x;
p++;
*p = 'a';
}
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;
}