0

Bug help

My teacher gave me a task: On a sidewalk there a n people. Some of them are walking right, someone are walking left. Those who go left are no 2,those who go right are number 1. When there are 1 and 2 one to other they are swapping. How many teleportations will be made while there are 1 and 2 one to other? My code: #include <bits/stdc++.h> using namespace std; bool teleportirana(int arr[]) { bool isit = false; for(int i=0; i<sizeof(arr)-1; i++) { if(arr[i] == 1 && arr[i+1] == 2) { isit = true; break; } } return isit; } int main() { int n; cin>>n; int arr[n]; for(int i=0; i<n; i++) { int a; cin>>a; arr[i] = a; } int count = 0; while(teleportirana(arr)) { for(int i=0; i<n-1; i++) { if(arr[i] == 1 && arr[i+1] == 2) { arr[i] = 2; arr[i+1] = 1; count++; } } } cout<<count; return 0; }

8th Mar 2021, 4:19 PM
CodeFu
CodeFu - avatar
5 Respuestas
+ 7
CodeFu , showing your code in the post area should only be done with very few lines of code. in your case it would be better to place the code in playground and link it here. it is easier for people that will help you, if they don't need to do copy and paste for running your code. thanks!
8th Mar 2021, 4:37 PM
Lothar
Lothar - avatar
0
When you pass an array into a function, it decays to a pointer. Therefore, using sizeof() on the pointer will always return the size of the pointer, i.e. 8 byte on typical 64-bit systems, and not the size of the original array. For C-style arrays, it is common to add another parameter to the function that denotes the actual size of the array. However, you could avoid this problem altogether by using std::vector as a container instead. This is what a fixed version could look like: https://code.sololearn.com/cIXq1ZB26J9E/?ref=app Alternative solution that does not need an array: https://code.sololearn.com/cKuRXdK4RQiK/?ref=app Note VLA's like "arr[ n ]" are not standard C++ and only extensions to specific compilers like GCC, which is why I replaced it by a dynamically allocated array in the fixed version. This could also be solved by simply using std::vector.
8th Mar 2021, 5:13 PM
Shadow
Shadow - avatar
0
Lothar Thanks for the suggestion.
8th Mar 2021, 8:50 PM
CodeFu
CodeFu - avatar
0
Shadow What is size_t? Sorry I am a student and we do not learn things like that😢
8th Mar 2021, 9:04 PM
CodeFu
CodeFu - avatar
0
Just an unsigned integral type used to represent sizes, it's quite common in the standard library. It depends on your system, but you can probably think of it as an alias for the unsigned long long int type. https://en.cppreference.com/w/cpp/types/size_t
8th Mar 2021, 9:15 PM
Shadow
Shadow - avatar