How to input a 2-D array by using functions in c++ | SoloLearn: Learn to code for FREE!

+2

How to input a 2-D array by using functions in c++

How to use functions for taking input from user and a function to display the 2-D array entered by the user in c++ ? My code is below 👇but it's not working.. https://code.sololearn.com/ceuZaoiSBqZt/?ref=app

6/1/2020 7:17:23 PM

Aayushi Mittal

30 Answers

New Answer

+2

A similar question came up a while back. As has already been mentioned vectors are sometimes a viable alternative to arrays in C++. That's why I wrote two solutions. One uses an array and the other uses the vector class. Dynamic array demo in C++ https://code.sololearn.com/cShrgY112B16/#cpp 2D Vector demo in C++ https://code.sololearn.com/cNMf27IpHsnt/#cpp Both are heavily commented and while they use randomly generated integers for the data the fill function is easy to modify to accept user input. That's the beauty of modular programming.

+6

Bobby Fischer I am not much experienced in embedded systems either. I too think differences are negligible. Speed is not an issue. I think it's more of a memory thing and runtime cost of using vectors(more internal bookkeeping) along with inherent complexities of C++.You need to consider other factors like maintainability of code (Templates are not everyones cup of tea and STL is templates). Also using raw arrays will almost alway produce smaller binary than when using vector (due to dependency on other STL components and headers) this might be a deciding factor in embedded systems or systems with limited memory say in 1GB space the OS/firmware and other programs has to run. Exception handling appears really good at the top but is one thing that really has huge runtime overhead (there is just too much of internal bookkeeping) besides that most people can't really differentiate between an exception and an error and blindly use exception handling everywhere. At the all I can say is search the net for more information. If you want to discuss these types of things you should probably create a separate thread in your feedpost (not in main q/a thread). Thanks.

+5

int arr[rows][cols]; This is illegal C++. They are supported in C++ by using compiler extensions. They are called VLA (variable length arrays) and are C99 feature. Mustafa K. There is a problem. The pointer you are talking about is a part of an array, which will be destroyed once the function returns. Any local pointer returned from a function is garbage and pointing to garbage for all practical purposes. Using them is a disaster waiting to happen.

+5

Bobby Fischer int [row][col] is illegal in C++ because both row and col are not compile time constant and C++ standard mandates that. The memory for VLA are allocated on function stack. They also have limitation that they cannot be initialized at the time of declaration. Their scope is like any other normal variable. To be frank they appears to be quite useful to me but C++ committee has other thoughts i guess. It was added in C99 originally. Since they are non-standard, one should use them at their own risk. You are basically writing non-portable code if you are using them.

+5

Bobby Fischer 1. When working with embedded systems. 2. At system and Kernel level programming. 3. Systems with limited memory. 4. Bug fix, maintainence or providing backward compatibility with C or cross platform development or systems where STL is not available or if available but suffers from performance issues due to poor or buggy implementation. 5. When for whatever reasons some developers decided not to use STL at all :) Each system is different. Each application is different. You should evaluate and choose the best tools(data structures, algorithms, container classes etc.). If something is available which works quite well for most cases still doesn't mean it is a best fit for your case automatically.

+5

Bobby Fischer So what do you think C++ is not used in some low level codes or embedded systems? There are all sorts of systems and various C++ compilers. Automatic dynamic memory definitely needs more bookkeeping than manually(new/malloc/calloc etc..) managed dynamic memory. When you are woring with systems which have fixed memory space available for user programs then it is all together a different type of challenge. Besides that i have mentioned you(generic) need to evaluate your(generic) case before deciding what to use.

+4

Will work with new but you will have to return a pointer to pointer as you cannot assume the memory allocated is contiguous in case of 2D array You can simulate 2D array using a pointer to a pointer. int** myarray(int r, int c) { int **arr = new int*[r]; for(int i=0; i < r; ++i) { arr] = new int[c]; } return arr; } int **arr = myarray(3, 4);

+2

Mohamed ELomari in the example I gave I advised him to return the pointer that points to the first element which is, arr or which also is same thing with arr[0][0], this way since he already knows rows, cols and the address of the first element, he can iterate thru array using this pointer. I don't see any problem here?

+2

~ swim ~ why is int[row][col] illegal? Aayushi Mittal ever heard about vectors? using vectors, you don’t have to deal with all the array pointers crap.

+2

~ swim ~ I deleted my comment that you replied to because I though it wouldn't work too...but had a go and it did. work...now I understand why.

+2

~ swim ~ Actually I’ve only just read the guy’s code. Agree with you about that, wouldn’t be the case if row/col were declared as global const.

+2

Bobby Fischer Yeah then it would be a normal 2D array.

+2

Martin Taylor you mentioned that vectors are “sometimes” a viable alternative to arrays in C++. when exactly do you prefer arrays over vectors?

+2

~ swim ~ notice that the post I was referring to mentioned C++, not some low level embedded system that runs C. also if memory is an issue, isn’t it even better to use a dynamic array?

+2

~ swim ~ I did some research before posting my questions. People said the same thing, but nobody mentioned about the numerical differences between these two. Anyway, thank you for your answers.

+2

Bobby Fischer Vectors are sequence containers representing arrays that can change in size. If I know that a fixed size array can be used then I use a fixed size array.

+2

Bobby Fischer You asked "In what kind of systems/compilers, and shouldn’t today’s processor be so tight on memory management?" Not every embedded system uses a Raspberry Pi or Android device as it's controller. Devices such as toasters, microwaves, washing machines, fuel injection systems, air bag systems etc. use microcontrollers with only a few kilobytes of program store and as little as 256 bytes of RAM. It gets rather important to use efficient code on such systems. The Atmel ATmega328p commonly found in Arduinos is a typical example of a microcontroller. It has 32Kbytes of Flash (code space) and 2Kbytes of SRAM. It doesn't use some obscure C++ compiler either. It uses the avr-gcc compiler. That's the gnu compiler gcc/g++ targeted to produce avr code. Yes, that's the same compiler used on Linux, MinGW, Cygwin etc. The opposite is also true. If you write inefficient code, or use wasteful data structures, it is not often obvious in small pieces of example code. However, when used on larger data sets the performance hit becomes noticeable.

+1

Instead of this, return arr[rows][cols]; Change the return type of function from int to int* then, return arr; // which is equal to &arr[0][0] int* p = input(rows, cols); Since you already know rows, cols and pointer to the first element, you can iterate thru array like this, for (int i=0; i<rows; i++) for (int j=0; j<cols; j++) cout<< *p; // prints the element pointed by p p++; // p now points to the next element

+1

@Mustafa K., a local array cannot be directly returned from a C/C++ function as it may not exist in memory after function call is over, in simple words functions can’t return arrays in C/C++.

+1

rodwynnejones Illegal in C++ but compilers may support them through compiler extension.