I wrote a program which should create many random numbers and save it in an array. I also checked up many questions and everyone just saying to set seed one time but that does not solve my problem.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
void printArray(int *arr){
for(int i = 0; arr[i] != '\0'; i++){
printf("%i, ", *arr);
}
}
int main(int argc, char* argv[])
{
// set seed
srand(time(NULL));
int number_max;
// first argument
int arg1 = atoi(argv[1]);
if(arg1 <= 4){
printf("number to small or not a number\n");
return 0;
}
// 2^n space for random numbers
number_max = pow(2, arg1);
// initialize array
int numbers[number_max];
// create 2^n random numbers from 0 to 10000
for(int i = 0; i < number_max; i++){
numbers[i] = (rand() % (10000 - 0 + 1)) + 0;
}
// print Array
printArray(numbers);
}
That is my code. My whole array contains the same value. I understand the problem, but don't know how to solve.
Thanks for your help :)
Few things:
Your loop condition for (int i = 0; arr[i] != '\0'; i++) requires that the array is terminated with zero. This is not the case unless you explicitly terminate the array with zero. Also, if any of the values in numbers is zero, it will stop there.
You are always dereferencing the first element in the array. Print arr[i] or *(arr + i) to print the actual array values one by one.
Not code related, but it's grammatically correct to say "number too small", not "number to small". :-)
You see same values because you are printing same element *arr, which is equivalent to arr[0].
Maybe you want this:
void printArray(int *arr){
for(; *arr != '\0'; arr++){
printf("%i, ", *arr);
}
}
or this:
void printArray(int *arr){
for(int i = 0; arr[i] != '\0'; i++){
printf("%i, ", *(arr + i));
}
}
or this:
void printArray(int *arr){
for(int i = 0; arr[i] != '\0'; i++){
printf("%i, ", arr[i]);
}
}
Note that you can write simply 0 instead of '\0'.
Related
I want to copy my array over to a pointer, so I can sort the array without changing the original. I'm not getting any errors, and am at a dead end. I've tried printing the pointer's contents, but it's always junk data. If anyone could help me it'd be much appreciated.
#include <stdio.h>
void bubbleSort(char *array[], int arrIndex);
void displaySort (char *array[], int arrIndex);
int main (void)
{
int index;
int count = 0;
printf("Enter number of people (0 - 50): ");
scanf("%d", &index);
index -= 1;
char userLastFirst[25][index];
int userAge[index];
//defining pointer
char *namePtr[25][index];
//do while loop, loops while count is less than or equal to the index
do{
printf("Enter name %d (last, first): ", count);
scanf(" %[^\n]s", userLastFirst[count]);
printf("Enter age %d: ", count);
scanf("%d", &userAge[count]);
// printf("\n\n%s %d\n\n", userLastFirst[count], userAge[count]);
count++;
} while (count <= index);
//assigning values to pointer
for(int i = 0; i < index; i++){
namePtr[25][i] = &userLastFirst[25][i];
}
//does not print values of pointer
for(int i = 0; i < index; i++){
printf("value of ptr[%d] = %s\n", i, namePtr[i]);
}
bubbleSort(*namePtr, index);
displaySort(*namePtr, index);
return 0;
}
void bubbleSort(char *array[], int arrIndex)
{
for (unsigned int pass = 0; pass < arrIndex - 1; ++pass) {
for (int i = 0; i < arrIndex - 1; ++i) {
if (array[i] < array[i + 1]) {
int temp = *array[i];
*array[i] = *array[i + 1];
*array[i + 1] = temp;
}
}
}
}
void displaySort(char *array[], int arrIndex)
{
for(int i = 0; i < arrIndex; i++){
printf("%s",*array[i]);
}
}
Sorry it's a lot, but I've looked everywhere, and am not exactly sure what the problem is. I suspect it's how I pass pointers thru the functions, or how I'm using * and & but am not totally sure what I'm doing wrong. The for loop below the one that assigns the array values to the pointer is for testing. It's supposed to print out the values I had given it in the previous for loop, but it doesn't. It just prints junk data.
There are couple of issues here, and since I don't know what exactly you want your final code to look like, I am going to give a few examples of what is wrong and how you could possibly fix that.
char userLastFirst[25][index];
This should be
char userLastFirst[index][25];
You don't want 25 people with names up to index characters in them, but rather index people with names up to 25 characters int them.
char *namePtr[25][index];
should be
char namePtr[index][25];
Same as before + you don't need the * here. Since you decided to go with vla let's stick with it. You would use * and more specifically char ** if you went with malloc/calloc.
namePtr[25][i] = &userLastFirst[25][i];
rather than doing this awkward copying, try:
strcpy(namePtr[i], userLastFirst[i]);
it copies the entire string for you, rather than just a single character. You will need to #include the <string.h> library for that.
void bubbleSort(char *array[], int arrIndex)
The first bubble sort argument should be:
char array[][25] // the same in displaySort
if you want to do it without the hassle of malloc/calloc.
And also don't go with int as your temp type. Rather do char temp[25] and copy them around with strcpy.
And don't compare strings with <, it doesn't work in C. Use strcmp for that.
And that's it for doing it without malloc/calloc, here's an example code:
#include <stdio.h>
#include <string.h>
void bubbleSort(char array[][25], int size);
void displaySort(char array[][25], int size);
int main (void)
{
int num_of_people;
printf("Enter number of people (0 - 50): ");
scanf("%d", &num_of_people);
char original_array[num_of_people][25];
char copied_array[num_of_people][25];
for (int i = 0; i < num_of_people; i++) {
printf("Enter name %d (last, first): ", i);
scanf(" %[^\n]s", original_array[i]);
}
for(int i = 0; i < num_of_people; i++){
strcpy(copied_array[i], original_array[i]);
}
bubbleSort(copied_array, num_of_people);
displaySort(copied_array, num_of_people);
return 0;
}
void bubbleSort(char array[][25], int size)
{
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - 1 - i; ++j) {
if (strcmp(array[j], array[j + 1]) > 0) {
char temp[25];
strcpy(temp, array[j]);
strcpy(array[j], array[j + 1]);
strcpy(array[j + 1], temp);
}
}
}
}
void displaySort(char array[][25], int size)
{
for(int i = 0; i < size; i++){
printf("%s\n",array[i]);
}
}
and the program work like this:
Enter number of people (0 - 50): 4
Enter name 0 (last, first): Kowalski, Jan
Enter name 1 (last, first): Kowalska, Anna
Enter name 2 (last, first): Nowak, Miłosz
Enter name 3 (last, first): Amper, Ohm
Amper, Ohm
Kowalska, Anna
Kowalski, Jan
Nowak, Miłosz
I hope this is something you wanted to achieve.
I wrote a program in C to arrange the data in ascending order. When I compiled the code it showed no error but when it runs it shows a very different result than expected. However, when I ran the code in online C compiler it shows the correct result. I entered 5 different numbers 2 ,3 ,1 ,5 ,4.
Result in Linux: 0 1 2 3 4
Result in online compiler: 1 2 3 4 5
Why is this happening?
#include<stdio.h>
int * array(int x[],int l){
int i,j,k;
for(i=0;i<l;i++){
for(j=0;j<l;j++){
if(x[j]>x[j+1]){
k=x[j];
x[j]=x[j+1];
x[j+1]=k;
}
}
}
return x;
}
void main(){
int i,n;
int *b;
printf("enter n\n");
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
scanf("%d",&a[i]);
b=array(a,n);
printf("the ascending order is: ");
for(i=0;i<n;i++){
fflush(stdout);
printf("%d\t",b[i]);
}
}
Your code accesses memory beyond your array:
for(j=0;j<l;j++){
if (x[j] > x[j + 1]) {
x[j] = x[j + 1];
x[j + 1] = k;
In your case, when n = 5, you allocate the array for 5 elements with indices 0,1,2,3,4. The latest element of the array is x[4]. But when your code runs and j == l-1, you try to compare and even modify the element x[5]. In fact, your program should crash as it tries to access the "unallocated" memory. But probably because of aligning, the "x[5]" addresses the allocated memory. And, probably, x[5] = 0 on your computer, and your algorithm uses this element as a part of the sorting process. So your function array() returns the array of [0,1,2,3,4,5] and then your main() prints first five elements of this array.
That's why you've got sorted elements [0,1,2,3,4] instead of [1,2,3,4,5].
BTW, the bubble algorithm can be optimized to not touch already sorted elements.
Also, remember the array doesn't copy to pass into the function, the array always passes by its address, so it is not needed to "return" the modified array.
So, the final code can look like:
#include <stdio.h>
void array(int x[], int l)
{
int i, j, k;
for (i = l; i > 1; i--) {
for (j = 1; j < i; j++) {
if (x[j - 1] > x[j]) {
k = x[j - 1];
x[j - 1] = x[j];
x[j] = k;
}
}
}
}
void main()
{
int i, n;
printf("enter n\n");
scanf("%d", &n);
int a[n];
for (i = 0; i < n; i++)
scanf("%d",&a[i]);
array(a, n);
printf("the ascending order is:");
for (i = 0; i < n; i++) {
printf(" %d", a[i]);
fflush(stdout);
}
printf("\n");
}
Of course, there are lots of things to be done in this code, like human-readable variables, formatting, further optimization. But I hope you can do it yourself.
You may find it easier to write programs to get their input from the command line instead of prompting for it. Using C11, you can allocate an array using the length provided by argc, and process the argv array directly:
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] ) {
if( argc == 1 ) {
errx(EXIT_FAILURE, "syntax: %s values...", argv[0]);
}
int a[argc - 1];
for( int i=0; i < argc-1; i++ ) {
if( 1 != sscanf(argv[i + 1], "%d", a + i) ) {
errx(EXIT_FAILURE, "could not scan '%s'", argv[i + 1]);
}
}
array(a, sizeof(a)/sizeof(a[0]));
printf("the ascending order is:");
for (i = 0; i < n; i++) {
printf(" %d", a[i]);
fflush(stdout);
}
printf("\n");
}
I have assignment to write program that sort an array and search for a specific number, that part I've already done, My problem is how to Initialize the array in the size that the user sets with random values smaller than 500? I know how to do that with known size but not with unknown size?
example for input/output:
"Please enter the size of the array:
5"
This will help you.
int main(void)
{
int n,i;
n=rand()%500; // Get random value
int arr[n]; // Initialize the dynamic array
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
// Do your stuff
}
You can do something like this:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void printArray(int* p, int size)
{
for (int j = 0; j < size; ++ j) printf("%d ", p[j]);
printf("\n");
}
int main(void) {
srand(time(NULL)); // Start with a random seed based on time
int n = 0;
printf("Which array size do you need?\n");
if (scanf("%d", &n) != 1 || n < 1)
{
printf("Wrong input\n");
exit(0);
};
printf("Creating random array of size %d\n", n);
int* p = malloc(n * sizeof(*p)); // Reserve memory
for (int j = 0; j < n; ++j) p[j] = rand() % 500; // Generate random numbers
printArray(p, n); // Print the result
free(p); // free the allocated memory
return 0;
}
#include <stdio.h>
int main(){
void sorting(){
int a[4];
a[0]=1;
a[1]=6;
a[2]=15;
a[3]=3;
a[4]=19;
int size = 4;
int t =1;
if (size ==0) return; // ie if you reach to the end stop
int i;
for (i=0;i<size-1;i++){
if(a[i+1] >a[i]) { //if the +1 element is bigger than before it do the swap
int j;
j= a[i+1];
a[i+1]=a[i]; //swap
a[i] = j; //swap
}
}
sorting(*a,size - 1);//recursion
void print_int() {
int i; // Loop counter
for (i = 0; i < 4; i++) {
printf("%d\n", a[i]);
}}
}
It compiles ok but when I try to run the file nothing appears? My intentions were to create an array sort them then display them.
Also, the code where the recursion happened "sorting(*a,size - 1);//"
if I tried to replace *a with a[] an error will happen. Why is that?
the error is "error expected expression before ']' token"!
thank you.
int a[4];
But you access a[4]=19; index 4 that is out of bound. You can access highest index 3.
I think function void sorting() should be defined outside main .Nested functions are GNU extensions in GCC.
Your code has to many problems. Here is a working Array sort:
#include <stdio.h>
void bubble_sort(int *array, int length){
int i,j, k, temp;
for (i = 0 ; i < length-1; i++){
for (k = 0 ; k < length-i-1; k++){
if (array[k] > array[k+1]){
temp = array[k];
array[k] = array[k+1];
array[k+1] = temp;
}
}
}
printf("The sorted Array List:\n\n");
for ( j = 0 ; j < length ; j++ ){
printf("%d ", array[j]);
}
}
int main(void){
int array[] = {1,6,15,3,19};
int length = sizeof array / sizeof array[0];
bubble_sort(array, length);
printf("\n");
return 0;
}
You should read about functions declarations and definitions.
About arrays you should know that if you declare:
int array[4];
Your working array is from 0 to 3 and not from 0 to 4.
Take a look at the following:
int main(void){
int array[] = {1,6,15,3,19};
int size = 5;
int i;
for(i=0;i<size;i++){
printf("%d ",array[i]);
}
return 0;
}
I have size=5 and not size=4- like you tried. You should be careful about number of Array elements.
Aside from all the problems spotted by others, you must repeatedly execute the for loop until no more exchanges are made, which is the standad way of bubbling. As you use recursion, it is of course nonsense to declare the array to be sorted (and its size) inside the function called recursively.
I'm trying to sort elements in an array from smallest to largest that a user inputs along with the size. This is my code so far:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAXVALUES 20
void sort(int *A[], int n) {
int i, tmp, j;
for (i = 0; i <= (n - 2); i++) {
for (j = (i + 1); j <= (n - 1); j++) {
if (*A[i] > *A[j]) {
tmp = *A[i];
*A[i] = *A[j];
*A[j] = tmp;
}
}
}
return;
}
int main(int argc, char *argv[]) {
int n, A[MAXVALUES], i;
printf("Enter an array and no. of elements in array: ");
scanf("%d%d", &A[MAXVALUES], &n);
sort(A[MAXVALUES], n);
printf("Ordered array is: \n");
for (i = 0; i <= (n - 1); i++) {
printf(" %d", A[i]);
}
return 0;
}
The compiler compiles it without any errors but it stops working after I put in the inputs. I've yet to quite grasp the theory behind arrays and pointers so could someone tell me where in my code I'm going wrong?
scanf("%d%d", &A[MAXVALUES], &n); is the problem
That's not how you read an array.
First you read the n, after that inside a loop you read every element like
scanf("%d", &A[i]); where i is the index from 0 to n
EDIT:
scanf("%d", &n);
int i = 0;
for(i = 0; i < n; i++)
{
scanf("%d", &A[i]);
}
This is what you want.
You can't use scanf() to read in a whole array at once.
This:
scanf("%d%d", &A[MAXVALUES], &n);
Makes no sense; it passes scanf() the address of the element after the last one in A, causing undefined behavior. The sort() call is equally broken.
To read in multiple numbers, use a loop. Also, of course you must read the desired length first, before reading in the numbers themselves.
Firstly I'll tell you a couple of things about your sorting function. What you want, is take an array (which in C is representable by a pointer to the type of elements that are in that array, in your case int) and the array's size(int) (optionally you can take a sorting method as an argument as well, but for simplicity's sake let's consider you want to sort things from lowest to highest). What your function takes is a pointer to an array of integers and an integer (the second argument is very much correct, or in other words it's what we wanted), but the first is a little more tricky. While the sorting function can be wrote to function properly with this argument list, it is awkward and unnecessary. You should only pass either int A[], either int *A. So your function header would be:
void sort1(int *A, int n);
void sort2(int A[], int n);
If you do this however, you have to give up some dereferencing in the function body. In particular I am referring to
if (*A[i] > *A[j]) {
tmp = *A[i];
*A[i] = *A[j];
*A[j] = tmp;
} which should become
if (A[i] > A[j]) {
tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
You should check out the operators [] and *(dereference) precedence http://en.cppreference.com/w/c/language/operator_precedence
Now, to adapt to these changes (and further correct some code) your main would look like so:
int main(int argc, char *argv[])
{
int A[MAXVALUES], n;
do{
printf("n="); scanf("%d", &n);
}while(n < 0 || n > 20);
int i;
for(i = 0; i < n; ++i)
scanf("%d", &A[i]); //this will read your array from standard input
sort(A, n); //proper sort call
for(i = 0; i < n; ++i)
printf(" %d", A[i]);
printf("\n"); //add a newline to the output
return 0;
}