Im trying to build a dynamic array (according to the user input) using by a function. Im giving a small example of what i thought to do:
enter code here
int main()
{
int *array;
int counter=0; ) //countes how many inputs we got
*array=dynamic_array(array,counter)
return 0;
}
int *dynamic_array(int *array, int counter){
int c=0;
while(c!=-1)
{
counter++;
array=(int *)realloc(arraya(counter)*sizeof(int));
}
return(array);
}
And another qustion, if i want to use &counter- which i cannot do it on c, how can i replace it?
Thank you.
Your code is really weird, so it's hard to tell what you actually want.
You probably want something like this:
#include <stdlib.h>
#include <stdio.h>
// declare the dynamic_array function
int *dynamic_array(int *array, int counter);
int main()
{
int *array = NULL; // initialize to NULL (see realloc documentation)
// allocate an array of 10 ints
int counter = 10;
array = dynamic_array(array, counter);
array[0] = 12;
array[1] = 34;
// extend the array to 20 ints
counter = 20;
array = dynamic_array(array, counter);
printf("array[0] = %d\n", array[0]);
printf("array[1] = %d\n", array[1]);
return 0;
}
int *dynamic_array(int *array, int counter)
{
array = (int*)realloc(array, counter * sizeof(int));
return(array);
}
Related
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;
}
I am solving a leetcode problem "Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice."
I was able to solve the problem if array elements are positive.
I created a hashtable which works well for positive numbers. How can I make it to work for non-positive numbers.
#include "stdio.h"
#include "stdlib.h"
#include "assert.h"
/**
* Note: The returned array must be malloced, assume caller calls free(). [2,7,11,15]
*/
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
//create a hashmap
int *hashmap = (int*)malloc(100000*sizeof(int));
int *retarray = NULL;
//memset all values to -1;
memset(hashmap,-1,(100000*sizeof(int)));
int i = 0;
int complement;
for(i=0;i<numsSize;i++){
complement = abs(target-nums[i]);
if(hashmap[complement]!= -1){
*returnSize = 2;
retarray = (int*)malloc(*returnSize*sizeof(int));
retarray[0] = hashmap[complement];
retarray[1] = i;
return retarray;
}
hashmap[nums[i]] = i;
}
*returnSize = 0;
return retarray;
}
int main(){
int i = 0;
// int arr[4] = {2,7,11,15};
int arr[4] = {-3,3,11,15}; //fails for this.
int *ret_arr;
int returnSize;
ret_arr = twoSum(arr,4,9,&returnSize);
assert(returnSize==2);
printf("ret array %d %d \n",ret_arr[0],ret_arr[1]);
}
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.
I want to return a dynamic array by reference from a void function.
I already searching 3 hours for the answer, couldn't find anything helpfull.
Here is my simplified code :
main()
{
int **a;
xxx(&a);
printf("%d\n\n", a[1]);
}
void xxx(int **a)
{
int i;
*a = (int*)malloc(5 * 4);
for (i = 0; i < 5; i++)
a[i] = i;
printf("%d\n\n", a[1]);
}
I just want to allocate dynamic array in the "xxx" Function and return it by reference to main, than I want to print it or use it for something else. Thanks in advance :)
edit
#include <stdio.h>
#include <stdlib.h>
#define MACROs
#define _CRT_SECURE_NO_WARNINGS
void xxx(int **a);
int main(void)
{
int *a;
xxx(&a);
printf("%d\n\n", a[1]);
}
void xxx(int **a)
{
int i;
*a = malloc(5 * sizeof(**a));
for (i = 0; i < 5; i++)
a[i] = i;
printf("%d\n\n", a[1]);
}
I have amended a few things and added some comments.
#include <stdio.h> // please inlcude relevant headers
#include <stdlib.h>
#define ELEM 5 // you can change the requirement with a single edit.
void xxx(int **a) // defined before called - otherwise declare a prototype
{
int i;
*a = malloc(ELEM * sizeof(int)); // do not use magic numbers, don't cast
if(*a == NULL) {
exit(1); // check memory allocation
}
for (i = 0; i < ELEM; i++) {
(*a)[i] = i; // index correctly
}
}
int main(void) // 21st century definition
{
int *a; // correct to single *
int i;
xxx(&a);
for (i = 0; i < ELEM; i++) { // show results afterwards
printf("%d ", a[i]);
}
printf("\n");
free(a); // for completeness
}
Program output:
0 1 2 3 4
In your main(), you need to have a pointer, not a pointer to pointer. change
int **a;
to
int *a;
and, inside the xxx(), change
a[i] = i;
to
(*a)[i] = i;
That said
Don't use magic numbers, rewrite your malloc statement like
*a = malloc(5 * sizeof(**a));
to be more robust. Also, for static counts, use #define MACROs.
Please see this discussion on why not to cast the return value of malloc() and family in C..
main() is not a valid signature for a hosted environment. You need to use int main(void), at least.
Ok guys so the thing that made it work is
a[i] = i;
to
(*a)[i] = i;
3 hours for such a simple answer.
Thank you very much everybody here.
Can some explain why it was the problem?
Okay, so I am calling function fill_arrays like this:
fill_arrays(&data1, &data2, &size1, &size2);
fill_arrays looks like this:
void fill_arrays(int **data1, int **data2, int *size1, int *size2){
*size1 = get_size(*size1, 1);
*size2 = get_size(*size2, 2);
*data1 = malloc(*size1 * sizeof(int *));
*data2 = malloc(*size2 * sizeof(int *));
input_data(&data1, *size1, 1);
}
In input_data function I would like to assign some numbers to an array:
void input_data(int **data, int size, int index){
*data[5] = 5;
}
The problem is, I am completely lost with pointers... Maybe you can tell me how should I call function input_data in order to be able to assign some numbers to data array?
Assuming that input_data should set all array values to a known value, you could write
void input_data(int *data, int size, int value){
for (int i=0; i<size; i++) {
data[i] = value;
}
}
calling this like
input_data(*data1, *size1, 5); // set all elements of data1 to 5
The key point here is that you can use (*data1)[index] to access a particular array element and can pass your arrays as int* arguments.
I stumbled upon this question while doing a homework assignment and the answer doesn't strike me as entirely satisfactory, so I'll try to improve upon it.
Here is a small program that will establish an array of a user-defined size, fill it arbitrarily, and print it.
#include <stdio.h>
#include <stdlib.h>
void fill_array(int *array, int n)
{
int i;
for (i = 0; i < n; i++)
{
// fill array like [1, 2, 3, 4...]
array[i] = i+1;
}
}
void print_array(int *array, int n)
{
int i;
printf("[");
for (i = 0; i < n; i++)
{
if (i == (n-1))
printf("%d]\n", array[i]);
else
printf("%d, ", array[i]);
}
}
int main()
{
int n;
printf("Please enter a size for your array>");
scanf("%d", &n);
// dynamically allocate memory for integer array of size n
array = (int*) malloc (n * (sizeof(int)));
fill_array(array, n);
print_array(array, n);
return 0;
}
I hope this helps anyone who is learning C for the first time, or coming back to it after years away from the tried and true language, like me.
It seems you should also add int *array = NULL in order to get it working.