I cant seem to find out where i'm going wrong in C. its on line 37 it says assignment to expression with array type any help or advice would be great thanks.
I was wondering also is it something to do with not adding in the brackets to show that they're arrays on line 37 but when i put them in it displays more errors
/*
This program uses pass by reference to calculate the values after two arrays are multiplied by each other
16/02/2015
Jake Young
*/
#include <stdio.h>
#define size 5
//Prototype
int multiply_function(int *[], int *[]);
main()
{
int array1[size];
int array2[size];
int i;
int answer[size];
//get users input for array1
printf("Please enter %d values into array1:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array1[i]);
}//end for loop
//get users input for array2
printf("Please enter %d values into array2:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array2[i]);
}//end for loop
//call function()
answer=multiply_function(&array1, &array2); // line 37
//Print out the results from array1 multiplied by array2
printf("Array1 multiplied by Array2 is the following:\n");
for(i=0; i<size; i++)
{
printf("%d multiplied by %d is %d\n", array1[i], array2[i], answer[i]);
}//end for loop
}//end main()
multiply_function(int *array1[], int *array2[])
{
int *answer[size];
int i;
for(i=0; i<size; i++)
{
//calculate multiplication
*answer[i]= *array1[i]* *array2[i];
}//end for loop
return(*answer);
}//end function()
int multiply_function(int *[], int *[]);
This doesn't make any sense. You intend to pass arrays of integers to the function, not arrays of pointers. You'll have to study how arrays should be passed to functions.
main()
This form is not standard. Unless you are programming a "bare metal" embedded system, you should use int main (void).
answer=multiply_function(&array1, &array2);
This doesn't make any sense. You declared the function to return an int. Again, study how arrays are passed to and from a function. Furthermore, you can't copy arrays with the assignment operator: you have to use memcpy() or similar functions.
multiply_function(int *array1[], int *array2[])
The function definition is different than the prototype: that is always bad practice. Apart from that, the function doesn't make any sense, as already mentioned.
int *answer[size];
This doesn't make any sense, you are declaring an array of pointers where you want an array of integers.
return(*answer);
Returning a pointer to a local variable in C is always a bug. And you can't return arrays like this. And there is no need for the parenthesis.
OK, you should really invest some more time to study arrays, pointers and fundamentals of functions in C.
Apart from grammatical problems in the code, the fundamental problem in this code is the answer[] array. it is defined both in main() and the multiply_function(). What you must do is to pass this array to the multiply_function() and have the function fill in the array.
I'm giving the solution below, with the hope that you'll compare it to your version and study the differences and continue to learn the basics of C:
#include <stdio.h>
#define size 5
//Prototype
int multiply_function(int *, int *, int *);
main()
{
int array1[size];
int array2[size];
int i;
int answer[size];
//get users input for array1
printf("Please enter %d values into array1:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array1[i]);
}//end for loop
//get users input for array2
printf("Please enter %d values into array2:\n", size);
for(i=0; i<size; i++)
{
scanf("%d", &array2[i]);
}//end for loop
//call function()
multiply_function(array1, array2, answer);
//Print out the results from array1 multiplied by array2
printf("Array1 multiplied by Array2 is the following:\n");
for(i=0; i<size; i++)
{
printf("%d multiplied by %d is %d\n", array1[i], array2[i], answer[i]);
}//end for loop
}//end main()
multiply_function(int *array1, int *array2, int *answer)
{
int i;
for(i=0; i<size; i++)
{
//calculate multiplication
answer[i]= array1[i] * array2[i];
}//end for loop
return(*answer);
}//end function()
Related
I am stuck on a programming assignment in C. The user has to enter a number specifying the size of an array no bigger than 10 elements which will store the names of students. This must be done in a separate function from the main function called getNames. Each name can be up to 14 characters and getNames must be invoked from within the main function. Here is my code:
#include <stdio.h>
void getNames(char *a, int n){
int i;
for(i=0; i<n; i++){
printf("Enter a name: ");
scanf("%s", &a[i]);
}
}
void printNames(char *a, int n){
int i;
for(i=0; i<n; i++){
printf("%s\n", &a[i]);
}
}
void main(){
int num; //number of names in array 'names'
printf("Num of students: ");
scanf("%d", &num);
char names[num][15]; //each name is 14 characters plus
//a null character
getNames(names[num], num);
printNames(names[num], num);
}
The code compiles and runs without syntax errors but the array is not filled correctly. For example:
Num of students: 5
Enter a name: Jeb
Enter a name: Bob
Enter a name: Bill
Enter a name: Val
Enter a name: Matt
returns:
JBBVMatt
BBVMatt
BVMatt
VMatt
Matt
Clearly there is an issue writing to the array but I am not sure what it is.
For this assignment our professor was adamant that we cannot use any global variables. His wording was rather vague about how we should implement this. My first thought would be to move the for loop in getNames into the main function and just calling getNames repeatedly but I would like a solution that incorporates that into getNames. I'm new to C, having mostly dealt with Java so please bear with me. Any help would be appreciated.
If the code you have posted is exactly the code you are using, then it is invoking undefined behavior by accessing a memory location that your program does not own: getNames(names[num], num);.
Array indexing in C goes from 0 to n-1. (or from names[0]-names[num-1]) Same in other similar calls.
next issue is the function prototypes to accommodate;
char names[num][15];
The function needs to send the address of an array of arrays. See edits on code to show the difference.
Next issue are the following statements, see comments after each
getNames(names[num], num);//names[n] points to memory beyond what is owned.
//should point to address of beginning of memory &names[0]
printNames(names[num], num);//ditto
Working code example, see edits to explain:
//void getNames(char *a, int n){//change *a to either a[][15] or (*a)
void getNames(char a[][15], int n){
int i;
for(i=0; i<n; i++){
printf("Enter a name: ");
scanf("%s", a[i]);
}
}
//void printNames(char *a, int n){ //change *a to either a[][15] or (*a)
void printNames(char a[][15], int n){
int i;
for(i=0; i<n; i++){
printf("%s\n", a[i]);
}
}
void main(){
int num; //number of names in array 'names'
printf("Num of students: ");
scanf("%d", &num);
char names[num][15]; //each name is 14 characters plus
//a null character
//getNames(names[num], num);//names[n] points to memory beyond what is owned.
//printNames(names[num], num);//ditto
getNames(&names[0], num);
printNames(&names[0], num);
}
you can do following
Method
in main function call as below
getNames(names, num);
printNames(names, num);
and change the functions as below
void getNames(char (*a)[15], int n)
{
...
}
void printNames(char (*a)[15], int n)
{
...
}
Method , in main calls remain same
void getNames(char a[5][15], int n)
and
void printNames(char a[5][15], int n)
But instead of using hard values better to use #define row and col sizes
So there is this project in Data Structures that i have to deal with this semester and it requires that i have to code in C . The problem is that i am a little bit rusty in C and i am dealing with basic problems. One of the problems is that i have to write a simple program in C that implements BubbleSort . The BubbleSort algorithm has to be a seperate function and call it in the main program . Here is my effort . The problem is that it doesnt type the sorted array . I hope you can help me .
THE CODE :
int calculateRand()
{
int num;
num = (rand())%(UPPER-LOWER+1)+LOWER;
return num;
}
void swap(int *xp, int *yp)
{
int temp=*xp;
*xp=*yp;
*yp=temp;
}
void BubbleSort(int S[], int n)
{
int up=n;
int i,j;
while(up>1)
{
j=0;
for(i=1; i<up-1; i++)
{
if(S[i]>S[i+1])
{
swap(&S[i], &S[i+1]);
j++;
}
}
}
for(i=0; i<n; i++)
{
printf("%d\n", S[i]);
}
}
int main()
{
int n,i;
printf("Parakalw dwste mia timh sto n: \n");
scanf("%d", &n);
int S[sizeof(n)];
printf("O mi taxinomimenos pinakas einai o exis \n");
for(i=0; i<n-1; i++)
{
S[i]=calculateRand();
printf("%d\n", S[i]);
}
printf("O pinakas meta thn taxinomisi einai \n");
BubbleSort(S[sizeof(n)], n);
return 0;
}
So if we start from the top there is a problem in the calculateRand() function as you do not declare the UPPER and LOWER variables or pass them as parameters to function.
Swap function is ok.
In the BubbleSort() function you need to decrease the up variable value after the for loop.
while(up>1)
{
for(i=1; i<up-1; i++)
{
if(S[i]>S[i+1])
{
swap(&S[i], &S[i+1]);
j++;
}
}
up--;
}
Also at this point you should start iterating from 0 instead of 1 since arrays start from index 0. So for(i=0; i<up-1; i++) is the correct way to go.
Lastly in the main() function when you're declaring the array variable S you shouldn't pass the sizeof(n) since n is an integer and size of an integer is 4. Instead you want to use n as it is int S[n];
For loop to populate the array should go up to n not n-1 if you want to fill all elements of the array. However if you change this you'll need to make the similar change in the BubbleSort() function.
And finally in the BubbleSort() function call you are passing the last element of the array which is an integer whereas function expects you to pass an array. It should look like this BubbleSort(S, n); instead.
sizeof(n) has nothing to do with the value of the variable n. It's the the size of the variable n, i.e. mostly 4 bytes for the modern architectures.
Modern variants of C permit variable size arrays thus
int S[n];
would have been legit. Otherwise
int *S = (int *)malloc(n*sizeof(int));
will help.
When you call BubbleSort , your argument should be S not S[sizeof(n)];
as the title says, my program crashes when i try to print a bidimensional array.
The error is surely printf in function printarray, but i couldn't understand why it lead to crash.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#define COL 40
#define ROW 40
void printarray(int array[COL][ROW], int col, int row);
main (){
int n,m,p,q;
int array[COL][ROW];
printf("Dammi 2 numeri \n"); scanf("%d",&n); scanf("%d",&m);
do{
printf("Dammi 2 p[<n] e q[<m] \n"); scanf("%d",&p); scanf("%d",&q);
}while(p>=n || q>=m);
printf("Mi hai dato: n= %d m= %d p= %d q= %d \n",n,m,p,q);
int i,j;
int random;
srand(time(NULL));
for(i=0; i<=n;i++){
for(j=0; j<=m;j++){
do{
random = rand() % 10;
}while(random == 0);
printf("\n i am at array[%d][%d] with number: %d\n",i,j,random);
array[i][j] = random;
}
}
//printf("lol0 ->>>>>>>>>>>%d<--------",array[0][0]);
printarray(array[n][m],n,m);
system("PAUSE");
}
void printarray(int array[COL][ROW], int col, int row){
int i,j;
for(i=0; i<=col;i++){
//printf("lol3 %d",i);
for(j=0; j<=row; j++){
printf("%d",array[i][j]);
}
printf("\n");
}
}
If an array dimension has size N then the valid range of indices is [0, N - 1].
So the loops in the function should look like
void printarray(int array[COL][ROW], int col, int row){
int i,j;
for(i=0; i< col;i++){
//printf("lol3 %d",i);
for( j=0; j<row; j++){
printf("%d",array[i][j]);
}
printf("\n");
}
}
The same is valid for loops in main.
This call of the function invalid
printarray(array[n][m],n,m);
There shall be
printarray(array,n,m);
Take into account that such a declaration of an array like
int array[COL][ROW];
is very confusing. It would be more correctly to write
int array[ROW][COL];
^^^ ^^^
Also it is not clear what is the meaning of variables p and q in this loop
does not make sense
printf("Dammi 2 numeri \n"); scanf("%d",&n); scanf("%d",&m);
do{
printf("Dammi 2 p[<n] e q[<m] \n"); scanf("%d",&p); scanf("%d",&q);
}while(p>=n || q>=m);
It seems that this loop is from some other program.:)
And you have to check that n and m are not greater than ROW and COL.
Also it is a bad idea to mix l'Italian with English.:)
The posted code does not cleanly compile, for several reasons.
1) missing
#include <time.h>
2) function main() ALWAYS returns 'int' so a proper main statement would be: 'int main( void )'
3) the first parameter to 'printarray()' is defined to be a pointer to a 2 dimensional array.
However,
a) the actual call passes the contents of a specific 'cell' in the array.
b) the passed 'cell' is beyond the end of the array.
Suggest: 'printarray( array, n, m )' as the calling statement.
Note, in C, an array name degrades to the address of the first entry in the array.
4) an array should be defined as arrayName[numRows][numColumns].
This will become much more important when declaring an array of pointers where each pointer will point to the contents of the associated row.
In the posted code, the definition/naming is backwards from typical.
in Memory, an array is laid out left to right (the columns) then top to bottom (the rows).
The 'biggest' index is rows and should be listed first.
5) to avoid text replacement problems, numeric values in macros should be wrapped in parens.
6) as a suggestion, appropriate vertical spacing (blank line) between code blocks makes the code much clearer and more understandable by us humans
7) when calling scanf() (and family of functions) always check the returned value (not the parameter values) to assure the operation was successful
8) consistent indentation makes the code much easier to read/understand by us humans, suggest: indent 4 spaces after every opening brace '{' and un-indent before every closing brace '}'. Note: Never use tabs for indenting. Different environments have different tab widths and/or different tab stops.
9) for readability, and to make debug much easier, only place one statement per line of code. This applies to declaring variables, so they can be easily commented and applies to executable statements
here i am attaching the your program without any error. the problem was to calling the printarray function.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#define COL 40
#define ROW 40
void printarray(int array[COL][ROW], int col, int row);
main (){
int n,m,p,q;
int array[COL][ROW];
printf("Dammi 2 numeri \n"); scanf("%d",&n); scanf("%d",&m);
do{
printf("Dammi 2 p[<n] e q[<m] \n"); scanf("%d",&p); scanf("%d",&q);
}while(p>=n || q>=m);
printf("Mi hai dato: n= %d m= %d p= %d q= %d \n",n,m,p,q);
int i,j;
int random;
srand(time(NULL));
for(i=0; i<=n;i++){
for(j=0; j<=m;j++){
do{
random = rand() % 10;
}while(random == 0);
printf("\n i am at array[%d][%d] with number: %d\n",i,j,random);
array[i][j] = random;
}
}
//printf("lol0 ->>>>>>>>>>>%d<--------",array[0][0]);
printarray(array,n,m);
system("PAUSE");
}
void printarray(int array[COL][ROW], int col, int row){
int i,j;
for(i=0; i<=col;i++){
//printf("lol3 %d",i);
for(j=0; j<=row; j++){
printf("%d",array[i][j]);
}
printf("\n");
}
}
I want to make a program that uses a function I created where it swaps all the elements of an array X (that has the length of N) with some number K, only if that element is greater than K. Where am I going wrong here?
#include <stdio.h>
#include <stdlib.h>
int swap_K(int *, int);
int main()
{
int N,i,K;
printf("Enter N: ");
scanf("%d",&N);
printf("Enter K: ");
scanf("%d",&K);
int X[N];
for (i=1; i<=sizeof(X)/sizeof(int); i++){
printf("Enter %d. element: ",i);
scanf("%d",&X[i]);
}
swap_K(X,K);
for (i=1; i<=sizeof(X)/sizeof(int); i++){
printf("%d",X[i]);
}
}
int swap_K(int *X, int K)
{
int i;
for (i=1; i<=sizeof(X)/sizeof(int); i++){
if (X[i]>K)
X[i]=K;
}
return X;
}
In swap_K(int *X, int K), sizeof(X) is sizeof(int *), not the size of the array.
In C, a pointer is not really the same as an array.
To fix it, use N instead of sizeof(X)/sizeof(int) everywhere, esp. inside swap_K().
1) Arrays start with index 0.
2) In your main function you don't need to use sizeof(X)/sizeof(int) in for loop as you already know it is equal to N.
3) When you pass the array to the function, you are sending the base address of the array which decays into pointer, so in swap_K function, sizeof(X) will return sizeof(int) which is 4(generally).
To overcome this you should send the size of your array from main function. For example: swap_K(X,K,N);
4) You don't need to return X from swap_K as you are sending the base address of X from main function.
For example:
#include <stdio.h>
#include <stdlib.h>
int swap_K(int *, int, int);
int main()
{
int N,i,K;
printf("Enter N: ");
scanf("%d",&N);
printf("Enter K: ");
scanf("%d",&K);
int X[N];
for (i=0; i<N; i++)
{
printf("Enter %d. element: ",i);
scanf("%d",&X[i]);
}
swap_K(X,K,N);
for (i=0; i<N; i++)
{
printf("%d",X[i]);
}
}
int swap_K(int *X, int K,int N)
{
int i;
for (i=0; i<N; i++)
{
if (X[i]>K)
X[i]=K;
}
//return X; //This is not required
}
Your loop is incorrect
for (i=1; i<=sizeof(X)/sizeof(int); i++)
It should be
for (i=0; i<N; i++)
There are several problems with the code posted:
arrays in C are 0-indexed, so the for loops should ALWAYS iterate from 0 to N - 1. Iterating past N is a buffer overflow
the pointer to the array is just the pointer to the first element of the array. The swap function can't know if the pointer passed to it is part of an array or a single value. With this in mind it will need to take another argument which tells what is the size of the passed in array as pointer. Iteration inside the loop will use that value instead of sizeof(X) / sizeof(int) = 1
you're defining X as a variable sized array which is allocated entirely on the stack. Introducing a reasonably large N will crash your program. It would be better to allocate the array in the heap if you don't know what the size of the input will be.
I have been asked to write a lottery program in c++ not sure if i am using function correctly please help
//function prototypes
int myNumbers();
void displayNums();
#include <stdio.h>
#define NUMS 6
#define WIN 7
// function myNumbers takes input from user
int myNumbers(int numbers[]) //implememt function
{
int i;
int numbers;
int input[NUMS];
printf ("Please enter your lucky numbers\n");
for (i=0;i<NUMS;i++)//loop through array to take input
{
scanf("%d",&input[i]);
}//end for loop
return (numbers);
}//end function myNumbers
Each of your functions declares a new array, rather than using the array passed to it as an argument.
void displayNums(int print[])
{
int i;
int output;
int numbers[NUMS];
output = myNumbers(numbers);
printf("Your numbers are %d \n", output);
}
Note that nowhere is the print argument used, and you're using int numbers[NUMS] instead. Remove that declaration and use print. (Also please consider naming your argument something other than print; this name is confusing and does not accurately describe what the variable stores.)
you are not using arrays properly to communicate the numbers, see the function
int myNumbers(int userPick[]) //implememt function
{
int i;
int numbers;
int input[NUMS];
printf ("Please enter your lucky numbers\n");
for (i=0;i<NUMS;i++)//loop through array to take input
{
scanf("%d",&input[i]);
}//end for loop
numbers = *(input+i);
return (numbers);
}//end function myNumbers
it reads the number to a local array and returns *(input+i) which will be a random number since your read array is from input+0 to input+i-1. you should pass array or pointer to global array.
Even in case of display() function you are passing one array and using some other array inside display() function.
you should use a common array to communicate values. you can create a array in global scope and use it in all functions or create a array in main() and pass pointer to it to other functions and use the same array in other functions. learn how to pass arrays between functions and use arrays
Your functions looks erroneous:
int myNumbers(int userPick[]) // 1. userPick is not used anywhere
{
int i;
int numbers; // 2. initialize this variable to 1 first
int input[NUMS];
printf ("Please enter your lucky numbers\n");
for (i=0;i<NUMS;i++)
{
scanf("%d",&input[i]);
}//end for loop
numbers = *(input+i); // 3. is this suppose to be inside the loop ?
return (numbers);
}//end function myNumbers
And in
void displayNums(int print[])//implement function
{
int i;
int output;
int numbers[NUMS];
output = myNumbers(numbers);
printf("Your numbers are %d \n",output);
}//end function displayNums
You don't use print but create a new array numbers
Most of your code is erroneous. It won't compile. Here's some sample code. Work with it to implement the rest
#include <stdio.h>
#define NUMS 6
void displayNums(int nums[])
{
int i;
printf("Your numbers are:\n");
for(i = 0; i < NUMS; i++)
printf("%d ", nums[i]);
printf("\n");
}
void myNumbers(int nums[])
{
printf("Please Enter your lucky numbers\n");
int i;
for(i = 0; i < NUMS; i++)
scanf("%d", &nums[i]);
}
int main()
{
int numbers[6];
myNumbers(numbers);
displaynums(numbers);
//do the rest of the stuff here
return 0;
}
Going through a C tutorial might be helpful? Check out http://c.learncodethehardway.org/book/ for a nice intro to the language.