So I am currently getting into programming and I'm trying to write this code, but I am having trouble with arrays. I have read a lot of articles online and it seems that this code should work, but for some reason there is an error when I pass my arrays between my functions. Ignore the commented out section in the middle that is where I got it to work inside my main function. For this assignment I need it to work in the functions I defined below. I am just wanting to initialize my array in one function then print it out in the other.
Thanks!
here is the error it displays
prelab7.c:32: warning: passing argument 1 of ‘print_array’ makes pointer from integer without a cast
prelab7.c:7: note: expected ‘int *’ but argument is of type ‘int’
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int errorcheck(int );
void intializearrary(int[], int);
void print_array(int [], int);
int main()
{
int maxsize,i;
int n[maxsize];
printf("\nEnter the size of the input: ");
scanf("%d", &maxsize);
while (errorcheck (maxsize))
{
printf("\nInvalid input enter the size of the input again");
scanf("%d", &maxsize);
}
/* srand(time(NULL));
for (i = 0; i < maxsize; i++)
{
n[i] = generaterandomnumber();
printf("\nn[%d]=%d", i, n[i]);
}
*/
print_array( n[i], maxsize);
return 0;
}
int errorcheck (int maxsize)
{
if (maxsize < 0 || maxsize > 100)
return 1;
else
return 0;
}
void initializearrary( int n[],int maxsize )
{
int i;
srand(time(NULL));
for (i = 0; i < maxsize; i++)
{
n[i] = rand()%10;
}
}
void print_array(int n[], int maxsize)
{
int i; //counter
printf("\nInput Array\n");
for (i = 0; i < maxsize; i++)
{
{
printf("\t%d", n[i]);
}
}
/*int generaterandomnumber()
{
return rand()%10;
}*/
Move
int n[maxsize];
Just after the while loop and change
print_array( n[i], maxsize);
To
print_array( n, maxsize);
The former is done so that maxsize gets initialized before the VLA is constructed.
The latter is done because print_array expects an int* as the first argument, but you pass an invalid argument n[i] which is of type int.
Related
I can't solve simple task to generate matrix with given size. I'm getting too much errors whitch do not understand like: C2087, C2131 or C2447 (Microsoft Visual Studio)
Please help me if you can
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iomanip>
int max = 100;
void random(int & size, int M[][])
{ for (int i = 0; i < size; i++)
{ for (int j = 0; j < size; j++)
{
M[i][j] = rand() % 9;
}
}
}
void display(int size, int M[][])
{ for (int i = 0; i < size; i++)
{ for (int j = 0; j < size; j++)
{
printf("%d", &M[i][j]);
}
}
}
int main()
{
printf("give me matrix size\n");
int size;
scanf_s("%d", &size);
//int* M = new int[size][size];
int M[max][max];
random(size, M);
display(size, M);
return 0;
}
There is an issue with the way that you are handling arrays in c. Arrays are not actually passed around as arrays, but as pointers.
Consider this example
void print_arr (int array[], int length);
void print_arr (int * array, int length);
void print_arr (int array[10], int length);
void print_arr (int array[11], int length);
These four functions, as far as c is concerned, are the same. When you pass an array as a function argument, you are actually just passing a pointer. It works okay because you can access indexes of pointers. When you write
int function (int array[]) {
return array[3];
}
C will take the address of array, add (3 * sizeof(int)), and return that value. It can do this because it knows each element of the array has the size of int.
The problem with this is that you cannot pass two dimensional arrays in c. When you write
void function (int array[][]) {
array[2][3];
}
C will first calculate the first index. The issue is that it does not know the size to offset the array by. What if your array is 4 by 4? what if it's 7 by 9? Each possible size would require a different offset, and c doesn't know which.
There are a few options. Either write the size in ahead-of-time, like this:
int function (int array[10][10]) {
return array[2][3];
}
This tells c the size of the array, and lets it correctly calculate offsets.
Or, if you don't know the size ahead of time, manually pass the information in, like this:
int function (int * array, int width) {
int index = (2 * width) + 3;
return array[index];
}
In this example, you're basically doing the math that c normally does for you, manually.
Thank you Carson. So i tried to make matrix by making long array. Still I have problem with pointers I think.
My errors:
Error C2540 non-constant expression as array bound line 30
Error C2440 'initializing': cannot convert from 'int (*)[1]' to 'int *' Line 30
Error C2664 'void random(int,int *)': cannot convert argument 2 from 'int' to 'int *' Line 32
Error C2664 'void wypisz(int,int *)': cannot convert argument 2 from 'int' to 'int *' Line 33
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void random(int size, int * M)
{
for (int i = 0; i < size^2; i++)
{
int x = rand() % 9;
M[i] = x;
}
}
void display(int size, int *M)
{
for (int i = 0; i < size^2; i++)
{
printf("%d ", &M[i]);
if(size%i==0)
printf("\n");
}
}
int main()
{
printf("Gimme size: \n");
int size;
scanf_s("%d", &size);
int* M = new int[size][size];
random(size, *M);
display(size, *M);
return 0;
}
#include <stdio.h>
int main(void) {
int list_size;
printf("size of the array:");
scanf("%d", &list_size);
int list[5];
for (int i = 0; i < list_size; i++) {
scanf("%d", &list[i]);
}
printArray(list, 5);
return 0;
}
void printArray(int list[], int list_size){
for (int j = 0; j < list_size; j++) {
printf("%d ", list[j]);
}
}
Error C2371 : 'printArray' : Override, the default format is different. How can I change the code?
Is the array declaration wrong?
I have to make function 'printArray', so I can't put code into main function.
For starters you are not using the variable list_size in the array declaration
scanf("%d", &list_size);
int list[5];
It seems you mean
int list[list_size];
Correspondingly the function printArray should be called like
printArray(list, list_size);
You have to declare the function printArray before its call for example before main
void printArray(int list[], int list_size);
int main( void )
{
//...
}
As the function does not change the passed array then the first parameter should be declared with the qualifier const.
void printArray(const int list[], int list_size);
int main( void )
{
//...
}
And the function can be defined like
void printArray( const int list[], int list_size ) {
for (int j = 0; j < list_size; j++) {
printf("%d ", list[j]);
}
putchar( '\n' );
}
Pay attention to that this declaration
int list[list_size];
declares a variable length array. You need to set a corresponding option of the compiler to compile your program according to the C99 Standard.
Otherwise you could define some large enough constant for the size of the array. For example
int main( void )
{
enum { N = 100 };
int list[N];
int list_size;
printf( "size of the array (not greater than %d): ", N );
if ( scanf( "%d", &list_size ) != 1 || N < list_size ) list_size = N;
//...
Like this
/* function declaration or prototype */
void printArray(int list[], int list_size);
int main(void) {
...
}
void printArray(int list[], int list_size) {
...
}
You have to declare functions before you use them. Function declarations are also called prototypes.
You should declarate the function after the headers files if you make the function after the principal program
#include <stdio.h>
void printArray(int list[], int list_size);
int main(void)
{
int list_size;
do
{
printf("size of the array:");
scanf("%d", &list_size);
}
int list[list_size];
for (int i = 0; i < list_size; i++)
{
scanf("%d", &list[i]);
}
printf("\nDisplay of array :\n");
for (int i = 0; i < list_size; i++)
{
printf("%d", list[i]);
}
printf("\n\n");
printArray(list, list_size);
return 0;
}
void printArray(int list[], int list_size)
{
printf("\nDisplay of array :\n");
for (int j = 0; j < list_size; j++)
{
printf("%d ", list[j]);
}
}
This code print 2 time the output of array,if you want to display the array 1 time you should remove this foor loop :
printf("\nDisplay of array :\n");
for (int i = 0; i < list_size; i++)
{
printf("%d", list[i]);
}
C is parsed without looking ahead. You could write a single-pass C compiler (not the most useful thing, but the language was designed with this in mind). When the compiler sees the call to printArray, i.e. the line printArray(list, 5);, it doesn't know yet what printArray's real declaration is - it hasn't read it yet. But it has to do something with that call, and instead it makes a guess: the compiler implicitly declares, at that moment, the function as-if you had the following declaration:
int printArray();
In C, this declaration really means
int printArray(...);
And thus, the call to printArray is generated with such an implicit declaration - the function is called as if it was a variadic function. But it isn't a variadic function. You later attempt to define it in an incompatible way, as:
void printArray(int [], int);
This is not allowed and triggers an error: in C, all the declarations must agree with the definition. C allows multiple declarations - they are not an error, as long as they all agree. In your case they didn't: the implicit one didn't match the explicit one that came later.
There are two ways of fixing this error:
Declare void printArray(int list[], int size); before the point of use, e.g. before main. You can still define it later - after main.
Change the signature of printArray to match what the compiler implied, i.e. printArray(...) { ... }. The only problem is: such a signature would be useless. You can pass whatever arguments you want into that function, but there's no way to actually use them from inside the function. That variadic argument mechanism of C requires at least one named argument. So no luck there. A minimum viable printArray function with variadic arguments could look as follows - and of course then it's not defined as printArray(...) anymore, so the compiler would raise the error you see due to the mismatch of implicit declaration and definition, and you're back to square one.
void printArray(int list[], ...)
{
va_list args;
va_start(args, list);
int count = va_arg(args, int);
for (int i = 0; i < count; ++i) printf("%d ", list[i]);
printf("\n");
va_end(args);
}
The problem is in va_start: you have to pass it the first named argument to the function. With a signature like printArray(...), there are no named arguments, and thus you can't use va_start, and there's no way of accessing any arguments passed to such function from the inside of it - not while depending on Standard (portable) C. On various architectures there are non-portable "hacks" to bypass this issue, but they are not recommended at all.
Note: If you want to declare a function with no arguments in C, it should be declared as:
int myFunction(void); /* <- like this, not like -> */ int myFunction();
To add to the potential confusion, C++ sees things differently: there, the int foo(void) is redundant, since it interprets int foo() as a function taking no parameters, and not as int foo(...) like C would.
You could've declared your function before the main() one. As for the rest, I don't see the problem with your function.
#include <stdio.h>
void printArray(int list[], int list_size)
{
for (int j = 0; j < list_size; j++)
{
printf("%d ", list[j]);
}
}
int main(void)
{
int list_size;
printf("size of the array:");
scanf("%d", &list_size);
int list[list_size];
for (int i = 0; i < list_size; i++)
{
scanf("%d", &list[i]);
}
printArray(list, list_size);
return 0;
}
I have two functions. One that creates a multiplication table of a given number and the other function prints the array out. Below is my code:
Here's the error (Line 18):
expression must be a pointer to a complete object type
How do I fix this error and print the array? Also, I don't know how to print a new line after every row.
#include "multiplication.h"
#include <stdio.h>
int arr[][];
void mulitpication(int num){
/* initialize array and build*/
int arr[num][num];
for(int i=0; i<num;i++){
for(int j=0;j<num;j++){
arr[i][j]= (i+1)*(j+1);
}
}
}
void print(int arr[][]){
/* print the arr*/
int i;
for(i=0;i<sizeof(arr);i++){
for(int j=0;j<sizeof(arr);j++){
printf("%d ",arr[i][j])**(line 18)**;
}
}
}
If using C99 or later with VLA support, pass into the print function the dimensions needed.
// void print(int arr[][]){
void print(size_t rows, size_t cols, int arr[row][col]){
size_t r,c;
for (size_t r = 0; r < rows; r++) {
for (size_t c = 0; c < cols; c++) {
printf("%d ",arr[r][c]);
}
printf("\n");
}
}
You need to declare the array in main(), so it can be passed to both functions.
When an array is passed as a function parameter, it just passes a pointer. You need to pass the array dimensions, they can't be determined using sizeof.
To get each row of the table on a new line, put printf("\n"); after the loop that prints a row.
#include <stdio.h>
void multiplication(int num, arr[num][num]){
/* initialize array and build*/
for(int i=0; i<num;i++){
for(int j=0;j<num;j++){
arr[i][j]= (i+1)*(j+1);
}
}
}
void print(int num, int arr[num][num]){
/* print the arr*/
int i;
for(i=0;i<num;i++){
for(int j=0;j<num;j++){
printf("%d ",arr[i][j]);
}
printf("\n");
}
}
int main(void) {
int size;
printf("How big is the multiplication table? ");
scanf("%d", &size);
int arr[size][size];
multiplication(size, arr);
print(size, arr);
return 0;
}
My issue is that I am getting segmentation fault (core dumped) each time I try, I have yet to clean up my code, but I am stumped.
I must enter the values in with the compiler e.g "./filename 0 100" whereby 0 is min and 100 is max.
It must then fill the array of 10 elements with random numbers (0-100). I am so close, just can't fathom the main function.
Also, how can I print the array {0,1,2,3} in format "[0,1,2,3]" including the commas, without it looking like "[0,1,2,3, ]"
#include <stdlib.h>
#include <stdio.h>
int getRandom(int min, int max);
void fillArray(int data[], int size, int min, int max);
void printArray(int data[], int size);
int main(int argc, char *argv[]) {
int a;
int b;
if (argc>=3){
a = atoi(argv[1]);
b = atoi(argv[2]);
int arr[10];
printf("\t An array with random values from 0 to 100 \n");
fillArray(arr,10 ,a, b);
printArray(arr, 10);
} else {
printf("Incorrect number of arguments - please call with assignment min max\n");
}
return 0;
}
int getRandom(int min, int max) {
int result = 0;
int low = 0;
int high = 0;
if (min<max) {
low = min;
high = max+1;
} else {
low = max + 1;
high = min;
}
result = (rand() % (high-low)) + low;
return result;
}
void fillArray(int data[], int size, int min, int max){
int i;
for(i=min ; i < max+1; i++){
data[i] = getRandom(min,max);
}
}
void printArray(int data[], int size){
int i;
printf("[");
for(i=0; i<size; i++){
printf("%d,", data[i]);
}
printf("]");
}
I agree with #Steve Friedl that the main problem with your program lies in the fillArray function. There i should run from 0 to size.
As for your second question, testing whether you're printing the last number helps to suppress the unwanted comma:
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
printf("%d", data[i]);
if (i < size - 1)
printf(",");
}
printf("]");
}
If you prefer a more compact solution (although with an optimizing compiler there's not really a difference), you could write it as:
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
printf("%d%c", data[i], i < size-1 ? ',' : ']');
}
}
Also, in your main function, you should include a and b in your printing:
printf("\t An array with random values from %d to %d \n", a, b);
I believe this is blowing things up for you:
void fillArray(int data[], int size, int min, int max){
int i;
for(i=min ; i < max+1; i++){ // <-- HERE
data[i] = getRandom(min,max);
}
}
The calling function allocates 10 items in the arr array, and that's passed as the size parameter, but you're not using that parameter to limit filling up the array. If the max value is 100, then it's trying to fill one hundred slots instead of just ten.
for (i = 0; i < size; i++)
data[i] = getRandom(min,max);
should fix at least this issue.
EDIT: The comma thing, I prefer to add commas before the items unless this is the first. In this case it doesn't matter much, but it's more general, especially for variable-length lists where you don't know you're at the end until you get there. Augmenting the helpful response from #JohanC :
void printArray(int data[], int size) {
printf("[");
for (int i = 0; i < size; i++) {
if (i > 0) printf(",");
printf("%d", data[i]);
}
printf("]");
}
Sorry for that title. I really didn't know how to define this problem.
I was needed to declare integer array of N numbers and to fill it with random nums in void function. Then that array needs to be printed in main. The thing is that i am not allowed to use printf in void function so only way to print in main is to use pointers I guess. My knowledge is limited as I am beginner at pointers. Thx in advance and sorry for bad english.
Here is my code so far. When I compile it marks segmentation error.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void form();
int main()
{
int N, a[100];
printf("Input index: \n");
scanf("%d", &N);
form(N, &a);
printf("Array: \n");
for (int i = 0; i < N; i++) {
printf("a[%d] = %d", i, a[i]);
}
}
void form(int N, int *ptr[100])
{
srand(time(NULL));
for (int i = 0; i < N; i++) {
*ptr[i] = rand() % 46;
}
There are several issues in your code.
1) Your array decalaration form() is obsolete. Use proper prototype.
2) For declaring a VLA, declare it after reading N instead of using a fixed size array.
3) An array gets converted into a pointer to its first element when passed to a function. See: What is array decaying?
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void form(int, int*); /* see (1) */
int main(void) /* Standard complaint prototype for main.
If you need to pass arguments you can use argc, and argv */
{
int N;
printf("Input size: \n");
scanf("%d", &N);
int a[N]; /* see (2) */
form(N, a); /* see (3) */
printf("Array: \n");
for (int i = 0; i < N; i++) {
printf("a[%d] = %d", i, a[i]);
}
}
void form(int N, int *ptr) { /* Modified to match the prototype
srand(time(NULL));
for (int i = 0; i < N; i++) {
ptr[i] = rand() % 46;
}
}
So a couple things:
void form();
As Olaf was alluding to, this declaration is incorrect - you are missing the applicable parameters. Instead, it should be
void form(int N, int ptr[100]);
The main reason your program is crashing is because of the following line:
*ptr[i] = rand() % 46;
You are dereferencing the pointer at i, which is actaully giving you a number - what you want is to assign the value of the pointer at i the new random value:
ptr[i] = rand() % 46;
As related reading, see this question about passing an array in as a function parameter (basically, int ptr[] is the same thing as int * ptr)
Small modifications on your code:
1) Correction and simplification of parameter handling at function call. Just hand over "a", it's an array, so it is an address, you can use int *ptr, or int ptr[], or int ptr[100] in the formal parameter list for it. So you can use simply ptr[i] in your function.
2) Make a prototype for function from old-style declaration providing parameter list.
3) int i; declaration before the for loop - not mandatory, depends on your compiler standard
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void form(int N, int *ptr);
int main()
{
int N, a[100];
printf("Input index: \n");
scanf("%d", &N);
form(N, a);
printf("Array: \n");
int i;
for (i = 0; i < N; i++) {
printf("a[%d] = %d", i, a[i]);
}
}
void form(int N, int *ptr)
{
srand(time(NULL));
int i;
for (i = 0; i < N; i++) {
ptr[i] = rand() % 46;
}
}