Hey guys I am trying to finish my code but instead of getting values I am getting address of the values. Why is that?
Is the algorithm is built right? I need to arrange the array Received by the user sorted. All numbers with the rest of the division by m equal to 0 will appear at the beginning of the array, all the numbers with the rest of the division by m equal to 1 will be followed, with the rest of the two numbers will appear later, and so on. Will last the rest of the numbers with a distribution on m equal to m-1.
This is my output:
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void SortByModulo(int *arr,int m,int length);
void main()
{ int length,m,i;
int *arr;
printf("Please inseret array length:\n");
scanf("%d" ,&length);
arr=(int *)malloc(length*sizeof(int));
if(!arr) // Terms - if there is not enough memory,print error msg and exit the program.
{
printf("alloc failed\n");
return ;
}
for(i=0; i<length; i++)
arr[i]=(int)malloc(length*sizeof(int)); // Allocate memory for each row
printf("Please inseret %d elemetns :\n",length);
for (i=0 ; i<length ; i++)
{
scanf("%d" , arr[i]);
}
printf("Insert a natural number that you want to sort by modulo:\n");
scanf("%d" ,&m);
SortByModulo(arr,m,length);
system("pause");
return;
}
void SortByModulo(int *arr,int m,int length)
{ int i,j,temp,k;
for ( i=length ; i>1 ; i--)
{
for ( j=0 ; j<i-1 ; j++)
{
if((arr[j]%m)>(arr[j+1]%m))
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
for (j=0 ; j<length ; j++)
{
printf("%d ", arr[j]);
}
printf("\n");
}
First: You have memory leak! and arr[i]=(int)malloc(length*sizeof(int)); is not needed. You need only one 1-D array (declaration of arr is correct). Remove following code:
for(i=0; i<length; i++)
arr[i]=(int)malloc(length*sizeof(int)); // Allocate memory for each row
Note: Don't cast returned address by malloc() and calloc() functions. read:Do I cast the result of malloc() and calloc()
Second missing & in scanf:
scanf("%d", arr[i]);
// ^ & missing
should be:
scanf("%d", &arr[i]);
Related
I'm trying to create a program which randomly decides how many cards you have, then randomly allocates a value to each of those cards.
I have managed to randomise the amount of cards, and I know how to randomise their values using an array and a for loop, but the problem is that this method only works when I manually choose a value for the number of elements in the array, but I want the number of elements to be the random amount of cards.
How do I go about this?
Here's my code so far to show what I mean. And yes, I'm aware the code probably could be done better but this is my first C assignment and I'm a complete beginner.
Thanks :)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
int main(void)
{
system("cls"); /* Clears output to start */
srand(time(NULL)); /* Sets seed for random number generator */
int player1_amount = rand() %9 + 2; /*Generates random number for player 1's amount of cards */
int player2_amount = rand() %9 + 2; /*Generates random number for player 2's amount of cards */
int a = 1; /* For loop purposes */
while(a <= 1) /* While loop to print out each player's amount of cards once */
{
printf("Player 1 you have %d cards! \n", player1_amount);
Sleep(500);
printf("Player 2 you have %d cards! \n", player2_amount);
a++;
}
Sleep(1000); /* Delays for 1 second before printing card values */
int values[3]; /* Creates an array with 3 elements, but I want the number of elements to be player1_amount from above */
int b; /* Random variable for the loop */
int size = sizeof(values) / sizeof(values[0]); /* Gets length of array */
for (b = 0; b < size; b++) /* For loop randomises 3 values and then stops */
{
values[b] = rand() % 10 +1;
}
printf("Player 1 your cards are"); /* For loop to print out the values one after the other */
for(b = 0; b < size; b++)
{
printf(" %d, ", values[b]);
}
getch();
return 0;
}
I believe you will want to use malloc or calloc for that with a pointer.
int *values = (int *)calloc(player1_amount, sizeof(int));
Just make sure you free your allocation when done:
free(values);
C allows you to declare variable sized array. If you are not interested in using functions like malloc or calloc you can simply use variable to declare array as I've done here :
#include <stdio.h>
void main()
{
int x;
printf("\nEnter the value of x : ");
scanf("%d" , &x);
int array[x];
for(i = 0 ; i < x ; i++)
{
printf("Enter the element : ");
scanf("%d" , &array[i]);
}
for(i = 0 ; i < x ; i++)
{
printf("%d " , array[i]);
}
}
This program runs correctly without any error. So your problem is solved here itself without using malloc or calloc. But just make sure you declare your array after scanning or giving value to your variable which will represent the size of your array(here : x is the variable) and in your case I guess : player1_amount.
But still if you want to use malloc then here it goes :
#include <stdio.h>
#include <stdlib.h>
void main()
{
int x , i;
int * array;
printf("\nEnter the value of x : ");
scanf("%d" , &x);
array = (int *) malloc(x * sizeof(int));
for(i = 0 ; i < x ; i++)
{
printf("Enter the element : ");
scanf("%d" , &array[i]);
}
for(i = 0 ; i < x ; i++)
{
printf("%d " , array[i]);
}
}
Both the codes will give you same output.
A little explanation ...
Malloc will take input parameter as the amount of memory you wish to allocate to given variable(like 'array' in our case) in bytes and will output the pointer to that block of memory.
Since here we are working with integer array the return type is cast as : (int *), had it been a character array we would type cast it as : (char *).
My sorting program results in a "segmentation fault 11":
#include <stdio.h>
int main()
{
// Asking user for number of inputs in an array
int n;
do {
printf ("enter the number of intigers you want to sort\n");
scanf("%d",&n);
}while (n<=1);
int sort [n];
printf ("please enter %d numbers\n",n);
for (int i=0; i<n; i++) {
scanf("%d",&sort[i]);
}
printf("you entered\n ");
for (int i=0; i<n; i++) {
printf(" %d ",sort[i]);
}
printf("\n");
int k,c,i,x;
for (i=0;i<n;i++) {
if (sort[i]<sort[i-1]){
k=i-2;
while (sort[k]>sort[i]){
k--;
}
k++;
x =sort[i];
c=i;
for (c=i;c>k;c++){
sort[c-1]=sort[c];
}
sort[k]=x;
}
}
printf ("Sorted numbers :-\n");
for (int i=0; i<n; i++) {
printf ("%d ",sort[i]);
}
printf ("\n");
return 0;
}
Now I have looked up the internet and found that it is caused because a variable has value that exceeds the system's memory limit. But cannot understand that concept.
for (i=0;i<n;i++)
{
if (sort[i]<sort[i-1])
You are accessing array out of its bounds.Maybe you want to start your loop from 1.Also
k=i-2;
while (sort[k]>sort[i])
will access index beyond 0 for example if i is 0 or 1 or 2
k = i - 2; looks unstable for low values of i.
sort[i - 1] is undefined when i is zero.
The thing causes the behaviour of sort[k] to be undefined.
Moral of the story: check all the array indexes before attempting to retrieve an array element. Your debugger will help you here.
In addition to all said before:
c=i;
for (c=i;c>k;c++){
sort[c-1]=sort[c];
}
sort[k]=x;
i can be 0 -> c can be 0 -> sort[c-1] would also result in accessing array out of bounds.
There is no need to initialize c=i twice. It is enough to do it in the loop-declaration
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.
Hey guys I am trying to finish my code but instead of getting values i am getting an error msg
.when i am about to enter lien number 54 or 60.
if(*arr[rows*columns]<num) or printf("Number value %d in a two-dimensional size is:%d\n",num,*arr[num]);
This is error msg.
Unhandled exception at 0x013137b2 in LB_12.exe: 0xC0000005: Access violation reading location 0xabababab.
Mission description and the error msg int he next picture.
what is wrong? i have to create another array and copy the values if i want the program to print the values?
This is my code
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void SortArray(int **arr,int rows,int columns,int num);
void freemalloc ( int **arr,int rows);
void main()
{
int **arr;
int i,j,rows,columns,num;
printf("Please enter the size of 2D array(rows ,cols)");
scanf("%d %d",&rows , &columns);
arr=(int **)malloc(rows*sizeof(int *)); // Allocate array of pointers
if(!arr) // Terms - if there is not enough memory,print error msg and exit the program.
{
printf("alloc failed\n");
return ;
}
for(i=0; i<rows; i++)
arr[i]=(int *)malloc(columns*sizeof(int)); // Allocate memory for each row
printf("Please fill the 2D array\n");
for(i=0 ; i<rows ; i++)
{
for (j=0 ; j<columns ; j++)
{
printf("row:%d columns:%d\n", i,j);
scanf("%d" , &arr[i][j]);
}
}
printf("Please enter a postive number: ");
scanf("%d",&num);
SortArray(arr,rows,columns,num);
freemalloc(arr,rows);
system("pause");
return;
}
void SortArray(int **arr,int rows,int columns,int num)
{
int i,j,temp;
for(i=0 ; i<rows ; i++ ) // Bubble sort for sorting the 2d array
{
for(j=0 ; j<i-1 ; j++ )
{
if(arr[i][j]>arr[i][j+1])
{
temp=arr[i][j];
arr[i][j]=arr[i][j+1];
arr[i][j+1]=temp;
}
}
}
if(*arr[rows*columns]<num)
{
printf("No solution,The maximum value is:%d\n",arr[rows*columns]);
}
else
{
printf("Number value %d in a two-dimensional size is:%d\n",num,*arr[num]);
}
}
void freemalloc ( int **arr,int rows)
{
int i;
for (i=0 ; i<rows ; i++) // Loop for free the array of pointers
{
free(arr[i]); // free each seprate row
}
free(arr);
}
My guess is that rows * columns is larger than what you have allocated, meaning you try to dereference a random pointer, leading to undefined behavior and causing the crash.
Also, you will never sort anything, as the outer loop condition is always false (try changing > to <).
My bet is :
printf("Number value %d in a two-dimensional size is:%d\n",num,*arr[num]);
You're asking for some number and put it in variable num. What makes you think that number num is first number in num-th row?
There might be, and propably are more problems with this code.
EDIT:
*arr[num] is evaluated from right to left. [] have higher precedence than * operator.
So it first does arr[num]. and result of that is dereferenced *(arr[num]). num is treated like a row, so if you don't have enough rows-you got memory violation because you are beyond array