C: generate array with random numbers in range (allwowing duplicates) - c

I want to write a C function that gets: a seed, int n (the number of random ints to generate), and upper limit (the max allowed number).
I came so far as to have somthing like this:
// I need a function definition here
// I forgot how to allocate the int array ... somehting with 'sizeof'?
srand(time(NULL)); //seed for rand
for(i = 0; i < length; i++)
array[i] = rand()%upperLimit;
return array;
Then I probably need those header files:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

You need #include <time.h> for the time function.
This is simple program matching your description with comments in the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int *
alocate (unsigned int n)
{
return malloc (n * sizeof (int)); // allocate memory block for n numbers and return int pointer to it
}
int *
generate_block_with_random_numbers (unsigned int n, int upper_limit)
{
// function `int *generate_block_with_random_numbers(unsigned int n, int upper_limit)`
// gets a positive integer n as an argument
// reserves the n block of int variables in memory
// fills this block with random values
// returns a pointer to the beginning of the reserved block.
srand (time (NULL)); // seed generator
int *array = alocate (n); // note: array pointer always points to the beginning of the allocated memory
for (int i = 0; i < n; i++)
{
// you can index the array moving to its next element via [i]
array[i] = rand () % (upper_limit+1); //
}
return array;
}
int
main ()
{
unsigned int n = 5;
unsigned int upperL = 5;
int *block = generate_block_with_random_numbers (n, upperL);
// Display the data contained in the returned block:
for (int i = 0; i < n; i++)
{
printf ("%d\n", block[i]); // print it
}
return 0;
}
Output:
5
0
2
3
3

Related

how can i return an array from a function

How can I return an array from a function, I am trying to perform (3*3)*(3*1) matrix multiplication using this translation function and how can i get an array out of it.
#include <stdio.h>
#include <math.h>
int* translation(int x, int y, int tx, int ty) {
static int res[3][1] = {0}, xy[3][1] = {{x},{y},{1}};
int tm[3][3] = {{1,0, tx}, {0,1,ty}, {0,0,1}};
for (int i = 0; i<3; i++) {
for (int j = 0; j<3; j++) {
res[i][0] += tm[i][j]*xy[j][0];
}
}
return res;
}
int main()
{
int *arr[3][1];
arr = translation(5, 5);
printf("%d %d %d", arr[0][0], arr[0][1], arr[0][2]);
return 0;
}
"How can I return an array from a function"
You can't.
The language has no such concept.
You'll have to return something including the length to give the user of the function the information. In C the idiomatic approach is to supply a pointer to the function and to get a value (via that pointer) in return:
size_t no_idea;
void function(void *data, &no_idea);
As a user of this function you'd have to read no_idea before judging.
you question is missing a lot of information like what you want to do with your code, the variable named xy isn't defined anywhere in your code, and so on...
but for clarification, if your result matrix is of unknown size, you can wrap your array into a struct, if you don't know what is the struct, you can refer to this small tutorial about struct in c, so your struct maybe look like something like this:
typedef struct Array_t{
size_t arrSize_x;
size_t arrSize_y;
int **arr;
}Array_t;
where arr is your matrix of unknown size which will be created dynamically and arrSize_x, arrSize_y are your matrix dimensions.
so in order to create a matrix of unknow size at compile time , you should create it dynamically in the heap memory using functions like calloc or malloc, although in C99, it allowed created arrays statically of unknown size during compile time but it's not the case with struct as the struct once defined, your array is created and you cannot do something like this:
typedef struct Array_t{
size_t arrSize_x;
size_t arrSize_y;
int arr[arrSize_x][arrSize_y];
}Array_t;
but if the size of the array is known you can do something like this:
typedef struct Array_t{
int arr[3][1];
}Array_t;
to create a dynamic array, you will find in the next example code something like this:
// rows are stored in heap memory and initiated with zeros
res.arr = (int**) calloc(res.arrSize_x, sizeof(int));
// columns are also stored in heap memory and initiated with zeros
for (int i = 0; i < res.arrSize_x; ++i) {
res.arr[i] = (int *) calloc(res.arrSize_y, sizeof(int));
}
where res.arr is a pointer pointing to an array of pointers and the next diagram may simplify my explanation where the next graph expresses the created matrix in heap memory for arr of size 3 x 1:
while if the size is known, so the explanation diagram may look like this:
and when you return, you can either return by value or by reference, but if you are going to return a struct by reference then you should declare it as static.
so you can do something like this (for clarification purposes, size of matrix is unknown):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct Array_t{
size_t arrSize_x;
size_t arrSize_y;
int **arr;
}Array_t;
Array_t translation(int x, int y, int tx, int ty) {
// create a struct holding the array
Array_t res;
res.arrSize_x = 3;
res.arrSize_y = 1;
// rows are stored in heap memory and initiated with zeros
res.arr = (int**) calloc(res.arrSize_x, sizeof(int));
// columns are also stored in heap memory and initiated with zeros
for (int i = 0; i < res.arrSize_x; ++i) {
res.arr[i] = (int *) calloc(res.arrSize_y, sizeof(int));
}
res.arr[0][0] = 1;
res.arr[1][0] = 2;
res.arr[2][0] = 3;
return res;
}
int main()
{
Array_t array;
// 1, 2, 3, 4 are dummy parameters
array = translation(1, 2, 3, 4);
printf("elements are :\n");
for (int i = 0; i < array.arrSize_x; ++i) {
for (int j = 0; j < array.arrSize_y; ++j) {
printf("%d\t", array.arr[i][j]);
}
printf("\n");
}
return 0;
}
and this is the output:
elements are :
1
2
3
but if size of matrix is known then you can do something like this (for clarification purposes, size of matrix is known):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct Array_t{
int arr[3][1];
}Array_t;
Array_t translation(int x, int y, int tx, int ty) {
// create a struct holding the array
Array_t res;
res.arr[0][0] = 1;
res.arr[1][0] = 2;
res.arr[2][0] = 3;
return res;
}
int main()
{
Array_t array;
// 1, 2, 3, 4 are dummy parameters
array = translation(1, 2, 3, 4);
printf("elements are :\n");
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 1; ++j) {
printf("%d\t", array.arr[i][j]);
}
printf("\n");
}
return 0;
}
and this is the ouput:
elements are :
1
2
3

Unexpected output for this following code [duplicate]

This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 2 years ago.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int a1(int *a)
{
int middleItem;
int midIndex;
if (a == NULL || sizeof(a) % 2 == 0)
return 0;
midIndex = sizeof(a) / 2 ;
middleItem = a[midIndex];
for (int i=0; i<sizeof(a); i++)
{
if (i != midIndex && middleItem >= a[i])
return 0;
}
return 1;
}
int main()
{
int a[] = {9};
for (int i=0; i<sizeof(a); i++)
{
a1(a[i]);
}
return 0;
}
An array with an odd number of elements is said to be centered if all elements (except the middle one) are strictly greater than the value of the middle element. Note that only arrays with an odd number of elements have a middle element.
output:
returns 1 if it is a centered array, otherwise, it returns 0.
sizeof(a) is number of bytes in a and it is not necessarily same as the number of elements in the array a.
It is even worse in the function a1: now sizeof(a) is the size of pointer and you cannot get number of elements from that, so you have to pass it separately.
Passing a[i] as the first argument of a1 is wrong because a[i] is an integer while a pointer is required for the argument.
You will want to output what the function returned.
Try this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int a1(int *a, int size)
{
int middleItem;
int midIndex;
if (a == NULL || size % 2 == 0)
return 0;
midIndex = size / 2 ;
middleItem = a[midIndex];
for (int i=0; i<size; i++)
{
if (i != midIndex && middleItem >= a[i])
return 0;
}
return 1;
}
int main()
{
int a[] = {9};
int size = sizeof(a) / sizeof(*a);
printf("%d\n", a1(a, size));
return 0;
}

My pointer in an array doesn't work as it supposed to

I wanted to create a function, that would accept an 1:array_of_int, and 2:size_of_array, then return sum of the 3 biggest int. Code follows:
#include <stdio.h>
#include <stdlib.h>
int max_3(int arr[], int asize)
{
int max_arr[3];
int max =0;
int sum = 0;
int* pi;
for(int j=0; j<3; j++)
{
for(int i =0; i<asize;i++)
{
if(arr[i] > max)
{
max = arr[i];
pi = (arr + i); // to know the address of the max int of 'i' cycle
}
}
max_arr[j] = max;
*pi = 0; // make the max int = 0 so that the next 'i' cycle doesnt have the previous max in it
//(so it can look for another max value - the second one)
}
for(int i=0; i<3; i++)
sum += max_arr[i];
return sum;
}
int main (int argc, char** argv) {
int arr[6] = {1,5,9,12,16,14};
printf("%i\n",max_3(arr, 6));
return (EXIT_SUCCESS);
}
The pointer pi doesn't make the value of the current max value 0, and the next cycle in for (int i..) make the biggest one again as from the previous. So instead of returning max val1 + val2 + val3, it returned 3 * val1 (the biggest one) -- in my particular example - it printed out 48 instead of 42 (12 + 16 + 14) - as it should. But how when I make the value of address (which my pointer point to) as 0? I do not understand that properly.
Your if statement:
if (arr[i] > max)
isn't going to be entered after the first time you find max (i.e. when j > 0).
You need to zero it after:
max_arr[j] = max;
max = 0;
The following proposed code:
performs the desired functionality
is very straight forward in its' algorithm
incorporates a bubble sort for selecting the top three entries in the array
eliminates the 'magic' number 6
modifies the second parameter to type size_t as that is the type returned by sizeof()
the expression: sizeof(arr)/sizeof(arr[0]) lets compiler calculate number of entries in array
the statement: int arr[] = {1,5,9,12,16,14}; lets compiler allocate room for array
avoids modifying the original array, when sorting
and now, the proposed code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // memcpy()
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
void bubbleSort(int arr[], size_t n)
{
size_t i;
size_t j;
for (i = 0; i < n-1; i++)
{
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
swap(&arr[j], &arr[j+1]);
}
}
}
}
int max_3(int arr[], size_t asize)
{
int localArray[ asize ];
memcpy( localArray, arr, asize*sizeof( int ) );
// sort array
bubbleSort( localArray, asize );
// calculate sum of max 3 entries
int sum = localArray[asize-1] + localArray[asize-2] + localArray[asize-3];
return sum;
}
int main ( void )
{
int arr[] = {1,5,9,12,16,14};
printf( "%i\n", max_3( arr, sizeof(arr)/sizeof(arr[0])) );
return (EXIT_SUCCESS);
}
a run of the proposed code results in:
42
After the very first iteration of the outer loop (the loop for(int j=0; j<3; j++)) the value of max and pi will never change.
In that first iteration of the outer loop, you will find that the fifth element in the array will be largest, max will be equal to 16 and pi will point to that element. You set max_arr[0] to 16 and set *pi to zero. Then the outer loop starts over with max still being equal to 16. And now there will be no value in the array that will be equal or larger than that. So you set max_arr[1] to 16 as well, and set *pi (where pi is still pointing to the fifth element) to zero again. And the same thing the next iteration.
The natural solution would be to define max and pi inside the outer loop:
for(int j=0; j<3; j++)
{
// The variables will be redefined and reinitialized each iteration of the loop
int max = 0;
int *pi;
for(int i =0; i<asize;i++)
{
if(arr[i] > max)
{
max = arr[i];
pi = (arr + i); // to know the address of the max int of 'i' cycle
}
}
max_arr[j] = max;
*pi = 0; // make the max int = 0 so that the next 'i' cycle doesnt have the previous max in it
//(so it can look for another max value - the second one)
}
There are a few other problems with the code, like for example the possibility that pi will never be initialized. I leave it as an exercise to the reader to figure when that will happen and how to solve it.

C - dynamic arrays of structures

I have a problem with a rather big piece of code. Knowing myself, it's some kind of a silly mistake, or, more likely, lack of understanding of pointers. I really need some help, so if someone could look at it I would be so grateful! I'm going to explain it now.
It's a program for my programming class. The teacher gave us a number (N) and a letter (X) in a txt file, and wants us to create a structure with three fields(int, char and float), and then four functions:
function #1 takes the number N as an argument and dynamically allocates memory for an array of pointers to N structures. then it assigns values to the fields in the structures - int and char are set to random values, and the float field is set to the number of the structure. the function returns the address of the array.
function #2 takes the size of the created array (the number of pointers in it) and a pointer to the array as arguments and deletes the array, freeing the memory.
function #3 takes the size of the created array and a pointer to the array as arguments, and then sorts the structures based on the int field, using bubble sort
function #4 searches through the structures and counts how many times the letter (X) is repeated in the char fields of the structures.
Here's the code with comments and errors. Please, can someone explain what am I doing wrong? To be honest I'm almost out of time, but I'm willing to stay up all night to understand and fix this.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>
struct Foo {
int fieldint;
char fieldchar;
float fieldfloat;
};
Foo *initialize(int N);
int sort(int N, Foo *tablica);
int count(int N, Foo *tablica, char*X);
int deleting(int N, Foo **tablica);
int main () {
//this reads the number N and the letter to find from the .txt file:
FILE *file = fopen("inlab01.txt", "r");
int number;
char letter[1];
if (file == NULL) {
printf("Error opening file");
exit(-1);
}
while (fscanf(file, "%d%s", &number, letter) != EOF);
fclose(file);
//creating the array
//again, it's supposed to be an array of pointers to N structures:
Foo *arr[number];
*arr = initialize(number);
//sorting:
sort(number, *arr); //the program crashes at this function
//counting how many times the given letter appears:
//count(number, *arr, letter);
//we're supposed to print the first 20 of the structures
//this loop prints one structure and then the program crashes
for(int i=0;i<20;i++) {
printf("Structure %d:\nfield int:%d\nfield char:%c\nfield float:\f\n\n", i+1, arr[i]->fieldint, arr[i]->fieldchar, arr[i]->fieldfloat);
}
//deleting:
deleting(number, arr);
getch();
return 0;
}
Foo *initialize(int N) {
Foo **array;
array = (Foo **)malloc(sizeof(Foo) * N);
srand( time( NULL ) );
for(int i=0; i<N; i++) {
array[i] = (Foo*)malloc(sizeof(Foo));
array[i] -> fieldint = rand(); //random number
array[i] -> fieldchar = ( char )( rand() % 24 ) + 65; //random letter
array[i] -> fieldfloat=i;
}
return *array;
}
int sort(int N, Foo *array) {
int temp;
for (int i=0;i<N;i++){
for (int j=N-1;j>=j;j--) {
if(array[j].fieldint < array[j-1].fieldint) {
temp = array[j-1].fieldint;
array[j-1].fieldint = array[j].fieldint;
array[j].fieldint = temp;
}
}
}
return 0;
}
int count(int N, Foo *array, char*X){
int counter = 0;
for(int i=0;i<N;i++) {
if (array[i].fieldchar == 'X') {
counter = counter+1;
}
}
return counter;
}
int deleting(int N, Foo **array) {
for (int i=0;i<N;i++) {
free(array[i]);
}
free(array);
return 0;
}
The whole thing compiles, but then the program crashes instead of doing anything, really.
Please help.
struct Foo
{
int fieldint;
char fieldchar;
float fieldfloat;
};
Foo **array;
array = (Foo **)malloc(sizeof(Foo) * N);
You are compiling this code in C++. You want to use a C compiler, and you have to change the code to the following:
struct Foo **array;
You would use struct Foo everywhere, and you don't need that cast. Or declare the structure with typedef
Secondly, Foo **array is for allocating a 2-dimensional array. The way you are allocating 2-D array is wrong. Besides, you only need a 1-dimensional array Foo arr[number]
for (int j=N-1;j>=j;j--)
Note you have an error in your sort function (j >= j) is always true. Fix the sort function, avoid allocating a 2-D array and you are done.
int sort(int N, struct Foo *array)
{
int temp, i, j;
for (i = 0; i< N; i++) {
for (j = i + 1; j < N; j++) {
if (array[i].fieldint > array[j].fieldint) {
temp = array[i].fieldint;
array[i].fieldint = array[j].fieldint;
array[j].fieldint = temp;
}
}
}
return 0;
}
int main()
{
srand((unsigned)time(NULL));
int number = 3;
struct Foo arr[number];
int i;
for (i = 0; i < number; i++) {
arr[i].fieldint = rand(); //random number
arr[i].fieldchar = 'A' + (char)(rand() % 26); //random letter
arr[i].fieldfloat = (float)i;
}
sort(number, arr);
for (i = 0; i < number; i++)
printf("Structure %d:\nfield int:%d\nfield char:%c\nfield float:%f\n\n",
i + 1, arr[i].fieldint, arr[i].fieldchar, arr[i].fieldfloat);
getch();
return 0;
}
Note that your sort function swaps fieldint but Foo has other members, you probably want to swap all members if your goal is to swap the object.

C segmentation fault with very large array at specific indices

I have a program that deals with very large arrays, and when I'm trying to populate the array with random values, it always segfaults at a specific index. On Mac OSX 10.10 running XCode, it segfaults at index 1000448, and on GCC targeting LLVM version 6.1.0 it faults at 1001472.
Here is my code
#include <stdlib.h>
#include <stdio.h>
#define WIDTH 1000
#define HEIGHT 1000
/////////////////////////////////////////////////////////
// Program main
/////////////////////////////////////////////////////////
int main(int argc, char** argv) {
// set seed for rand()
srand(2006);
// 1. allocate host memory for matrices A and B
unsigned int length = WIDTH * HEIGHT;
unsigned int size = sizeof(int) * length;
printf("%i", size);
int* matrixA = (int*) malloc(size);
for(int i = 0; i < size; i++) {
printf("%i\n", i);
matrixA[i] = rand() % 10;
}
free(matrixA);
}
Why is this segfaulting? I checked the size allocated to matrixA, and it appears to be the correct size (4,000,000)
the following code
compiles cleanly
performs the appropriate error checking
#include <stdlib.h>
#include <stdio.h>
#define WIDTH (1000)
#define HEIGHT (1000)
/////////////////////////////////////////////////////////
// Program main
/////////////////////////////////////////////////////////
int main( void )
{
// set seed for rand()
srand(2006);
// 1. allocate host memory for matrices A and B
unsigned int length = WIDTH * HEIGHT;
unsigned int size = sizeof(int) * length;
printf("%u\n", size);
int* matrixA = NULL;
if( NULL == (matrixA = malloc(size) ) )
{// then malloc failed
perror( "malloc failed");
exit( EXIT_FAILURE );
}
// implied else, malloc successful
for(unsigned i = 0; i < length; i++)
{
printf("%i\n", i);
matrixA[i] = rand() % 10;
}
free(matrixA);
} // end function: main
Oops, I just realized what the problem was. I'm looping from 0 to size, instead of length. If someone could tell my why those particular values, though, it would be great

Resources