2D array pass in a function without Define (M x N) globally - c++

How I will pass a 2D array in a function. I take input from keyboard but when I pass it into function it doesn't work.
for example
#include<bits/stdc++.h>
using namespace std;
void printGrid(int M, int N, int arr[][N])
{
for(int i=0; i<M; i++)
{
for(int j=0; j<N; j++)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
}
int main()
{
int M,N;
scanf("%d %d",&M,&N);
int arr[M][N];
printGrid(M,N,arr);
return 0;
}
This solution doesn't work. It says N was undeclared on this scope.
Is there any way to work with 2D array in Function ?

You are compiling your code the wrong way. int arr[][N] is a variable-length array (VLA). This is a feature that was introduced in the C language in the year 1999. If you use a compiler which is older than that, or if you use a C++ compiler, you will get the error described.
Make sure to compile your code with a standard-compliant C compiler! You need to use a compiler which supports the C99 standard or later. For example you could use the GCC compiler version 5.x. Or if you use an older version of that compiler, set the compiler option gcc -std=c99.

Why don't you try something like this:
#include <iostream>
#include <vector>
using namespace std;
void print(const vector<vector<int>>& arr) {
for(auto& subArr : arr) {
for(auto& element : subArr) {
cout << element << ' ';
}
cout << '\n';
}
}
int main() {
int M,N;
cin >> M >> N;
vector<vector<int>> arr(M, vector<int>(N));
print(arr);
}
This piece of code doesn't do much - it just initializes the 2D array to zeroes and prints it - but that's not the point. It shows some techniques that you should use if you're coding using modern C++. Besides it solves your problem of printing a 2D array in this case implemented as a vector of vectors.
I would recommend reading about std::vector: cppreference.com - std::vector

Solution of my Problem...
Thanks for you guys response..
#include<stdio.h>
#define MAX 500
int arr[MAX][MAX];
void printGrid(int M, int N)
{
for(int i=0; i<M; i++)
{
for(int j=0; j<N; j++)
{
printf("%d ",arr[i][j]);
}
printf("\n");
}
}
int main()
{
int M,N;
scanf("%d %d",&M,&N);
printGrid(M,N);
return 0;
}
this code work the limitation you give for the array

Related

Segmentation fault(code dumped) in c++ after several try I cann't get the solution

#include <iostream>
using namespace std;
int main() {
int T,D;
long long int N;
long long int a[N];
long long int b[D];
cin>>T;
for(int i=0;i<T;i++)
{
cin>>N>>D;
for(int i=0;i<N;i++)
{
cin>>a[i];
}
for(int i=0;i<D;i++)
{
b[i]=a[i];
}
for(int i=0;i<(N-D);i++)
{
a[i]=a[i+D];
}
for(int i=0;i<D;i++)
{
a[i+N]=b[i];
}
for(int i=0;i<N;i++)
{
cout<<a[i];
}
cout <<endl;
}
return 0;
}
Why is this coding having segmentation fault? I have seen many solution but cann't get it right.On visual studio or any other application it is not working but on gfg it is working. Please help me solve this problem
There are several things that are wrong.
C-style arrays must be set at compile time. So if you want to use int a[N], N must to known at compile time. If you want a flexible array, one C++ way is to use std::vector.
Then the array a goes from 0 to N-1. So going a[N] is going too far. So a[i+N] is way out if bounds and will be segfault.
you declare array a with N element, but use index out of the array range.
long long int a[N]; // declare here, maximum element is N
for(int i=0;i<D;i++)
{
a[i+N]=b[i]; // use index out of array a
}

Unexpected value while placeing integers into an array

I am trying to fill an array with different integers, but it doesn't work as expected.
#include <iostream>
using namespace std;
int main(){
int i=0;
int num;
int MyArray[]={};
while (true) {
cout<<"sayi giriniz"<<endl;
cin>>num;
MyArray[i]=num;
i++;
for (int j=0; j<i; j++) {
cout<<MyArray[j]<<endl;
}
}
return 0;
}
https://imgur.com/a/tANGpSY
When I enter the 3rd value it gives an unexpected result.
int MyArray[]={};
Now, MyArray has a size of 0, so any indexes that you tried to access MyArray will cause undefined behavior.
If you want to make an array that is dynamically in size, use std::vector in the <vector> header.
Change
int MyArray[]={};
to
std::vector<int> MyArray;
This:
MyArray[i]=num;
i++;
To this:
MyArray.push_back(num); // you don't even need i
This
for (int j=0; j<i; j++) {
cout<<MyArray[j]<<endl;
}
To this:
for(const auto &i : MyArray) // range based for loop, recommend
{
std::cout << i << '\n';
}
Also, using namespace std; is bad, so don't use it.
If you want to take input and are unsure about the number of elements, you should use a vector. The array which you have made is of 0 size. It will surely give you an error.

C++ Passing Dynamic Array Determined by Parameter

This function has been asked a few times on here but I am interested in a particular case. Is it possible to have the size of the array passed defined by an additional argument?
As an example, let's say I want a function to print a 2D array. However, I the array may not have the same dimensions every time. It would be ideal if I could have additional arguments define the size of that array. I am aware that I could easily switch out the n for a number here as needed but if I have more complex functions with separate header files it seems silly to go and edit the header files every time a different size array comes along. The following results in error: use of parameter 'n' outside function body... which I understand but would like to find some workaround. I also tried with g++ -std=c++11 but still the same error.
#include <iostream>
using namespace std;
void printArray(int n, int A[][n], int m) {
for(int i=0; i < m; i++){
for(int j=0; j<n; j++) {
cout << A[i][j] << " ";
}
cout << endl;
}
}
int main() {
int A[][3] = {
{1,2,3},
{4,5,6},
{7,8,9},
{10,11,12}
};
printArray(3, A, 4);
return 0;
}
Supposedly, this can be done with C99 and also mentioned in this question but I cannot figure out how with C++.
This works:
template<size_t N, size_t M>
void printArray( int(&arr)[M][N] ) {
for(int i=0; i < M; i++){
for(int j=0; j < N; j++) {
std::cout << A[i][j] << " ";
}
std::cout << std::endl;
}
}
if you are willing to put the code in a header file. As a bonus, it deduces N and M for you.

error in function to remove data of array which same in c++

I make function to remove data of array which same in c++, so as make the process like this:
input:4
input:
25.50
64.25
64.25
25.50
output:
5.50
64.25
but the function error like this image
here the code
#include <iostream>
using namespace std;
void removeSame(double a[int x]){
int index[x];
for(int z=0; z<x; z++){
jum[z]=0;
for(int c=0; c<x; c++){
if(a[c]==a[z]){
index[z]=c;
}
}
}
for(int z=0; z<x; z++){
if(z==index[z]){
cout<<a[z]<<endl;
}
}
}
int main(){
int n,x;
cin>>n;
double a[n];
for(x=0; x<n; x++){
cin>>a[x];
}
removeSame(a[x]);
return 0;
}
then when I change the code like this, an error occurs again
void removeSame(double a[], int x){
...
}
the error like this:
cannot convert 'double' to 'double*' for argument '1' to 'void hapusygsama(double*, int)'
please help me
UPDATE. thx for you all who are reply my thread
#include <iostream>
using namespace std;
void hapusygsama(double a[], int len){
int index[len];
for(int z=0; z<len; z++){
for(int c=0; c<len; c++){
if(a[c]==a[z]){
index[z]=c;
}
}
}
cout<<endl;
for(int z=0; z<len; z++){
if(z==index[z]){
cout<<a[z]<<endl;;
}
}
}
int main(){
int n,x;
cin>>n;
double a[n];
for(x=0; x<n; x++){
cin>>a[x];
}
hapusygsama(a, n);
return 0;
}
Your code is illegal C++. C++ does not currently support run-time arrays. All array dimensions must include constant bounds. In addition, C++ does not permit any kind of declaring size in parameter like double a[int x]. You must pass the size as a separate parameter.
A much elegant way to achive the wished behaivour would be to use std::unique and std::resize
The code would be:
int main() {
std::vector<float> myvector;
int n;
cin >> n;
float b;
for (int i=0; i<n; i++){
cin >> b;
myvector.push_back(b);
}
std::sort(myvector.begin(), myvector.end());
myvector.resize(std::distance(myvector.begin(),std::unique (myvector.begin(), myvector.end())));
return 0;
}
Also in your question you have as input flaoting point numbers, while for the code you use int, I think you should change that too.
You don't pass the parameters correctly to the function :
#include <iostream>
using namespace std;
void removeSame(double a[], int x){
// ^^^
int index[x];
for(int z=0; z<x; z++){
jum[z]=0;
for(int c=0; c<x; c++){
if(a[c]==a[z]){
index[z]=c;
}
}
}
for(int z=0; z<x; z++){
if(z==index[z]){
cout<<a[z]<<endl;
}
}
}
int main(){
int n,x;
cin>>n;
double a[n];
// ^^^^ ERROR : not permitted, n is not a constant
// it would not compile.
for(x=0; x<n; x++){
cin>>a[x];
}
removeSame(a, x);
// ^^^
return 0;
}
You want to receive an array in removeSame to remove values who are the same. In you code, you try to pass a double value only.
As I said, it would compile because n is not a constant when you declare a in the main function.
EDIT : It seems it is an extension in gcc who permits this kind of syntax. But I suggest to use something more common...
You should do :
int main() {
int n, x;
cin >> n;
double* a = new double[n];
...
delete[] a;
return 0;
}
In that case, the prototype of removeSame should be :
void removeSame(double* a, int x);
And last thing, you should verify the values entered by the user, one of the most important rule in development is : Never trust the users input !

implementation counting sort

here is code for counting sorting
#include <iostream>
using namespace std;
int main(){
int a[]={2,3,1,2,3};
int n=sizeof(int)/sizeof(int);
int max=a[0];
for (int i=1;i<n;i++) {
if (a[i]>max) {
max=a[i];
}
}
int *output=new int[n];
for (int i=0;i<n;i++) {
output[i]=0;
}
int *temp=new int[max+1];
for (int i=0;i<max+1;i++) {
temp[i]=0;
}
for (int i=0;i<n;i++){
temp[a[i]]=temp[a[i]]+1;
}
for (int i=1;i<max+1;i++) {
temp[i]=temp[i]+temp[i-1];
}
for (int i=n-1;i>=0;i--) {
output[temp[a[i]]-1]=a[i];
temp[a[i]]=temp[a[i]]-1;
}
for (int i=0;i<n;i++) {
cout<<output[i]<<" ";
}
return 0;
}
but output is just 2,only one number. what is wrong i can't understand please guys help me
int n=sizeof(int)/sizeof(int);
is wrong. That just assigns 1 to n.
You mean
int n=sizeof(a)/sizeof(int);
I've not looked beyond this. No doubt there are more problems, but this is the most significant.
This is the kind of thing you can work out very easily with a debugger.
Look at this expression:
int n=sizeof(int)/sizeof(int);
What do you think the value of n is after this? (1)
Is that the appropriate value? (no, the value should be 5)
Does that explain the output you are seeing? (yes, that explains why only one number is shown)
My advice would be that if you're going to do this in C++, you actually try to use what's available in C++ to do it. I'd look up std::max_element to find the largest element in the input, and use an std::vector instead of messing with dynamic allocation directly.
When you want the number of elements in an array in C++, you might consider a function template something like this:
template <class T, size_t N>
size_t num_elements(T const (&x)[N]) {
return N;
}
Instead of dumping everything into main, I'd also write the counting sort as a separate function (or, better, a function template, but I'll leave that alone for now).
// warning: Untested code:
void counting_sort(int *input, size_t num_elements) {
size_t max = *std::max_element(input, input+num_elements);
// allocate space for the counts.
// automatically initializes contents to 0
std::vector<size_t> counts(max+1);
// do the counting sort itself.
for (int i=0; i<num_elements; i++)
++counts[input[i]];
// write out the result.
for (int i=0; i<counts.size(); i++)
// also consider `std::fill_n` here.
for (int j=0; j<counts[i]; j++)
std::cout << i << "\t";
}
int main() {
int a[]={2,3,1,2,3};
counting_sort(a, num_elements(a));
return 0;
}