I have trouble getting my dynamic int array to work properly. I have tried some examples but still can not get it to work. I think I am doing a minor pointer problem but I cannot figure out what. I want to have a dynamic int array and then from another function add numbers to this array. I have gotten the counter to work.
I have tried putting * at different places and trying my way but I am at this point lacking the knowledge to actually know where the * should be. I know some basics about & and * but apparently not enough
static void counterFunction(int* pointerToArray[], int* count)
{
while (*count < 10) {
*(*pointerToArray + *count) = *count;
*count = *count + 1;
}
}
static int* writeSortedToArray(void)
{
// I need to store 1000 numbers at this point
int* dynamicArray = malloc(1000 * sizeof(int));
int counter = 0;
counterFunction(&dynamicArray, &counter);
return 0;
}
The counter works properly, the dynamic array does not work at all. It only store a 0 according to my debugger (xcode)
To add to the other answers, I'd suggest a more generic approach and encapsulation of the management logic:
#include <assert.h> // assert()
#include <stddef.h> // size_t
#include <stdbool.h> // bool, true, false
#include <stdlib.h> // malloc(), calloc(), free(), EXIT_FAILURE, EXIT_SUCCESS
#include <stdio.h> // fputs(), printf(), putchar()
typedef int value_type;
char const *conversion_specifier = "%d"
size_t const initial_capacity = 10
size_t growth_factor = 2
typedef struct dynarray_tag {
size_t size;
size_t capacity;
value_type *data;
} dynarray_t;
dynarray_t dynarray_create(void)
{
dynarray_t new_dynarray = { 0, 0, NULL };
return new_dynarray;
}
dynarray_t dynarray_create_reserve(size_t capacity)
{
dynarray_t new_dynarray = { 0, capacity, NULL };
new_dynarray.data = malloc(capacity * sizeof *new_dynarray.data);
return new_dynarray;
}
dynarray_t dynarray_create_size(size_t size)
{
dynarray_t new_dynarray = { size, size, NULL };
new_dynarray.data = calloc(size, sizeof *new_dynarray.data);
return new_dynarray;
}
bool dynarray_is_valid(dynarray_t const *dynarray)
{
if (!dynarray)
return false;
if (!dynarray->size && !dynarray->capacity && !dynarray->data)
return true;
if (dynarray->size > dynarray->capacity)
return false;
if (dynarray->capacity && dynarray->data)
return true;
return false;
}
size_t dynarray_get_size(dynarray_t const *dynarray)
{
assert(dynarray_is_valid(dynarray));
return dynarray->size;
}
size_t dynarray_get_capacity(dynarray_t const *dynarray)
{
assert(dynarray_is_valid(dynarray));
return dynarray->capacity;
}
value_type* dynarray_at(dynarray_t *dynarray, size_t position)
{
assert(dynarray_is_valid(dynarray) && dynarray->size && position < dynarray->size);
return &dynarray->data[position];
}
value_type* dynarray_front(dynarray_t *dynarray)
{
assert(dynarray_is_valid(dynarray));
return dynarray_at(dynarray, 0);
}
value_type* dynarray_back(dynarray_t *dynarray)
{
assert(dynarray_is_valid(dynarray));
return dynarray_at(dynarray, dynarray->size - 1);
}
bool dynarray_reserve(dynarray_t *dynarray, size_t new_capacity)
{
assert(dynarray_is_valid(dynarray));
if (new_capacity <= dynarray->capacity)
return true;
if (new_capacity < dynarray->size)
return false;
value_type *new_data = realloc(dynarray->data, new_capacity * sizeof *new_data);
if (!new_data)
return false;
dynarray->data = new_data;
dynarray->capacity = new_capacity;
return true;
}
bool dynarray_resize(dynarray_t *dynarray, size_t new_size)
{
assert(dynarray_is_valid(dynarray));
if (new_size <= dynarray->capacity)
return true;
value_type *new_data = realloc(dynarray->data, new_size * sizeof *new_data);
if (!new_data)
return false;
dynarray->data = new_data;
dynarray->size = new_size;
dynarray->capacity = new_size;
return true;
}
bool dynarray_insert(dynarray_t *dynarray, size_t position, value_type value)
{
assert(dynarray_is_valid(dynarray));
if (dynarray->size + 1 > dynarray->capacity) {
size_t new_capacity = dynarray->capacity ? dynarray->capacity * growth_factor : initial_capacity;
if (!dynarray_reserve(dynarray, new_capacity))
return false;
}
for (size_t i = dynarray->size; i > position; --i)
dynarray->data[i] = dynarray->data[i - 1];
dynarray->data[position] = value;
dynarray->size++;
return true;
}
bool dynarray_push_front(dynarray_t *dynarray, value_type value)
{
assert(dynarray_is_valid(dynarray));
return dynarray_insert(dynarray, 0, value);
}
bool dynarray_push_back(dynarray_t *dynarray, value_type value)
{
assert(dynarray_is_valid(dynarray));
return dynarray_insert(dynarray, dynarray->size, value);
}
bool dynarray_insert_sorted(dynarray_t *dynarray, value_type value)
{
assert(dynarray_is_valid(dynarray));
if (!dynarray_get_size(dynarray) || value < *dynarray_front(dynarray))
return dynarray_push_front(dynarray, value);
if (value > *dynarray_back(dynarray))
return dynarray_push_back(dynarray, value);
size_t insert_pos = 0;
for (; insert_pos < dynarray->size && value > dynarray->data[insert_pos]; ++insert_pos);
return dynarray_insert(dynarray, insert_pos, value);
}
void dynarray_print(dynarray_t const *dynarray)
{
assert(dynarray_is_valid(dynarray));
for (size_t i = 0; i < dynarray->size; ++i) {
printf(conversion_specifier, dynarray->data[i]);
if (i + 1 < dynarray->size)
printf(", ");
}
}
void dynarray_sort(dynarray_t *dynarray) // insertion sort
{
assert(dynarray_is_valid(dynarray));
for (size_t i = 1; i < dynarray->size; i++) {
value_type key = dynarray->data[i];
size_t k = i - 1;
for (; k >= 0 && dynarray->data[k] > key; --k)
dynarray->data[k + 1] = dynarray->data[k];
dynarray->data[k + 1] = key;
}
}
void dynarray_free(dynarray_t *dynarray)
{
assert(dynarray_is_valid(dynarray));
free(dynarray->data);
dynarray->size = dynarray->capacity = 0;
dynarray->data = NULL;
}
int main(void)
{
dynarray_t arr = dynarray_create();
if (!dynarray_is_valid(&arr)) {
fputs("Not enough memory. :(\n\n", stderr);
return EXIT_FAILURE;
}
int result = EXIT_FAILURE;
for (value_type i = 2; i < 15; i += 2) {
if (!dynarray_push_back(&arr, i))
goto error_exit;
}
dynarray_print(&arr);
putchar('\n');
for (value_type i = 1; i < 14; i += 2) {
if (i != 7) {
if (!dynarray_push_front(&arr, i))
goto error_exit;
}
}
dynarray_print(&arr);
putchar('\n');
dynarray_sort(&arr);
dynarray_print(&arr);
putchar('\n');
if (!dynarray_insert_sorted(&arr, 0))
goto error_exit;
dynarray_print(&arr);
putchar('\n');
if (!dynarray_insert_sorted(&arr, 15))
goto error_exit;
dynarray_print(&arr);
putchar('\n');
if (!dynarray_insert_sorted(&arr, 7))
goto error_exit;
dynarray_print(&arr);
putchar('\n');
result = EXIT_SUCCESS;
error_exit:
result == EXIT_FAILURE && fputs("Not enough memory. :(\n\n", stderr);
dynarray_free(&arr);
return result;
}
Output:
2, 4, 6, 8, 10, 12, 14
13, 11, 9, 5, 3, 1, 2, 4, 6, 8, 10, 12, 14
1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14
0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14
0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
Todo:
dynarray_insert_range()
dynarray_create_init() from iterator pair
dynarray_from_file()
dynarray_copy()
dynarray_begin()
dynarray_end()
...
You make some mistakes:
1) int* pointerToArray[] is a pointer to pointer(s). You should use int* pointerToArray.
2) *(*pointerToArray+*count)=*count; is dereferencing pointerToArray two times, you should use *(pointerToArray + *count) = *count;.
3) dynamicArrayis already a pointer, you should not use the &operator to get its address. Then counterFunction(&dynamicArray, &counter);should be converted in counterFunction(dynamicArray, &counter);.
Finally, your code should look like:
#include <stdio.h>
#include <stdlib.h>
static void counterFunction(int * pointerToArray, int * count){
while (*count < 10) {
*(pointerToArray + *count) = *count;
*count += 1;
}
}
static int * writeSortedToArray(){
//I need to store 1000 numbers at this point
int * dynamicArray = malloc(100 * sizeof(int));
int counter = 0;
counterFunction(dynamicArray, &counter);
// as suggested, finally release the array
free(dynamicArray);
return 0;
}
int main(){
writeSortedToArray();
return 0;
}
static void counterFunction(int array[], int* count)
{
ptrdiff_t i;
for (i = *count; i < 10; i++)
array[i] = i;
*count = i;
}
static int *writeSortedToArray(void)
{
//I need to store 1000 numbers at this point
int *dynamicArray;
int counter;
dynamicArray = calloc(sizeof(*dynamicArray) * 1000);
counter = 0;
counterFunction(dynamicArray, &counter);
/* counter == 10 */
return dynamicArray;
}
First of all, if a function always returns 0, it should be void (except main(), for its own reasons). Although you probably didn't want to return 0, and instead return the array.
The counter function doesn't need to know that the array is dynamic. It can just accept any array, and use it with array notation.
I changed to a for loop, because it's more natural.
You don't need to pass a pointer to the array, and in fact you shouldn't, because then the compiler could notice the difference between a pointer to an array and a pointer to a pointer, and complain.
I don't get the purpose of your code, but this code is just the corrected version of your code.
Remember to free(dynamicArray); at some point.
Wrong use of pointer here. Your Dynamicarray from the WriteSortedToArray is already an adress so you do not need to pass it as an adress.
This should work :
static void counterFunction(int* pointerToArray, int count){
while (count < 10)
{
pointerToArray[count] = count;
count++;
}
}
static int* writeSortedToArray(void){
int* dynamicArray = malloc(1000 * sizeof(int));
int counter = 0;
counterFunction(dynamicArray, counter);
return 0;
}
If you want to keep the value of your counter when exiting your counterFunction which is 10, do this instead :
static void counterFunction(int* pointerToArray, int *count){
while (*count < 10)
{
pointerToArray[*count] = *count;
*count++;
}
}
static int* writeSortedToArray(void){
int* dynamicArray = malloc(1000 * sizeof(int));
int counter = 0;
counterFunction(dynamicArray, &counter);
return 0;
}
You should always free your memory using the free function to avoid memory leak issues.
free(dynamicArray)
Related
I would like to generate all posible combinations of ints, an example:
for set [1, 2, 3]; there all combinations are:
[
[], [ 3 ],
[ 2 ], [ 3, 2 ],
[ 1 ], [ 3, 1 ],
[ 2, 1 ], [ 3, 2, 1 ]
]
I know, how to do that in javascript, but cannot find out, how to do the same in C. The javascript version:
const combinations = (elements) => {
if (elements.length === 0) return [[]];
const firstEl = elements[0];
const rest = elements.slice(1);
const combsWithoutFirst = combinations(rest);
const combsWithFirst = [];
combsWithoutFirst.forEach(combs => {
const combWithFirst = [...combs, firstEl];
combsWithFirst.push(combWithFirst);
});
return [...combsWithoutFirst, ...combsWithFirst];
}
console.log(combinations([1, 2, 3]));
So what could be the c version?
EDIT: the version I have so far, but is not working correctly:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
int *values;
size_t size;
} comb;
comb *combinations;
size_t depth;
int count;
void init()
{
count = 1; // number of combintations so far
int size = depth;
for (int i = 0; i < depth; i++)
{
size *= 2;
}
combinations = malloc(sizeof(comb) * size);
}
comb *ctor(int *values, size_t size)
{
comb *newone = malloc(sizeof(comb));
newone->values = values;
newone->size = size;
return newone;
}
comb *pop_front(comb x)
{
int newSize = x.size - 1;
int *newVals = malloc(sizeof(int) * newSize);
memcpy(newVals, x.values + sizeof(int), newSize);
return ctor(newVals, newSize);
}
comb *push_back(comb x, int newValue)
{
int newSize = x.size + 1;
int *newVals = malloc(sizeof(int) * newSize);
memcpy(newVals, x.values, x.size * sizeof(int));
newVals[newSize - 1] = newValue;
return ctor(newVals, newSize);
}
void addComb(comb *x, comb y)
{
}
comb *func(comb *elements)
{
if (!depth)
{
return ctor(NULL, 0);
}
int firstEl = elements->values[0];
comb *rest = pop_front(*elements);
depth--;
comb *combsWithoutFirst = func(rest);
comb *combsWithFirst = ctor(NULL, 0);
for (int i = 0; i < count; i++)
{
comb *combWithFirst = push_back(combsWithoutFirst[i], firstEl);
// now add that combWithFirst to the combsWithFirst
}
// merge the two arrays
}
int main()
{
}
One simple way to do this is using a bitset. I guess 64 bits is far enough.
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
void comb(int *set, size_t n) {
assert(n < 64);
uint64_t bits = 0;
uint64_t end = 1 << n;
while (bits < end) {
printf("[");
for (size_t i = 0; i < n; ++i) {
if (bits & (1 << i)) {
printf("%d ", set[i]);
}
}
printf("]\n");
bits++;
}
}
int main(void) {
int set[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
comb(set, 10);
return 0;
}
so basically i am trying to solve a leet code problem called [two sum II] using hashing
but i am getting error in this test case 1,2,3,4,4,9,56,90 where i have to find two index those elements sum is equal to target 8
well the answer of this test case is 4,5 because the sum of index4 and index5 in array[1-8] is 8
Here the problem is when i compiled this below code in vs code it works perfectly fine and gives correct output 4,5
but during leet code submission it throws wrong answer and showing output 1,3 instead of 4,5
// here is my hash implemention code
#include <stdio.h>
#include <stdlib.h>
typedef struct Hash {
int value;
int index;
struct Hash *next;
} hash;
hash *Hashes[10];
int hashify(int value) { return abs(value) % 10; }
void insert(int value, int index) {
int key = hashify(value);
if (Hashes[key] == NULL) {
Hashes[key] = malloc(sizeof(hash));
Hashes[key]->value = value;
Hashes[key]->index = index;
Hashes[key]->next = NULL;
return;
}
hash *ptr = Hashes[key];
while (ptr->next != NULL) ptr = ptr->next;
ptr->next = malloc(sizeof(hash));
ptr->next->value = value;
ptr->next->index = index;
ptr->next->next = NULL;
return;
}
int search(int value) {
int key = hashify(value);
if (Hashes[key] == NULL) return -1;
if (Hashes[key]->value == value)
return Hashes[key]->index;
else {
hash *ptr = Hashes[key]->next;
while (ptr != NULL) {
if (ptr->value == value) return ptr->index;
ptr = ptr->next;
}
return -1;
}
}
// here is hash_free function
void Hash_free() {
for (int i = 0; i < 10; i++) {
if (Hashes[i] == NULL)
continue;
else {
if (Hashes[i]->next == NULL) {
free(Hashes[i]);
Hashes[i] = NULL;
} else {
hash *ptr;
while (ptr != NULL) {
ptr = Hashes[i]->next;
free(Hashes[i]);
Hashes[i] = ptr;
}
}
}
}
}
// here is two sum function code
int *twoSum(int *numbers, int numbersSize, int target, int *returnSize) {
int *result;
if (numbersSize == 2) {
result = malloc(2 * sizeof(int));
result[0] = 1;
result[1] = 2;
*returnSize = 2;
return result;
} else {
int val, element;
for (int i = 0; i < numbersSize; i++) {
val = target - numbers[i];
element = search(val);
if (element != -1) {
result = malloc(2 * sizeof(int));
if (element < i) {
result[0] = element + 1;
result[1] = i + 1;
} else {
result[0] = i + 1;
result[1] = element + 1;
}
*returnSize = 2;
Hash_free();
return result;
}
insert(numbers[i], i);
}
}
return NULL;
}
// here is main code
int main() {
int numbers[] = {1, 2, 3, 4, 4, 9, 56, 90};
int target = 8;
int numberSize = sizeof(numbers) / sizeof(int);
int returnSize;
int *res = twoSum(numbers, numberSize, target, &returnSize);
for (int i = 0; i < returnSize; i++) {
printf("%d ", res[i]);
}
free(res);
return 0;
}
Your "hash" variable is global, so it keeps preserving data of previous testcase executed. I have faced the same when using global variable.
Solution:
Just clear your hash or initialize it, in your main function( or the entry point function), so that it will ensure a fresh start for each of the test cases those are executed.
I wrote my implementation of vector ( dynamicly growing array) for integer type. And I was faced with a problem when using memmove and memcpy functions for data reallocation goals. Memmmove and memcpy functions work as not expected. So i replaced it with for and now it works properly. But what is the why memove works this way ?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct vector {
int v_size;
int v_length;
int* v_data;
} vector;
typedef vector *vect;
vect
new_vector(int size) {
vect tmp = (vector*)malloc(sizeof(vector));
tmp->v_size = size;
tmp->v_length = 0;
tmp->v_data = (int*)malloc(sizeof(int) * size);
return tmp;
}
void
add_velem(vect tmp, int elem) {
if(tmp->v_length != tmp->v_size) {
tmp->v_data[tmp->v_length] = elem;
tmp->v_length += 1;
} else {
tmp->v_size = tmp->v_size * 2;
tmp->v_length += 1;
int *new_vector = (int*)malloc(sizeof(int) * tmp->v_size);
memmove(new_vector, tmp->v_data, tmp->v_length); // GOT INPUT LIKE THIS:
// 500, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
// ALOT OF ZERO
/*
for(int i = 0; i < tmp->v_length; i++) {
new_vector[i] = tmp->v_data[i];
}*/ // BUT GOT RIGHT INPUT WHEN USING FOR. WHAT IS THE REASON?
free(tmp->v_data);
tmp->v_data = new_vector;
tmp->v_data[tmp->v_length - 1] = elem;
}
return;
}
int
get_vlength(vect tmp) {
return tmp->v_length;
}
int
get_vsize(vect tmp) {
return tmp->v_size;
}
int
get_velem(vect tmp, int elem) {
if(tmp->v_data == NULL) {
fprintf(stderr, "Index out of range!\n");
}else if(elem >= tmp->v_length) {
fprintf(stderr, "Index is out of range!\n");
return -1;
}
return tmp->v_data[elem];
}
void
delete_vector(vect tmp) {
free(tmp->v_data);
tmp->v_data = NULL;
free(tmp);
tmp = NULL;
}
int
main(void) {
vect example = new_vector(10);
printf("lenth of vector is %d\n", get_vlength(example));
add_velem(example, 500);
printf("element %d is pushed into vector\n", 500);
printf("size of vector is %d and\nlength of vector is %d\n", get_vsize(example), get_vlength(example));
int velem = get_velem(example, 0);
printf("elem 0 of vector is %d\n", velem);
for(int i = 1; i < 30; i++) {
add_velem(example, i);
}
printf("length of vector is %d now\n", get_vlength(example));
for(int i = 0; i < get_vlength(example); i++) {
printf("%d, ", get_velem(example, i));
}
delete_vector(example);
return 0;
}
I have a problem to understand Kruskal Algorithm. Here is the code
#include <stdio.h>
#define MAX_VERTICLES 100
#define INF 1000
int parent[MAX_VERTICLES];
int num[MAX_VERTICLES];
void setInit(int n) {
int i;
for (i = 0; i < n; i++) {
parent[i] = -1;
num[i] = 1;
}
}
int setFind(int vertex) {
int p, s, i = -1;
for (i = vertex;(p = parent[i]) >= 0; i = p)
;
s = i;
for (i = vertex;(p = parent[i]) >= 0; i=p)
parent[i]=s;
return s;
}
void setUnion(int s1, int s2) {
if (num[s1] < num[s2]) {
parent[s1]=s2;
num[s2]+=num[s1];
}
else {
parent[s2] = s1;
num[s1] += num[s2];
}
}
typedef struct {
int key;
int u;
int v;
}element;
#define MAX_ELEMENT 100
typedef struct {
element heap[MAX_ELEMENT];
int heap_size;
}HeapType;
void init(HeapType *h) {
h->heap_size = 0;
}
void printHeap(HeapType *h) {
int i;
int level = 1;
printf("\n==========");
for (i = 1; i <= h->heap_size;i++) {
if (i = level) {
printf("\n");
level *= 2;
}
printf("\t%d", h->heap[i].key);
}
printf("\n==========");
}
void insertMinHeap(HeapType *h, element item) {
int i;
i = ++(h->heap_size);
while ((i != 1) && (item.key < h->heap[i / 2].key)){
h->heap[i] = h->heap[i / 2];
i /= 2;
}
h->heap[i] = item;
}
element deleteMinHeap(HeapType *h) {
int parent, child;
element item, temp;
item = h->heap[1];
temp = h->heap[(h->heap_size)--];
parent = 1;
child = 2;
while (child <= h->heap_size) {
if ((child < h->heap_size) && (h->heap[child].key > h->heap[child + 1].key))
child++;
if (temp.key <= h->heap[child].key) break;
h->heap[parent] = h->heap[child];
parent = child;
child *=2;
}
h->heap[parent] = temp;
return item;
}
void insertHeapEdge(HeapType *h, int u, int v, int weight) {
element e;
e.u = u;
e.v = v;
e.key = weight;
insertMinHeap(h, e);
}
void insertAllEdges(HeapType *h){
insertHeapEdge(h, 0, 1, 13);
insertHeapEdge(h, 1, 2, 36);
insertHeapEdge(h, 2, 3, 12);
insertHeapEdge(h, 2, 4, 28);
insertHeapEdge(h, 3, 5, 32);
insertHeapEdge(h, 4, 5, 14);
insertHeapEdge(h, 0, 5, 19);
insertHeapEdge(h, 0, 6, 23);
insertHeapEdge(h, 1, 6, 15);
insertHeapEdge(h, 5, 6, 20);
}
void kruskal(int n) {
int edge_accepted = 0;
HeapType h;
int uset, vset;
element e;
init(&h);
insertAllEdges(&h);
setInit(n);
while (edge_accepted<(n-1)){
e = deleteMinHeap(&h);
uset = setFind(e.u);
vset = setFind(e.v);
if (uset != vset) {
printf("(%d,%d) %d \n", e.u, e.v, e.key);
edge_accepted++;
setUnion(uset, vset);
}7
}
}
void main(){
kruskal(7);
getchar();
}
I cannot understand how setFind and setUnion functions work.(the other things are fine)
Somebody can explain the algorithms explicitly, please?
The algorithm by Kruskal (which aims at the generation of a minimum spanning tree) needs subroutines for finding the connected component for a given vertex and the possibility to merge connected components.
Apparently, parent[i] stores one single vertex which can be followed until no parent is possible; the node which is reached this way is the root of the connected component - this node can be found via setFind; num[i] represents the number of children defined by this relation. Thus, the connected components are represented implicity.
The function setUnion aims at merging the smaller connected component into the larger one by attaching the root of one connected component to the other component and updating the number of children.
So I have this code thats supposed to do this
// REQUIRES: n >= 1. Elements a[0] ... a[n-1] exist.
// PROMISES
// If n == 1, returns 1.
// Returns 1 if all of a[0] <= a[1] ... a[n-2] <= a[n-1] are true.
// Otherwise, returns 0.
#include <assert.h>
#include "array-utils4F.h"
#define UNIT_TESTS 1
int is_sorted(const int *a, int n)
{
assert (n >= 1);
if (n == 1)
return 1;
int k ;
for (k = 1; k < n ; k++) {
if (a[k-1] > a[k])
return 0;
return 1;
}
}
int max_el(const int *a, int n)
{
assert(n >= 1);
int result = 0, i;
for (i = 0; i < n; i++)
if (a[i] > result)
result = a[i];
return result;
}
#ifdef UNIT_TESTS
#include <stdio.h>
#define COUNT(x) (sizeof(x)/sizeof(x[0]))
void test_is_sorted(const char *tag, const int *a, int n, int expected_rv);
void test_max_el(const char *tag, const int *a, int n, int expected_rv);
int main(void)
{
int test_01[] = { 10, 20, 30, 40, 50 };
int test_02[] = { 10, 10, 10, 10 };
int test_03[] = { 10, 20, 30, 40, 35 };
int test_04[] = { 10, 20, 30, 25, 40 };
int test_05[] = { 10, 5, 15, 25 };
test_is_sorted("test_01", test_01, COUNT(test_01), 1);
test_is_sorted("test_02", test_02, COUNT(test_02), 1);
test_is_sorted("test_03", test_03, COUNT(test_03), 0);
test_is_sorted("test_04", test_04, COUNT(test_04), 0);
test_is_sorted("test_05", test_05, COUNT(test_05), 0);
fputc('\n', stdout);
int test_06[] = { 100, 1, 2, 3 };
int test_07[] = { 1, 2, 100, 3 };
int test_08[] = { 1, 2, 3, 100 };
int test_09[] = { -1, -2, -3, -4 };
int test_10[] = { -8, -7, -6, -7, -8 };
test_max_el("test_06", test_06, COUNT(test_06), 100);
test_max_el("test_07", test_07, COUNT(test_07), 100);
test_max_el("test_08", test_08, COUNT(test_08), 100);
test_max_el("test_09", test_09, COUNT(test_09), -1);
test_max_el("test_10", test_10, COUNT(test_10), -6);
fputc('\n', stdout);
return 0;
}
void test_is_sorted(const char *tag, const int *a, int n, int expected_rv)
{
printf("Testing is_sorted for case with tag \"%s\":", tag);
if (expected_rv == is_sorted(a, n))
printf(" Pass.\n");
else
printf(" FAIL!\n");
}
void test_max_el(const char *tag, const int *a, int n, int expected_rv)
{
printf("Testing max_el for case with tag \"%s\":", tag);
if (expected_rv == max_el(a, n))
printf(" Pass.\n");
else
printf(" FAIL!\n");
}
#endif // #ifdef UNIT_TESTS
but when I test it it doesnt work, what can I change.
when i use this test int test_04[] = { 10, 20, 30, 35, 40 };
it returns 0. what am i doing wrong?I have added my entire code but the function still shows some defect, idk why it is doing this any help would be appreciated.
For now, when you did that if (a[0] <= a[k+ 1]), you just check if all value in the array are greater or equal than the first element of your array. You must check if an element is greater or equal than the previous element and if it's lesser or equal than the next element.
int is_sorted(const int *a, int n)
{
assert (n >= 1);
int k;
for (k = 1 ; k < n ; k++) {
if (a[k-1] > a[k])
return 0;
}
return 1;
}
Instead of use a variable result, you can directly return 0 when you know that the array isn't sorted.
Without added local variables
int is_sorted(const int *a, int n) {
assert (n >= 1);
while (--n)
if (a[n] < a[n-1])
return 0;
return 1;
}
Try this one
int is_sorted(const int *a, int n)
{
assert (n >= 1);
if (n == 1)
return 1;
int k, result=1;
for (k = 0; k < n - 1; k++) {
if (a[k] > a[k+ 1])
{
result = 0;
break;
}
}
return result;
}