/*I am getting the following errors
free.cpp: In function 'int main()':
free.cpp:24: error: expected `;' before 'obj'
free.cpp:25: error: 'obj' was not declared in this scope
free.cpp:25: error: expected primary-expression before 'int'*/

#include<iostream>
using namespace std;
int array[]={0,1,2,3,4,5,6,7,8,9};

class free
{
	public:
	void function(int array[]);
};



void free::function(int array[])
{
	for (int i=1;i<=10 ;i++ )
	{
		cout<<array[i];
	}
}


int main()
{
free obj;
obj.function(int array[]);
 return 0;
}

Dani AI

Generated

Following 's helpful reply, here are practical, durable ways to pass arrays in C++ and avoid the common pitfalls the thread didn't cover.

A safe C-style pattern — pass a pointer and an explicit length so the callee knows the bounds:

#include <iostream>
#include <cstddef>

void printArray(const int* a, std::size_t n) {
    for (std::size_t i = 0; i < n; ++i)
        std::cout << a[i] << ' ';
    std::cout << '\n';
}

int main() {
    int arr[] = {0,1,2,3,4,5,6,7,8,9};
    printArray(arr, sizeof(arr) / sizeof(arr[0]));
}

Why this helps: function parameters like int a[] decay to int*, so the function does not know the array length. Always pass the size (or use a container). Watch for off-by-one and bounds mistakes — iterate 0 to n-1 (use < n, not <= n), and prefer const if you don't modify the data.

Modern alternatives (preferred when available): use standard containers or views. Example with C++20 std::span:

#include <iostream>
#include <span>

void printSpan(std::span<const int> s) {
    for (int v : s) std::cout << v << ' ';
    std::cout << '\n';
}

int main() {
    int arr[] = {0,1,2,3,4,5,6,7,8,9};
    printSpan(arr); // span deduces size from the array
}

Quick checklist:

  • Pass the size or use std::array/std::vector/std::span.
  • Iterate i = 0; i < n; ++i.
  • Use const where applicable.
  • Avoid putting types in the function call — pass the variable name only.

For : beyond the compilation hiccup resolved earlier, confirming the index range and adopting one of the above patterns will prevent runtime out-of-bounds reads.

Recommended Answers

All 2 Replies

/*I am getting the following errors
free.cpp: In function 'int main()':
free.cpp:24: error: expected `;' before 'obj'
free.cpp:25: error: 'obj' was not declared in this scope
free.cpp:25: error: expected primary-expression before 'int']

free is a reserved keyword in c++ and c. You need to name your class something else.

Thanks,now it is working.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.