struct function passing and returning - c

Can anyone help me out to code the main function of this aadjacentElementsProduct function?
the question is:
This is what i tried :
struct arr_integer
{
int size;
int arr[];
};
int adjacentElementsProduct(struct arr_integer inputArray);
int main()
{
int res,i;
struct arr_integer array;
printf("Enter size of the array: ");
scanf("%d", &array.size);
printf("Enter the elements in array: ");
for (i = 0; i < array.size; i++)
{
scanf("%d", &array.arr[i]);
}
printf("%d\n", array.arr[2]);
res = adjacentElementsProduct(array);
printf("Max is %d", res);
getch();
}
Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
Example
For inputArray = [3, 6, -2, -5, 7, 3], the output should be adjacentElementsProduct(inputArray) = 21
.
7 and 3 produce the largest product.
int adjacentElementsProduct(struct arr_integer inputArray)
{
int arrLength = inputArray.size;
int max = inputArray.arr[0] * inputArray.arr[1];
for (int i = 1; i < arrLength - 1; i++)
{
if (inputArray.arr[i] * inputArray.arr[i + 1] > max)
{
max = inputArray.arr[i] * inputArray.arr[i + 1];
}
}
return max;
}

The structure member arr is a flexible array member. By default it doesn't have a size or even memory allocated for it, it needs to be allocated. And that can only be done through dynamic allocation of the whole structure (using e.g. malloc).
So the solution is something like
struct arr_integer *array;
size_t array_size;
// Get the number of elements for the array
printf("Enter size of the array: ");
scanf("%zd", &array_size);
// Allocate memory for both the structure and the array data
array = malloc(sizeof *array + sizeof *array->arr * array_size);
array->size = array_size;
// Now you can initialize `array->arr[i]` for any `i` between `0` and `array->size - 1`

#Muneer. You just need to readjust your for loop as follows:
int adjacentElementsProduct(struct arr_integer inputArray)
{
int arrLength = inputArray.size;
int max = inputArray.arr[0] * inputArray.arr[1];
for (int i = 2; i < arrLength - 1; i++)
{
if (inputArray.arr[i-1] * inputArray.arr[i] > max)
{
max = inputArray.arr[i-1] * inputArray.arr[i];
}
}
return max;
}
Notice the first value of i in the loop (i=2)

The problem is that you don't allocate any memory. Your struct with the [] syntax in the end is called "flexible array member". It can only be used if you allocate memory for the struct manually, like this:
#include <stdlib.h>
...
printf("Enter size of the array: ");
int size;
scanf("%d", &size);
struct arr_integer* array = malloc( sizeof(*array) + sizeof(int[size]) );
array->size = size;
printf("Enter the elements in array: ");
for (i = 0; i < array.size; i++)
{
scanf("%d", &array.arr[i]);
}
...
free(array);

While the answers about the missing memory allocation are correct, I think it would be easier to change it thus:
struct arr_integer
{
int size;
int *arr; //<<<<<<<<<<
};
int adjacentElementsProduct(struct arr_integer inputArray);
int main()
{
int res,i;
struct arr_integer array;
printf("Enter size of the array: ");
scanf("%d", &array.size);
//Of course add check for return value of scanf and to
// the validity of the size
array.arr = malloc(array.size * sizeof(*array.arr));
//and check the malloc return
//and later free the allocated memory!
.
.
.
This allows the OP to still use 'conventional' syntax for the declaration of the struct, and malloc - ing only the dynamic part. I think it is more readable.

Related

C how to reduce array size with realloc

whan I enter a bigger size to the array every thing just goes fine.
but if I put a smaller size it's just change the value in the array to some garbage value. Someone know's why?
int resize(int* calc, int size)
{
int new_number = 0, i = 0;
printf("Enter new number of grade: ");
scanf("%d", &new_number);
calc = (int*)realloc(calc, new_number * sizeof(int));
if (new_number > size)
{
for (i = size + 1; i <= new_number; i ++)
{
printf("Enter grade %d: ", i);
do
{
scanf("%d", &calc[i - 1]);
} while (check_valid(calc, i));
}
size = new_number;
}
return size;
}
The value returned from realloc() may be different from what is passed.
The argument calc is a copy of what is passed, so modification of that will not affect what is passed.
To update the array correctly, you should receive a pointer to the pointer so that the pointer can be updated from the resize() function.
Also:
It looks weird to return old size when new size is smaller than new size while resizing is done in both case.
Casting results of malloc() family is considered as a bad practice.
Try this (make calc pointer to int* and add dereferences):
int resize(int** calc, int size)
{
int new_number = 0, i = 0;
printf("Enter new number of grade: ");
scanf("%d", &new_number);
*calc = realloc(*calc, new_number * sizeof(int));
if (new_number > size)
{
for (i = size + 1; i <= new_number; i ++)
{
printf("Enter grade %d: ", i);
do
{
scanf("%d", &(*calc)[i - 1]);
} while (check_valid(*calc, i));
}
}
return new_number;
}
and the calling will be like this:
int size = 0;
int* calc = NULL;
size = resize(&calc, size); /* add & to pass the pointer to the pointer */
instead of one for original function int resize(int* calc, int size):
int size = 0;
int* calc = NULL;
size = resize(calc, size);

Segmentation fault problem in C (core dumped)

#include <stdio.h>
#include <stdlib.h>
struct arrayADT {
int *A;
int size;
int length;
int *B;
int arr3;
};
struct arrayADT * MergeArray(struct arrayADT *arr1, struct arrayADT *arr2) { //we create thus in heap cuz we need to be able to use these in main function
struct arrayADT *arr3 = (struct arrayADT *)malloc((sizeof(struct arrayADT)));
int i, j, k;
i = j = k = 0;
while(i < arr1->length && j < arr1->length ) {
if(arr1->A[i] < arr2->A[j]) {
arr3->A[k] = arr1->A[i];
k++;
i++;
}
else {
arr3->A[k] = arr2->A[j];
k++;
j++;
}
}
for(; i<arr1->length ; i++) {
arr3->A[k] = arr1->A[i];
k++;
}
for(; j < arr2->length ; j++) {
arr3->A[k] = arr2->A[j];
k++;
}
arr3->length = arr1->length + arr2->length;
arr3->length = 10;
}
void main() {
struct arrayADT arr;
printf("Enter the size of an array");
scanf("%d", &arr.size);
arr.A = (struct arrayADT *)malloc(arr.size * sizeof(int));
arr.length = 0;
int n;
printf("enter the number of elements in an array");
scanf("%d", &n);
printf("enter the elements");
for(int i = 0; i < n; i++) {
scanf("%d", &arr.A[i]);
}
arr.length = n;
display(arr);
printf("Enter second array");
int j;
struct arrayADT *B = (struct arrayADT *)malloc((sizeof(struct arrayADT)));
for(j = 0; j < arr.length; j++) {
scanf("%d", &B[j]);
}
struct arrayADT *arr3 = (struct arrayADT *)malloc(sizeof(struct arrayADT));
arr3 = MergeArray(&arr, &B);
display(*arr3);
I was looking to merge these arrays using heap memory and I am getting segmentation fault. I am new to C programming with pointers and I have been struck here it would be so helpful if I passed this barrier with your help.
And I am not getting where my error lies it would be helpful if someone specifies that too, so that I can avoid these errors in future.
PS: I am using minGW compiler.
In general, your code is rater unorganized. There are several cases for undefined behaviour, for example you don't scan in the second array correctly. The most probably candidate for your segmentaion fault is here:
struct arrayADT *arr3 = (struct arrayADT *)malloc((sizeof(struct arrayADT)));
This will give you an uninitialized chunk of memory. The length and size could of arr3 be anything, and its data field A does not point to valid memory. Accessing it will likely crash.
You have three arrays in your code. You construct each step by step and you treat each differently. That leads to errors easily. Let's go about this more systematically.
Let's create a struct type for a fixed-size array: The maximum size must be given on creation and cannot change. The actual length of the array may be anything from 0 to its maximum size.
typedef struct Array Array;
struct Array {
int *value; // data array
int length; // actual length, 0 <= length <= size
int size; // maximum capacity
};
We create such arrays on the heap and because initializing the members is error-prone, we write a constructor:
Array *array_create(int size)
{
Array *array = calloc(1, sizeof(*array));
array->size = size;
array->value = calloc(size, sizeof(*array->value));
return array;
}
This function creates an empty array for at most size integers. If we allocate memory, we must de-allocate it later, so let's write a corresponding destructor function, which cleans up the ressources:
void array_destroy(Array *array)
{
if (array) {
free(array->value);
free(array);
}
}
After destroying an array, it can no longer be used, just as with memory after calling free() on it.
The array is at first empty, so let's write a function to add elements at its end if there is room:
void array_push(Array *array, int x)
{
if (array->length < array->size) {
array->value[array->length++] = x;
}
}
And a function to print it:
void array_print(const Array *array)
{
printf("[");
for (int i = 0; i < array->length; i++) {
if (i) printf(", ");
printf("%d", array->value[i]);
}
printf("]\n");
}
Now you can create arrays like so:
Array *a = array_create(10);
for (int i = 0; i < a->size; i++) {
array_push(a, i);
}
array_print(a);
array_destroy(a);
Your merge function will be simpler, too. Here's a full example. (But is uses generated array, not arrays typed in by the user.)
#include <stdio.h>
#include <stdlib.h>
typedef struct Array Array;
struct Array {
int *value;
int length;
int size;
};
Array *array_create(int size)
{
Array *array = calloc(1, sizeof(*array));
array->size = size;
array->value = calloc(size, sizeof(*array->value));
return array;
}
void array_destroy(Array *array)
{
if (array) {
free(array->value);
free(array);
}
}
void array_push(Array *array, int x)
{
if (array->length < array->size) {
array->value[array->length++] = x;
}
}
void array_print(const Array *array)
{
printf("[");
for (int i = 0; i < array->length; i++) {
if (i) printf(", ");
printf("%d", array->value[i]);
}
printf("]\n");
}
Array *merge(Array *a, Array *b)
{
Array *res = array_create(a->length + b->length);
int i = 0;
int j = 0;
while(i < a->length && j < b->length) {
if(a->value[i] < b->value[j]) {
array_push(res, a->value[i++]);
} else {
array_push(res, b->value[j++]);
}
}
while(i < a->length) {
array_push(res, a->value[i++]);
}
while(j < b->length) {
array_push(res, b->value[j++]);
}
return res;
}
int main(void)
{
Array *a = array_create(10);
Array *b = array_create(6);
Array *c;
for (int i = 0; i < a->size; i++) {
array_push(a, 1 + 3 * i);
}
for (int i = 0; i < b->size; i++) {
array_push(b, 4 + 2 * i);
}
array_print(a);
array_print(b);
c = merge(a, b);
array_print(c);
array_destroy(a);
array_destroy(b);
array_destroy(c);
return 0;
}
If you've read so far, here's the lowdown:
Organzie your code. That applies to code layout as much as writing small, generally applicable functions instead of doing everything "by hand". (The array type above is a bit on the fence: It uses functions, but getting at the data is still done via accessing the struct fields. You could even change the szie and length, whixh shouldn't really happen.)
Enable compiler warnings with -Wall. You will get useful information about potential (and often actual) errors.
Good luck!

Array Rotation with Getting Max Value and Index Location of Array C language

I'm creating a program that gets the index value of the highest element in an array.
Sample Input:
4 (Size of a[])
1 2 4 3 (Elements of a[])
2 (Size of rotate[])
0 2 (Elemnts of rotate[])
Output will be:
2
0
Using left rotation.
In the First Rotation (0) the location will be 2 because 4 is the highest a[1,2,4,3]
In the Second Rotation (2) the location will be 0 because 4 is the highest a[4,3,1,2]
Problem is i'm not getting the desired output and there was a warning in for(j=0;j<rotateValue;j++)
I want the function to be as it is and to fix this part to int* output = getMaxIndex(a,rotate);
but i don't know how.
Thank you in advance for helping!
#include<stdio.h>
int i,j,k; // for looping
int n, m; // sizes of arrays
int getMaxIndex(int* a[], int* rotate[])
{
int indices[m];
for(i=0;i<m;i++)
{
int* rotateValue = rotate[i];
for(j=0;j<rotateValue;j++) // for rotation
{
int* first = a[0];
for(i=0;i<n-1;i++)
{
a[i] = a[i+1];
}
a[n-1] = first;
}
int location;
int* max = a[0];
for(j=0;j<n;j++) // getting the max element
{
if(a[j] > max)
{
max = a[j];
// printf("Max added");
}
}
for(j=0;j<n;j++) // getting the location
{
if(max == a[j])
{
location = j;
// printf("Loc added");
}
}
indices[i] = location;
}
// for(i=0;i<m;i++) // printing here to know if correct
// {
// printf("%d",indices[i]);
// }
return *indices;
}
int main()
{
scanf("%d",&n); // inputting array size
int* a[n];
for(i=0;i<n;i++) // filling elements of a[]
{
scanf("%d",&a[i]);
}
scanf("%d",&m); // inputting rotate array size
int* rotate[m];
for(i=0;i<m;i++) // filling elements of rotate[]
{
scanf("%d",&rotate[i]);
}
int* output = getMaxIndex(a,rotate); // call function
for(i=0;i<m;i++) // printing output
{
printf("%d",output[i]);
}
}
int getMaxIndex(int* a[], int* rotate[]);
Designing getMaxIndex() in the following way should solve most of the issues:
int* getMaxIndex(int a[], int rotate[])
{
static int indices[MAX_POSSIBLE_VALUE_OF_M];
/*
your code
*/
return indices;
}
Now, all you have to do is adjust your code in the main() function accordingly.
Why declare the array indices[] in getMaxIndex() as static int?
indices[] is a local variable of getMaxIndex(). And so after the return statement of getMaxIndex() is executed, it shall be destroyed. That means, if you return indices[] to main(), the main function will not be able to access indices[] anymore. And this issue can be solved by declaring indices[] as a static int instead of int.
NOTE: static array should have constant size. So, its size should be declared as maximum possible value of m instead of m.
Required adjustments in main():
Declare a[] and rotate[] as int instead of int*.
Check out my code.I am getting the correct output. I have written down a few mistakes that you have made.
void getMaxIndex(); //function declaration
int n, m; //for storing array size
int * a, * rotate;
int main(void) {
int i; //to use in loops
scanf("%d", & n); // inputting array size
a = (int * ) malloc(n * sizeof(int));
for (i = 0; i < n; i++) // filling elements of a[]
{
scanf("%d", & a[i]);
}
scanf("%d", & m); // inputting rotate array size
rotate = (int * ) malloc(m * sizeof(int));
for (i = 0; i < m; i++) // filling elements of rotate[]
{
scanf("%d", & rotate[i]);
}
getMaxIndex();
free(a);
free(rotate);
return 0;
}
void getMaxIndex() {
int i;
int aMax, rotateMax;
int aMaxIndex, rotateMaxIndex;
aMax = a[0];
rotateMax = rotate[0];
for (i = 1; i < n; i++) {
if (aMax < a[i]) {
aMax = a[i];
aMaxIndex = i;
}
}
for (i = 1; i < m; i++) {
if (rotateMax < rotate[i]) {
rotateMax = rotate[i];
rotateMaxIndex = i;
}
}
printf("%d\n%d", aMaxIndex, rotateMaxIndex);
}
My suggestions:
Always try to allocate memory for your array dynamically so that you can avoid errors such as Segmentation Fault or Core Dump.
In your code you have used array of pointers instead of pointers, there you went wrong. Try refering to your textbook or other sources to get a clear idea regarding pointers.
For example, in your code you passed your array named indices using the line:
return indices;
Now, to pass a pointer you don't need to use asterisk(). Simply write: return indices;
Also, don't use asterisk symbol to declare an array.
Your Code:
int* a[n];
Here you are declaring an array of pointers not an array.
Correct code:
int a[n];
But I liked your logic. You just have to implement it with the correct syntax. Just keep practicing.
I the code which I've written is understood by you, my work here is done. Happy Coding!!!

Why do I get a segmentation fault by declaring a 2d array in c?

I am new to threads and I have a program that uses threads to find the minimum number out of a 2d array and later on, it finds the distance that the other elements of the array have from the minimum number and stores them in another array.
The user should enter the size of the array and the number of threads he wants to use.
I tried the program below for 1d array and it worked just fine. When I converted it to work for a 2d array it started crashing and throwing a segmentation fault. I, however, cannot find which part of the 2d declaration is wrong.
Any help is really appreciated.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <pthread.h>
struct Parameters
{
// input
int s,p; //n is size of array, p is number of threads
int** array; //array with elements
int start;
int end;
// output
int smallest;
int pos; //position if minimum
int** B; //array that holds the distances
};
void* min(void* args)
{
struct Parameters* p = (struct Parameters*)args;
int **array = p->array;
int **B1 = p->B;
int start = p->start;
int end = p->end;
int smallest = array[start][start];
int pos = p->pos;
int distance;
//find the smallest
for (int i = start; i < end; i++)
{
for(int j = start; j < end; j++)
{
if (array[i][j] < smallest)
{
smallest = array[i][j];
pos = i;
}
}
}
//find the distances
for(int i = 0; i < ((struct Parameters*)args) -> s; i++)
{
for(int j = 0; j < ((struct Parameters*)args) -> s; j++)
{
distance = abs(pos - i);
B1[i][j] = distance;
}
}
params->smallest = smallest;
params->B = B1;
return NULL;
}
int main()
{
int smallest,pos;
int s,p;
struct Parameters *ptr = (struct Parameters *)malloc(sizeof(struct Parameters));
if(ptr == NULL)
{
printf("Not enough. Try again \n");
exit(0);
}
printf("Type s\n");
scanf("%d",&(ptr->s));
printf("Type p\n");
scanf("%d", &(ptr->p));
// declare an array of threads and associated parameter instances
pthread_t threads[(ptr->p)];
struct Parameters thread_parameters[(ptr->p)] ;
int arr[ptr->s][ptr->s];
int B2[ptr->s][ptr->s];
// intialize the array
for(int i=0; i< ptr->s; i++)
{
for(int j=0; j< ptr->s; j++)
{
printf("Type a \n");
scanf("%d",&arr[i][j]);
}
}
// smallest needs to be set to something
smallest = arr[0][0];
// start all the threads
for (int i = 0; i < ptr->p; i++)
{
memcpy(arr, thread_parameters[i].array, sizeof(arr));
thread_parameters[i].s = ptr->s;
memcpy(Bb, thread_parameters[i].B, sizeof(B2));
thread_parameters[i].start = i * (ptr->s / ptr->p);
thread_parameters[i].end = (i+1) * (ptr->s / ptr->p);
pthread_create(&threads[i], NULL, min, &thread_parameters[i]);
}
// wait for all the threads to complete
for (int i = 0; i < ptr->p; i++)
{
pthread_join(threads[i], NULL);
}
// Now aggregate the "smallest" and "largest" results from all thread runs
for (int i = 0; i < ptr->p; i++)
{
if (thread_parameters[i].smallest < smallest)
{
smallest = thread_parameters[i].smallest;
}
}
printf("Smallest is %d\n", smallest);
thread_parameters[ptr->p].B[ptr->s][ptr->s];
for (int i = 0; i < 1; i++)
{
for(int j = 0; j < ptr->s;j++)
{
for(int k = 0; k < ptr->s; k++)
{
printf("Element %d is %d away from min\n",j,thread_parameters[i].B[j][k]);
}
}
}
return 0;
}
Thank you!!
The issue with your code might also come from :
memcpy(arr, thread_parameters[i].array, sizeof(arr));
...
memcpy(Bb, thread_parameters[i].B, sizeof(B2));
as thread_parameters[i].array and thread_parameters[i].B are not allocated, if you are only reading the array it might b fine to only pass them by address
thread_parameters[i].array = arr
but for thread_parameters[i].B you would need to allocate the arrays and perform a deep copy (memcpy would not work)
The below text does not answer the question but does provide some insight on VLA usage
One reason for causing the segmentation with a declaration of a Variable Length Array is that the value is to large to allocate the array on the stack (some compiler choose this option, this choice might have performance reason).
The is not much option to recover cleanly from failure to allocate memory on the stack as there is little way to clean up stack memory during runtime within the same stack context.
You can mitigate the issue by allocating your 2D arrays on the heap instead, some of the strategies are available here(thanks #Lundin) and here.
int** alloc_2d_int_array(size_t rows, size_t cols) {
int **result = malloc(rows * sizeof(int *));
if(result == NULL) {
// could not allocate more memory
return NULL;
}
size_t row_size = cols * sizeof(int);
for(int i=0; i < rows; ++i) {
result[i] = malloc(row_size);
if(result[i] == NULL) {
// could not allocate more memory
// cleanup
return NULL;
}
}
return result;
}
the above implementation have not been tested, but does compile, there are still risk of integer overflow.
Then use the above define function as following:
int **arr = alloc_2d_int_array(ptr->s, ptr->s);
int **B2 = alloc_2d_int_array(ptr->s, ptr->s);
easier implementation (see here(thanks #Lundin))
int **arr = malloc(sizeof(int[ptr->s][ptr->s]);
int **B2 = malloc(sizeof(int[ptr->s][ptr->s]);

Allocating dynamic memory using malloc in C

I'm new to C and have been trying to tackle this question. It's a continuation of the last thread I made. I made some progress but still have so much to learn and fix.
In short:
In this question a "vector" is a one dimensional array of integers. Therefore an array of vectors would be a two dimensional array that holds one dimensional arrays inside him.
I need to use these variables:
int** vectors- the 2D array
int size -an integer that represents how many vectors exist inside **vectors
int* sizes-a 1D array of integers that represents the length of the vectors
I need to write the following functions:
int init(int ***vectors, int **sizes, int size)
the function allocated memory to **vectors and *sizes with size and initializes vectors to be full of NULLs,and sizes to be full of zeros.
int set(int **vectors, int *sizes, int index, int *tmp, int tmp_size)
the function receives an array of nulls (**vectors)), frees the vector inside **vectors whose index is index and allocates memory for a new vector, whose length is tmp_size and places inside it *tmp's elements.
This is my code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int init(int*** vectors, int** sizes, int size)
{
int i, k,j;
*sizes = (int*)malloc(size * sizeof(int));
if (*sizes == NULL)
return 0;
for (j = 0; j < size; j++)
{
(*sizes)[j] = 0;
}
*vectors = (int**)malloc(size * sizeof(int*));
if (*vectors == NULL)
return 0;
for (i = 0; i < size; i++)
{
(vectors)[i] = NULL;
}
return 1;
}
int set(int **vectors, int *sizes, int index, int *tmp, int tmp_size)
{
if ((vectors)[index] != NULL)
{
free((vectors)[index]);
}
(vectors)[index] = (int*)malloc(tmp_size * sizeof(int));
if ((vectors)[index] == NULL)
return 0;
for (int b = 0; b < tmp_size; b++)
{
(vectors)[index][b] = tmp[b];
}
sizes[index] = tmp_size;
return 1;
}
int main()
{
int size, i, length, indexhere;
int** vectors = NULL;
int* sizes = NULL;
int* tmp = NULL;
int* p = &vectors;
int tempindex;
printf("\nPlease enter an amount of vectors:\n");
scanf("%d", &size);
init(p, &sizes, size);
printf("Enter index\n");
scanf("%d", &indexhere);
printf("Enter Length\n");
scanf("%d", &length);
tmp = (int*)malloc(length * sizeof(int));
printf("Enter elements:\n");
for (int g = 0; g < length; g++)
scanf("%d", &tmp[g]);
set(&vectors, sizes, indexhere, tmp, length);
system("pause");
return 0;
}
Could someone explain please why the program always crashes?
In init function (vectors)[i] = NULL; should actually be (*vectors)[i] = NULL;
When calling set function from main you should pass vectors instead of &vectors.
There also seems to be several pointer type mismatches in your code, so you should really pay attention to compiler's warnings. This is because C unfortunately allows implicit conversions between incompatible pointers, unlike C++ for example.
You call set like this
set(&vectors, sizes, indexhere, tmp, length);
but the first argument is declared as an int **. By passing &vector you're passing a pointer to vector, i.e. something of type int ***. This mismatch will lead to undefined behavior and probable crashes.
Here is a complete working example.
#include <stdio.h>
#include <stdlib.h>
void destroyVectors(int **vectors, int size)
{
for (int i = 0; i < size; i++)
{
free(vectors[i]);
}
}
int init(int*** vectors, int** sizes, int size)
{
int i, j;
*sizes = (int*)malloc(size * sizeof(int));
if (*sizes == NULL)
return 0;
for (j = 0; j < size; j++)
{
(*sizes)[j] = 0;
}
*vectors = (int**)malloc(size * sizeof(int*));
if (*vectors == NULL)
return 0;
for (i = 0; i < size; i++)
{
(*vectors)[i] = NULL;
}
return 1;
}
int set(int **vectors, int *sizes, int index, int *tmp, int tmp_size)
{
if ((vectors)[index] != NULL)
{
free((vectors)[index]);
}
(vectors)[index] = (int*)malloc(tmp_size * sizeof(int));
if ((vectors)[index] == NULL)
return 0;
for (int b = 0; b < tmp_size; b++)
{
(vectors)[index][b] = tmp[b];
}
sizes[index] = tmp_size;
return 1;
}
int main()
{
int size = 0, length = 0, indexhere = 0;
int** vectors = NULL;
int* sizes = NULL;
int* tmp = NULL;
printf("\nPlease enter an amount of vectors:\n");
scanf("%d", &size);
init(&vectors, &sizes, size);
printf("Enter index\n");
scanf("%d", &indexhere);
printf("Enter Length\n");
scanf("%d", &length);
tmp = (int*)malloc(length * sizeof(int));
printf("Enter elements:\n");
for (int g = 0; g < length; g++)
scanf("%d", &tmp[g]);
set(vectors, sizes, indexhere, tmp, length);
for(int i = 0; i < length; ++i)
printf("byte: %d\n", vectors[indexhere][i]);
printf("sizes index: %d\n", sizes[indexhere]);
free(tmp);
free(sizes);
destroyVectors(vectors, size);
return 0;
}

Resources