Reading digits into an array and sorting it - arrays

The task is as follows: to fill the file with numbers using the generation() function - an array cannot be used here. Then read the digits into the array by the read_file() function into the array and sort it using the quick sort method. Output to the console.
I wrote the code as I logically understood it myself, but a set of values is output to the console after sorting, as it is output in case of an error with a lack of memory, random numbers with cons sometimes. Maybe it's worth filling in a dynamic array? And why, if I know a specific number of elements?
Please help me figure it out.
#include <stdio.h>
#include <stdlib.h>
#define N 10
#define A -25000
#define B 25000
void generation();
void read_file();
void method_simple_sort();
int main(void) {
generation();
method_simple_sort();
return EXIT_SUCCESS;
}
void generation() {
FILE *file;
int i;
file = fopen("index.txt", "w");
srand(time(0));
for (int i = 0; i < N; i++) {
fprintf(file, "%d\n", A + rand() % (A - B + 1));
}
fclose(file);
}
void read_file() {
FILE *file;
int i, a[N] = { 0 };
file = fopen("index.txt", "r");
for (i = 0; i < N; i++) {
fscanf(file, "%d ", &a[i]);
}
fclose(file);
for (int i = 0; i < N; i++)
printf("%d ", a[i]);
}
void method_simple_sort() {
int a[N], i = 0, k = 0, ind_max = 0, temp = 0;
read_file();
for (k = 0; k < N - 1; k++) {
ind_max = k;
for (i = 1 + k; i < N; i++) {
if (a[i] > a[ind_max]) {
ind_max = i;
}
}
temp = a[k];
a[k] = a[ind_max];
a[ind_max] = temp;
}
// вывод результатов в файл
printf("\n\nПростого выбора: ");
for (int i = 0; i < N; i++) {
printf("%d ", a[i]);
}
printf("\n\n\n\n");
}

The function method_simple_sort defines a local array variable int a[N].
It then calls read_file(), but read_file() does not fill this local array variable defined in method_simple_sort.
Instead it fill its own local array variable (called also int a[N], but it's a different one than the one in method_simple_sort).
The bottom line is that when method_simple_sort attempts to sort a it sorts an array containing uninitialized data.
Hence the "garbaged" values that you see printed at the end.

The array used by the methods read_file and method_simple_sort aren't the same. When you declare anything inside a function it is translated at low level in space to allocate on the stack when you call the function.
You should transform read_file(void) into read_file(int *a) without declaring another instance of an array inside read_file.
By doing that you can pass a reference to the array declared inside method_simple_sort.
In particular:
void read_file(int *a) {
FILE *file;
int i;
/* a[N] = { 0 };*/
...
}
void method_simple_sort() {
int a[N], i = 0, k = 0, ind_max = 0, temp = 0;
read_file(a);
...
}

Related

Write a C function GetEvenNumber

For my studies, I have to write a C function GetEvenNumber:
parameters: array with n integers + array size;
returns tr array which contains even integers from td.
I don't know a priori the length of the array tr.
My below code returns errors:
#include <stdio.h> // define the header file
int *GetEvenNumber(int t[], int size)
{
int tr[];
int j = 0;
for (int i = 0; i < size; i++)
{
if (t[i] % 2 == 0)
{
printf("%d is even \n", t[i]);
tr[j] = t[i];
j++;
}
}
return tr;
}
int main() // define the main function
{
int *t; // = {4, 3, 1, 8, 6 };
int *tr = GetEvenNumber(t, 5);
for (int i = 0; i < 5; i++)
printf("%d \n", tr[i]);
}
I get error:
error: array size missing in 'tr'
int tr[];
warning: function returns address of local variable [-Wreturn-local-addr]
return tr;
How do I fix that? Thanks.
You mentioned that you could not use malloc() to dynamically create tr within GetEvenNumber() to address the two issues raised by your copmiler. This leaves making tr a global variable, or as here pass in the result array tr to be filled out:
#include <stdio.h>
#include <stdlib.h>
void GetEvenNumber(size_t size, const int *td, size_t *size2, int *tr) {
*size2 = 0;
for(size_t i=0; i<size; i++)
if(td[i] % 2 == 0)
tr[(*size2)++] = td[i];
}
int main() {
int td[] = {4, 3, 1, 8, 6 };
size_t size = sizeof(td) / sizeof(*td);
int tr[size];
size_t size2;
GetEvenNumber(size, td, &size2, tr);
for (size_t i=0; i < size2; i++)
printf("%d \n", tr[i]);
}
If the input array td contains uneven elements, then the result array tr have fewer valid elements than the input. I used size2 here to tell caller how many elements are valid in tr. Your code did not assign any values to, in this example, last 3 elements. You don't tell us what should happen with those last elements.
In modern C, if you specify the size before the array in the argument, then you can use the size in array specification which help document what is going on.
The error is due to
int tr[];
because you have to specify the size of your array during its creation.
I suggest trying to add a function that returns the number of even numbers in the array:
int getEvenNum(int t[], int lent){
int numEven = 0; // initialize counter to zero
for(int i = 0; i < lent; i++){ // for each element of the array
if ((t[i] % 2) == 0){ // if it's even,
numEven++; // add 1 to counter
}
}
return(numEven); // finaly returns the value of the counter
}
and then you replace the int tr[]; by int tr[getEvenNum(t, size)]; (maybe there's a ; after the getEvenNum(t, size) but I'm not sure)
Since the array tr can have AT MOST the same number of elements as the original integer array, it would be safe to declare the array with the same size as the array 't[]'.
I have made some changes to your code. Try the following:
#include<stdio.h> // define the header file
void GetEvenNumber(int *t, int* tr, int size, int *pCountEven)
{
int i, j=0;
for (i=0; i < size; i++)
{
if(t[i]%2==0)
{
printf("%d is even \n", t[i]);
tr[j++] = t[i];
}
}
*pCountEven = j;
}
int main() // define the main function
{
int t[] = {4, 3, 1, 8, 6 };
int tr[5], countEven = 0, i;
GetEvenNumber(t, tr, 5, &countEven);
for (i=0; i < countEven; i++)
printf("%d\n", tr[i]);
return 0;
}
Edit: As #chqrlie (who is an experienced coder) pointed out, we can simply return the length of the array instead of taking the address of a variable.
So alternatively, you can try this:
#include <stdio.h> // define the header file
int GetEvenNumber(int *t, int *tr, int size) {
int i, j = 0;
for (i = 0; i < size; i++) {
if (t[i] % 2 == 0) {
printf("%d is even \n", t[i]);
tr[j++] = t[i];
}
}
return j;
}
int main() // define the main function
{
int t[] = { 4, 3, 1, 8, 6 };
int tr[5], countEven = 0, i;
countEven = GetEvenNumber(t, tr, 5);
for (i = 0; i < countEven; i++)
printf("%d\n", tr[i]);
return 0;
}

C how to return arrays from multiple functions?

I am trying to make a program that first creates an array in another function, returns it and then calls another function that shuffles the contents of the array and returns it. However I am struggling to do this in C since I do not quite understand the array pointer system that has to be used here.
So far my code doesnt return the values 1-20 from makeArray() but instead returns an array full of 0s and I have a feeling it has to do with the c's array pointer system.
Any help would greatly be appreciated! Thank you in advance
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int arrShuffle();
int arrShuffle(int * arr) {
int arr[21];
// shuffle array
for(int j=0; j<20; j++) {
int randInd = (rand() % 20) + 1;
int temp = arr[j];
arr[j] = arr[randInd];
arr[randInd] = temp;
}
return arr;
}
int makeArray() {
int arr[21];
// make array of 1-20
for(int i=0; i < 20; i++) {
arr[i] = i + 1;
}
return arr;
}
void main() {
int *orgArr;
int *modArr;
srand(time(NULL));
orgArr = makeArray();
for(int i=0; i < 20; i++) {
printf("OrgArr: %d\n", orgArr);
}
modArr = arrShuffle(orgArr);
}
You cannot use variables with automatic storage (aka local ones). You must allocate the array so the memory remains valid after the function ends:
int* makeArray() {
int *arr = calloc(21, sizeof *a);
// make array of 1-20
for(int i=0; i < 20; i++) {
arr[i] = i + 1;
}
return arr;
}
Remember to release the array when it is no longer used:
int main() {
int *orgArr;
...
orgArr = makeArray();
...
free(orgArr);
}
As tstanisl pointed out in their answer, a possible solution is to use dynamic memory allocation. My answer, instead, will give you yet another solution: using an array passed by the caller.
NOTE: both solutions are valid and their usefulness depends on the specific needs of your program. There's no "right" universal solution.
void makeArray(int arr[], size_t len) {
for (size_t i = 0; i < len; i += 1) {
arr[i] = (int) (i + 1);
}
}
void cloneAndModifyArray(const int orig[], int new[], size_t len) {
for (size_t i = 0; i < len; i += 1) {
new[i] = orig[i] * 2; // or some other modification
}
}
And you use it like this:
#define ARR_LEN (100)
int main(void) {
int arr[ARR_LEN];
makeArray(arr, ARR_LEN);
int modified_arr[ARR_LEN];
cloneAndModifyArray(arr, modified_arr, ARR_LEN);
return 0;
}

2D arrays using arrays of pointers or pointers to pointers in C?

I'm writing a C for which I need to create a 2D array. I've found a solution to my problem using double pointers (pointers to pointers) in the following way:
#include <stdio.h>
#include <stdlib.h>
int d = 3;
#define DIM_MAX 9
void changeArray(int d, int *array[d]);
int main()
{
//alocate array of 'd' colummns and 'd' row using malloc using array of pointers
int **array = malloc(d*sizeof(int *));
for(int count = 0; count < d; count++)
{
array[count] = malloc(d*sizeof(int *));
}
/* Call changeArray function */
changeArray(d, array);
for(int i = 0; i < d; i++)
{
for(int j = 0; j < d; j++)
{
printf("%d ", array[i][j]);
}
printf("\n");
}
for(int count = 0; count < d; count++)
{
free(array[count]);
}
return 0;
}
void changeArray(int n, int *array[d])
{
for(int i =0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
array[i][j] = i*j;
}
}
return;
}
The code above works pretty well (it seems), but I've read in the web that using pointer to pointer is not the correct way to create 2D arrays. So I've come up with the following code, which also works:
#include <stdio.h>
#include <stdlib.h>
#define DIM_MAX 9
int d = 3;
void changeArray(int d, int *array[d]);
int main()
{
//alocate array of 'd' colummns and 'd' row using malloc using array of pointers
int *array[DIM_MAX] = {0};
for(int count = 0; count < d; count++)
{
array[count] = (int *)malloc(d*sizeof(int *));
}
/* Call changeArray function */
changeArray(d, array);
for(int i = 0; i < d; i++)
{
for(int j = 0; j < d; j++)
{
printf("%d ", array[i][j]);
}
printf("\n");
}
for(int count = 0; count < d; count++)
{
free(array[count]);
}
return 0;
}
void changeArray(int n, int *array[d])
{
for(int i =0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
array[i][j] = i*j;
}
}
return;
}
What is the difference in using any of the two ways above to write this code?
[Not an answer, but an alternative approach to achieve the desired result, namely defining a user-defined 2D array.]
Assuming the compiler in use supports VLAs you could do this:
#include <stddef.h> /* for size_t */
void init_a(size_t x, size_t y, int a[x][y]); /* Order matters here!
1st give the dimensions, then the array. */
{
for (size_t i = 0; i < x; ++i)
{
for (size_t j = 0; j < y; ++j)
{
a[i][j] = (int) (i * j); /* or whatever values you need ... */
}
}
}
int main(void)
{
size_t x, y;
/* Read in x and y from where ever ... */
{
int a[x][y]; /* Define array of user specified size. */
init_a(x, y, a); /* "Initialise" the array's elements. */
...
}
}
It is actually pretty simple. All you have to do is this:
int i[][];
You are overthinking it. Same as a normal array, but has two indexes.
Let's say you want to create a "table" of 4 x 4. You will need to malloc space for 4 pointers, first. Each of those index points will contain a pointer which references the location in memory where your [sub] array begins (in this case, let's say the first pointer points to the location in memory where your first of four arrays is). Now this array needs to be malloc for 4 "spaces" (in this case, let's assume of type INT). (so array[0] = the first array) If you wanted to set the values 1, 2, 3, 4 within that array, you'd be specifying array[0][0], array[0][1], array[0][2], array[0][3]. This would then be repeated for the other 3 arrays that create this table.
Hope this helps!

define a two-dimensional global array which its size have to be scanned from a file

I want to define a two dimensional array as a global variable:
int visited[nbVertices][nbVertices];
but the problem that I have to scan the "nbVertices" from a file. is there anyway to fix this problem ?
I think it may be fixed by using pointers, but I don't know how to do it.
So, while we're at it: you don't need the array to be global. Hence, you can just use variable-length arrays and pass the array to all the functions that need it:
void printArray(int n, int k, int arr[n][k])
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < k; j++) {
printf("%6d", arr[i][j]);
}
printf("\n");
}
}
int main()
{
// get user input in the format "n" <space> "k"
char *end;
char buf[LINE_MAX];
if (!fgets(buf, sizeof buf, stdin))
return -1;
// create array, fill it with random stuff
int n = strtol(buf, &end, 10);
int k = strtol(end, NULL, 10);
int a[n][k];
for (int i = 0; i < n; i++) {
for (int j = 0; j < k; j++) {
a[i][j] = random();
}
}
// print it
printArray(n, k, a);
return 0;
}
Use malloc.
Your code might look something like this:
// somewhere in file, global
int **visited;
// somewhere in your code, when you read nbVertices
visited = malloc(sizeof(int*) * nbVertices);
for(size_t i = 0; i < nbVertices; i++)
visited[i] = malloc(sizeof(int) * nbVertices);
there shouldn't be any major differences using visited

How to change every second elements of array in c using for loop?

I'm using a for loop to create an 100 element array of char. I on the first run, I want to change all of its values to 1, the second run, I want its every second values to 0
char array[ 100 ] = { 0 };
int toggle_swith(char a[]) {
for (i = 0; i < 100; i++) {
printf(array[i] + "1 ");
}
}
int main( void ) {
int i;
for (i = 0; i < 100; i++) {
printf(array[i] + "0 ");
toggle_switch();
}
}
You need a function which initializes the array:
void InitializeArray(char Array[], int Length) {
int i;
for (i = 0; i < Length; i++) {
Array[i] = '1';
}
}
You need a function which changes every 2nd element:
void ChangeEverySecondElement(char Array[], int Length) {
int i;
for (i = 1; i < Length; i += 2) {
Array[i] = '0';
}
}
You need a function to print the array :
void PrintArray(char Array[], int Length) {
int i;
for (i = 0; i < Length; i++) {
putchar(Array[i]);
putchar(' ');
}
putchar('\n');
}
Then you need to put them together
int main() {
char Array[100];
InitializeArray(Array, 100);
PrintArray(Array, 100);
ChangeEverySecondElement(Array, 100);
PrintArray(Array, 100);
return 0;
}
If you are trying to learn C, I recommend the book I learned it from, C by Example written by Greg Perry.
you can do it all at once
for (i=0; i<100; i++) array[i]=(i%2)+'0';
a typical attempt at optimization could look like:
#define BUFSZ 100
int main(){
char buf[BUFSZ];
int *bp=(int *)&buf, i=(BUFSZ/sizeof(int));
/* handle aligned words 4 bytes at a time */
while (i) bp[--i]='0101'; /* for 64 bit use '0101'|('0101' <<32) */
/* handle unaligned bytes */
for(i=(BUFSZ/sizeof(int))*sizeof(int);i<BUFSZ;i++)buf[i]=1-i%2+'0';
write(1,buf,BUFSZ);
}
Initially you want to make all your array elements as 1
You can use memset
memset(array,1,100)
This will clear all elements. But if you insist on using a loop then,
#define ARRAY_SIZE 100
char array[ARRAY_SIZE] = {0};
for(int count = 0; count < ARRAY_SIZE; count++)
{
array[count] = 1;
//If you want to print it, use:
printf("%d",array[count]; // You can also use %c
}
To make alternate element 0,
for(int count = 0; count < ARRAY_SIZE; (count = count + 2)) //Count + 2 will hop every alternate element
{
array[count] = 0;
}
Again, You can add printf() if you want.
Print statement should look something like this.
printf("%c0",array[i]);
I suggest you look up Beginner C tutorial for more info.

Resources