I am doing a project that shuffle 10 cards (12) time randomly but it didn't work with my code.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void show(int[],int);
void shuffle(int[],int,int);
int main (void)
{
int karten[]={1,2,3,4,5,6,7,8,9,10};
int n = sizeof(karten)/sizeof(int);
//printf("%d",n);
int s=12;
srand(time(NULL));
printf("Karten vor dem Mischen: \n");
show(karten,n);
shuffle(karten,n,s);
printf("Karten nach dem Mischen:\n");
show(karten,n);
return 0;
}
void show(int karten[],int n)
{
for(int i=0;i<n;i++)
{
printf("%d,",karten[i]);
}
printf("\n");
}
void shuffle(int karten[],int n,int s)
{
int i=0;
int d=0;
int v[]={(int)malloc(sizeof(karten))};
for(int z=0;z<=s;z++)
{
i=rand()%10;
d=rand()%10;
//printf("%d-->%d\n",i,d);
v[i]=karten[i];
v[d]=karten[d];
karten[d]=v[i];
karten[i]=v[d];
}
printf("Es wurden %d Vertauschungen gemacht\n",s);
free(v);
}
The error is
(((process returned 255)))
and the program crashed.
void shuffle(int karten[],int n,int s) is equivalent to
void shuffle(int *karten,int n,int s)
so int v[]={(int)malloc(sizeof(karten))}; allocates just the size of karten
which is a pointer to an int, so 4 bytes(on most systems).
Because of that You are trying to access unallocated memory.
sizeof(karten) don't give you the length of the array, see sizeof array clarification. Just rewrite the code like this (don't need another array):
void shuffle(int karten[],int n,int s)
{
int i=0, vi;
int d=0, vd;
for(int z=0;z<=s;z++)
{
i=rand()%10;
d=rand()%10;
vi=karten[i];
vd=karten[d];
karten[d]=vi;
karten[i]=vd;
}
printf("Es wurden %d Vertauschungen gemacht\n",s);
}
Related
I'm studing c programming language and want to sort string in ascending order. This is c code:
/* string sorted in ascending order */
#include <stdio.h>
#include <string.h>
void sort(char *name[],int n);
int main()
{
char *name[]={"Zai","Demo","CS","Apple"};
int i,n=4;
sort(name,n); // call sort function
for(i=0;i<n;i++)
{
printf("%s\n",name[i]);
}
}
void sort(char *name[],int n)
{
char *temp;
int i,j;
for(i=0;i<n-1;i++)
{
for(j=0;j<n;j++)
{
if(strcmp(name[j],name[j+1])>0)
{
temp=name[j];
name[j]=name[j+1];
name[j+1]=temp;
}
}
}
}
I use the command:
gcc -o string_sort string_sort.c
./string_sort
But it can't work.This is error:
what should I do?
for(j=0;j<n;j++) has to be for(j=0;j<n-1;j++) because otherwise name[j+1]; will be out of range. With this change, it works. Also, j=0; isn't neccesary.
for(j=0;j<n;j++)
This line is crossing the bounds of the array. It should be:
for(j=0;j<n-1;j++)
As in the loop name[j+1]; will cross the bounds when j will be just 1 less then n.
#include <stdio.h>
#include <string.h>
void sort(char *name[],int n);
int main()
{
char *name[]={"Zai","Demo","CS","Apple"};
int i,n=4;
sort(name,n); // call sort function
for(i=0;i<n;i++)
{
printf("%s\n",name[i]);
}
}
void sort(char *name[],int n)
{
char *temp;
int i,j;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++) //change at this line
{
if(strcmp(name[j],name[j+1])>0)
{
temp=name[j];
name[j]=name[j+1];
name[j+1]=temp;
}
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Program compiles fine, but returns 'segmentation fault' when ran. Please help. thanks. Ignore the other three functions. The program should Fill an array and the print the value in the array, using pointers and pointer arithmetic
#include <stdio.h>
void FillArray ( int *array, int size );
void PrintArray ( int *array, int size );
//void BubbleSort ( int *array, int size );
//void SelectionSort ( int *array, int size );
//void Swap ( int *x, int *y );
#define SIZE 20
int main (void)
{
int NumList [SIZE];
FillArray(NumList, SIZE);
PrintArray (NumList, SIZE);
}
void PrintArray (int *array, int size)
{
int i;
for (i=0; i<100; i++)
{
printf("%d \t", *(array+i));
}
}
void FillArray(int *array, int size)
{
int i;
srand(time(NULL));
for (i=0; i<100; i++)
{
*(array+i)= rand()%101;
}
return;
}
Your array contain only 20 entries but you tried to access invalid entries whose indexes were from 20 to 99.
You are trying accesing out-of-bound elements. Here is a quick fix:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 100
void FillArray ( int *array, int size );
void PrintArray ( int *array, int size );
int main (void)
{
int NumList [SIZE];
FillArray(NumList, SIZE);
PrintArray (NumList, SIZE);
}
void PrintArray (int *array, int size)
{
int i;
for (i=0; i<100; i++)
{
printf("%d \t", array[i]);
}
}
void FillArray(int *array, int size)
{
int i;
srand(time(NULL));
for (i=0; i<100; i++)
{
array[i] = rand() % 101;
}
}
You are trying to access out-of-bound elements. Here is the right way to do it.
Although you pass size of array as another argument, instead of using it, you're using a larger size of 100 which is hard coded.
#include <stdio.h>
void FillArray ( int *array, int size );
void PrintArray ( int *array, int size );
#define SIZE 20
int main (void)
{
int NumList [SIZE];
FillArray(NumList, SIZE);
PrintArray (NumList, SIZE);
}
void PrintArray (int *array, int size)
{
int i;
for (i=0; i < size; i++)
{
printf("%d \t", *(array+i));
}
}
void FillArray(int *array, int size)
{
int i;
srand(time(NULL));
for (i=0; i < size; i++)
{
*(array+i)= rand()%101;
}
return;
}
I'm trying to print array of pointer using pointer instead of array but I got this error Segmentation fault at runtime:
enter number of element:5
array[0]=1
array[1]=2
array[2]=3
array[3]=4
array[4]=5
Segmentation fault
This is the code:
#include <stdio.h>
#include <stdlib.h>
int *array;
int n;
void input(int *array,int n);
void display(int *array,int n);
int sum(int *array,int n);
int main (void) {
int result;
printf("enter number of element:");scanf("%d",&n);
input(array,n);
display(array,n);
result=sum(array,n);
printf("sum of array=%d",result);
return 0;
}
void input(int *array,int n){
int j;
array=(int *)malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);scanf("%d",array+j);
}
}
void display(int *array,int n){
int j;
for(j=0;j<n;j++)
printf("%d\t",*(array+j));
printf("\n");
}
int sum(int *array,int n){
int sum=0,j;
for(j=0;j<n;j++)
sum+=*array+j;
return sum;
}
How can I fixed this code? please somebody explain me what's wrong with that code.
Variable array is a local variable in function input.
As such, it is pointless to set it with array = ..., because this assignment takes effect only inside the function. You should typically pass its address (&array) to any function that needs to change it.
In your specific example, you also have a global variable array, so a quick solution to your problem would be to simply call function input without passing variable array as an argument:
void input(int n)
{
...
array = (int*)malloc(n*sizeof(int));
...
}
int main()
{
...
input(n);
...
}
Note that this is a "dirty" workaround, and you should typically strive to avoid the use of global variables.
To add the clean version to barak's answer:
int input(int ** array, const size_t n)
{
int result = 0;
assert(NULL != array);
(*array) = malloc(n * sizeof(**array));
if (NULL == (*array))
{
result = -1;
}
else
{
size_t j;
for(j = 0; j < n; ++j)
{
printf("array[%zu]=", j);
scanf("%d", (*array) + j); /* still missing error checking here . */
}
}
return result;
}
And call it like this:
if (-1 == input(&array, n))
{
perror("input() failed");
exit(EXIT_FAILURE);
}
Try this input():
void input(int **array,int n){
int j;
*array=(int *)malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);scanf("%d",*array+j);
}
}
Because C use pass-by-value, if you want to change the value of a variable in a function, you need to pass the address of that variable as the argument to that function.
In this case, you want to change the value of array in input() and the type of array is int *, therefore the prototype of input() should be something like void input (int **array, ...).
this should do..make sure you understand what the others have said..
#include <stdio.h>
#include <stdlib.h>
int *array;
int n;
void input(int **array,int n);
void display(int **array,int n);
int sum(int **array,int n);
int main (void) {
int result;
printf("enter number of element:");scanf("%d",&n);
input(&array,n);
display(&array,n);
result = sum(&array,n);
printf("sum of array= %d",result);
return 0;
}
void input(int **array,int n){
int j;
*array= malloc(n*sizeof(int));
for(j=0;j<n;j++){
printf("array[%d]=",j);
scanf("%d",(*array)+j);
}
}
void display(int **array,int n){
int j;
for(j=0;j<n;j++){
printf("%d\t",*((*array)+j)); // you can use array notation aswell
//array[0][j] will work
}
printf("\n");
}
int sum(int **array,int n){
int sum=0,j;
for(j=0;j<n;j++){
sum += *((*array)+j);
}
return sum;
}
What does *array + j do? Does it evaluate *array and add j to it? Or does it add j to array and then dereference it? Would you be willing to bet $100 on it if I told you you are wrong?
Make your life and the life of anybody reading your code easier by using parentheses, or even better, write array [j].
I'm trying to create a simple(?) selection sort program in C that selects the largest integer of an integer array and places it in the location a[n-1], places the second largest number in a[n-2], etc until the smallest number is placed in a[0]. I've run through the below code on paper and it seems like it should work, but when I compile it I'm getting faulty results. Am I missing something obvious?
/* The program implements selection sort*/
#include <stdio.h>
#include "simpio.h"
#define n 5
void GetArray(int a[]);
void SelectionSort(int a[]);
int FindMax(int a[], int high);
void swap(int a[], int p1, int p2);
void PrintArray(int a[]);
main()
{
int a[n];
GetArray(a);
SelectionSort(a);
PrintArray(a);
getchar();
}
void GetArray(int a[])
{
int i;
for(i=0;i<n;i++)
{
printf("Enter integer# %d", i+1);
a[i]=GetInteger();
}
}
void SelectionSort(int a[])
{
int i, max;
for(i=0;i<n;i++)
{
max=FindMax(a,i);
swap(a,max,(n-1-i));
}
}
int FindMax(int a[], int high)
{
int i, index;
index=high;
for(i=high;i<n;i++)
{
if(a[i]>a[index])
index=i;
}
return index;
}
void swap(int a[], int p1, int p2)
{
int temp;
temp=a[p2];
a[p2]=a[p1];
a[p1]=temp;
}
void PrintArray(int a[])
{
int i;
for(i=0;i<n;i++)
printf("a[%d]=%d\n", i, a[i]);
}
Change these method to:
void SelectionSort(int a[])
{
int i, max;
for(i=0;i<n;i++)
{
max=FindMax(a,n-i-1);
swap(a,max,n-i-1);
}
}
int FindMax(int a[], int high)
{
int i, index;
index=high;
for(i=0;i<high;i++)
{
if(a[i]>a[index])
index=i;
}
return index;
}
I actually tested my answer and it works.
Selection sort is process of comparing minimum element from the list and placing from the least index.
Now consider below code snippet.
public void selectionSort(int[] elements) {
for(int i=0;i<elements.length;i++) {
int minPosition = i;
for(int j=i+1;j<elements.length;j++) {
if(elements[minPosition]>elements[j])
minPosition = j;
}
int temp = elements[i];
elements[i] = elements[minPosition];
elements[minPosition] = temp;
}
}
Thanks for reading, let me know feedback to improve from myside
Shouldn't:
max=FindMax(a,i);
swap(a,max,(n-1-i));
Be:
max=FindMax(a,i);
swap(a,max,i);
otherwise, next time through the loop, you'll find the same max value in the top position in the array.
A very basic implementation of selection sort
#include<stdio.h>
main()
{
int i,j,n=7,a[]={1,2,5,3,8,9,5},key;
for(j=1;j<n;j++)
{
key=a[j]; //a[j] is the new element to be added to the sorted
//sequence
i=j-1;
while(i>=0 && key<a[i]) //traverse through the sorted sequence
{a[i+1]=a[i];i--;} //until the place of key is found
a[i+1]=key;
}
for (j=0;j<n;j++)
printf("%d",a[j]);
}
#include<stdio.h>
#include<conio.h>
int removex(int arr[],int small,int n)
{
int i=0;
for(;i<n;i++)
if(arr[i]==small) //searching that no to delete
break;
for(;i<n-1;i++)
arr[i]=arr[i+1]; //delete by overloading no
return n-1;
}
void selectSort(int arr[],int sort[],int n)
{
int j=0,k=0,small;
while(n!=0)
{
small=arr[0];
for(j=0;j<n;j++)
if(arr[j]<small)
small=arr[j]; //finding smallest no
sort[k++]=small;
n=removex(arr,small,n); //removing that from list as we included that no into sorted list
}
}
void main()
{
int arr[10],arr2[10],i,n;
clrscr();
printf("Enter how many elements");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
selectSort(arr,arr2,n);
printf("sorted list is\n");
for(i=0;i<n;i++)
printf("%d\n",arr2[i]);
getch();
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define length 100
void print_array();
int main()
{
int m,n,i,j;
int A[length][length];
printf("Give dimensions of array (up to 100x100):\ni:\n");
scanf("%d",&i);
printf("j:\n");
scanf("%d",&j);
srand(time(NULL));
for (m=0;m<i;m++)
{
for (n=0;n<j;n++)
{
A[m][n]=rand()%45+1;
printf("A[%d,%d]=%d\n",m,n,A[m][n]);
}
}
print_array(i,j,A);
return 0;
}
void print_array(int i,int j,int A[][j])
{
printf("\n");
int m,n;
for (m=0;m<i;m++)
{
for (n=0;n<j;n++)
{
printf("A[%d,%d]=%d\n",m,n,A[m][n]);
}
}
}
Hello. I am trying to print a 2d array by calling a function print but when I run the program I get:
For the first printf() the correct values:
A[0,0]=25
A[0,1]=19
A[0,2]=13
A[1,0]=4
A[1,1]=17
A[1,2]=43
A[2,0]=7
A[2,1]=37
A[2,2]=20
But when with the 2nd printf() within the function call of print_array I get:
A[0,0]=25
A[0,1]=19
A[0,2]=13
A[1,0]=0
A[1,1]=0
A[1,2]=0
A[2,0]=0
A[2,1]=0
A[2,2]=0
Seems like I miss something with pointers... Thanks.
This is C99, right?
The problem is that you're confusing the array size.
The main program has int A[length][length], but then you call the function with a dynamic size for the final dimension, A[][j]. If j != length, then the function will index the array incorrectly.
I would recommend representing the array in the function call as a bare pointer to the first element, and doing the indexing manually:
void print_array(const int *A, size_t width, size_t height)
{
for(size_t i = 0; i < height; ++i)
{
for(size_t j = 0; j < width; ++j)
printf("A[%zu][%zu] = %d\n", i, j, A[i * width + j]);
}
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <time.h>
#define length 100
void print_array(int i,int j,int A[length][length]);
int main()
{
int m,n,i,j;
int A[length][length];
printf("Give dimensions of array (up to 100x100):\ni:\n");
scanf("%d",&i);
printf("j:\n");
scanf("%d",&j);
srand(time(NULL));
for (m=0;m<i;m++)
{
for (n=0;n<j;n++)
{
A[m][n]=rand()%45+1;
printf("A[%d,%d]=%d\n",m,n,A[m][n]);
}
}
print_array(i,j,A);
return 0;
}
void print_array(int i,int j,int A[length][length])
{
printf("\n");
int m,n;
for (m=0;m<i;m++)
{
for (n=0;n<j;n++)
{
printf("A[%d,%d]=%d\n",m,n,A[m][n]);
}
}
}
Apart from the above, you need to do some input validation for the dimension (i and j). They should not exceed the length. If it exceeds the length then you will run into problems.
void print_array(int i,int j,int A[][j])
should be
void print_array(int i,int j,int A[][length])
When you tell the compiler that the actual array has different dimensions than what you earlier specified, it accesses the wrong elements. A is always 100x100, you just don't fill all of it.
You need to define the size of the array int A[][] in the function signature. Use this function instead :
void print_array(int i,int j,int A[length][length])
{
printf("\n");
int m,n;
for (m=0;m<i;m++)
{
for (n=0;n<j;n++)
{
printf("A[%d,%d]=%d\n",m,n,A[m][n]);
}
}
}
First you should forward declare your function with the correct prototype
void print_array(int n,int m, int A[n][m]);
And then use it with the correct dimensions
print_array(length, length, A);
Other than that:
use size_t for sizes instead of int
usual naming conventions have i and j as indices and n and m
as sizes. Sticking to such conventions makes code easier to read for others.
You've declared A as int A[length][length], But in the print_array function you've declare it as A[][j] which means in your function A have a different number of colones which leads to this error.
change this line
void print_array(int i,int j,int A[][j])
with this one
void print_array(int i,int j,int A[][length])
http://www.cplusplus.com/doc/tutorial/arrays/
array and matrix printing functions are little similar but tricky..
but i have worked on it and found out some thing and i think it will be useful for all
here is a simple C code for Function for printing matrix
#include<stdio.h>
void printmatrix(int l,int x,int y,int *p_arr);
void putvalue(int l,int x,int y,int *r_arr);
/* ******** Function to insert some random value in to a Matrix ************ */
void putvalue(int l,int x,int y,int *r_arr)
{
int i,j;
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
r_arr[(l*i)+j]=i+j+10;
}
}
}
/* *********Function to Print any Matrix ********** */
void printmatrix(int l,int x, int y,int *p_arr)
{
int i,j;
printf("\n");
for(i=0;i<x;i++)
{
printf("\n");
for(j=0;j<y;j++)
{
printf(" %d",p_arr[(l*i)+j]);
}
}
}
/* ****** Main ****** */
void main()
{
int i,j,l;
int Big_arr[80][100],Small_arr[20][40];
// ****** I have taken two different size arrays *****
int x,y;
clrscr();
printf("\n Enter x and y values under 20X40:"); // Because of screen size of Output
scanf("%d %d",&x,&y);
if((x!=0)&&(y!=0))
{
printf("\n %dX%d",x,y);
l=sizeof(Big_arr[0])/sizeof(Big_arr[0][0]); // **** l is the length of a single row of matrix
putvalue(l,x,y,(int*)Big_arr);
printf("\n Printing Big_arr");
printmatrix(l,x,y,(int*)Big_arr);
l=sizeof(Small_arr[0])/sizeof(Small_arr[0][0]);
putvalue(l,x,y,(int*)Small_arr);
printf("\n Printing Small_arr");
printmatrix(l,x,y,(int*)Small_arr);
}
else
printf("\n ***** Enter valied x and y values *****");
getch();
}
hope u like it.