Skip to content

Instantly share code, notes, and snippets.

@MatrixManAtYrService
Last active February 2, 2020 16:50
Show Gist options
  • Save MatrixManAtYrService/3568891a61ed1146bb9847d5f3ebc865 to your computer and use it in GitHub Desktop.
Save MatrixManAtYrService/3568891a61ed1146bb9847d5f3ebc865 to your computer and use it in GitHub Desktop.
If you try to compile it, your compiler should show you where the problem is.
❯ g++ main.cpp
main.cpp: In function ‘void somefunction(const int*, int)’:
main.cpp:13:20: error: expected primary-expression before ‘]’ token
13 | somefunction(b[], c - 1);
#include <stdio.h>
void somefunction(const int[], int);
int main() {
int a[] = { 1, 3, 4, 5, 7, 9, 11 };
somefunction(a, 5);
return 0;
}
void somefunction(const int b[], int c) {
if (c > 0) {
somefunction(b, c - 1); // <- the problem was here, you tried to pass 'b[]'
// you only need to indicate b as an array in the function signaure
// you can reference it by name, without the [] in the body of the function
printf("%d ", b[c]);
}
}
❯ g++ main.cpp
❯ ./a.out
3 4 5 7 9
#include <stdio.h>
void somefunction(const int[], int);
int main() {
int a[] = { 1, 3, 4, 5, 7, 9, 11 };
somefunction(a, 6);
return 0;
}
void somefunction(const int b[], int c) {
if (c >= 0) { // <--arrays index 0 means the first element, so c == 0 is a valid case
somefunction(b, c - 1);
printf("%d ", b[c]);
}
}
Please ensure that your code is formatted correctly before posting. If you're not sure what that means, try formatting it with a pretty printer, like https://codebeautify.org/cpp-formatter-beautifier
Also, please be specific about why you think your code should work one way, and also about what it actually does. I don't know whether you were posting because you were getting a compile error, or if you were posting because of the (c <= 0) problem.
I think your question was answered in the comments, but if you still want answers and you change the post to make it clear why you're confused, I'll vote to reopen it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment