dynamically create a 2d array of strings - c

i'm new to C and whilst working on a problem i'm struggling to dynamically create a 2d array of string values that i can access like things[i][j]. so far i can create a 1 d array of strings and access it like thing[i] but im stumped on how to do that for a 2d array with the rows and columns needed decided for a variable called total.
total = 7
char* *students = malloc(sizeof(char*) * total);
for(i=0;i<5;i++){
students[i]="kitty";
}
for(i=0;i<5;i++){
printf("%s",students[i]);
}
this is what i have soo far but i cant do for a 2d array.
ive already created a 1d array of strings

You can allocate a two-dimensional array like
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//...
char ( *students )[7] = malloc( sizeof( char[5][7] ) );
for ( size_t i = 0; i < 5; i++ )
{
strcpy( students[i], "kitty" );
}
for ( size_t i = 0; i < 5; i++ )
{
puts( students[i] );
}
//...
free( students );
Another approach is to allocate a one-dimensional array of pointers that in turn will point to one dimensional arrays of characters as for example
char **students = malloc( 5 * sizeof( char * ) );
fir ( size_t i = 0; i < 5; i++ )
{
students[i] = malloc( 7 * sizeof( char ) );
}
fir ( size_t i = 0; i < 5; i++ )
{
strcpy( students[i], "kitty" );
}
for ( size_t i = 0; i < 5; i++ )
{
puts( students[i] );
}
//...
for ( size_t i = 0; i < 5; i++ )
{
free( students[i] );
}
free( students );

Related

Dynamic array of array of int in C

How can an array of array of int be declared outside the main, then build inside the main once we know the length of the array of array we want to build, if one dimension is already known.
For example, if the array should be array[numberofargs][2], where the dimension 2 is already known but not numberofargs before execution of main.
One way is just to declare for example a pointer in a file scope like
int ( *array )[2] = NULL;
and then in one of functions allocate a memory for the array.
For example
#include <stdlib.h>
int (*array)[2] = NULL;
int main(void)
{
int numberofargs = 5;
array = malloc( sizeof( int[numberofargs][2] ) );
//...
free( array );
return 0;
}
Or the following way
#include <stdlib.h>
int **array = NULL;
int main(void)
{
int numberofargs = 5;
array = malloc( numberofargs * sizeof( *array ) );
for ( int i = 0; i < numberofargs; i++ )
{
array[i] = malloc( sizeof( *array[i] ) );
}
//...
for ( int i = 0; i < numberofargs; i++ )
{
free( array[i] );
}
free( array );
return 0;
}
Unfortunately, I do not know how to create an array where only the second dimension is known. What you can do is the following:
#include <stdlib.h>
#include <stdio.h>
#define SECOND_DIM 2
int *array;
// returns array[x][y]
int foo(int *array, int x, int y) {
return *(array+x*SECOND_DIM+y);
}
int main(int args, char *argv[]) {
if(!argv[0]) return 0;
array = malloc(args*SECOND_DIM*sizeof(int));
for(int i=0;i<args; i++) {
for(int j=0;j<SECOND_DIM; j++)
*(array+(i*SECOND_DIM)+j) = (i+1)*100+j;
}
printf("array[0][0]: %d\n", foo(array,0,0)); // array[0][0]
printf("array[0][1]: %d\n", foo(array,0,1)); // array[0][1]
free(array);
}
int (*array)[2] = malloc(sizeof(int[numberofargs][2]));
And then when you're finished with it:
free(array);

Weird issue when making an array of random ints in C

I am currently learning C and I need to write a function to create an array of random integers. I've hit a problem where after creating I try to print and it the first 8 numbers correctly but the rest don't.
int* create(int n) {
int* array = malloc(n);
if (!array) return NULL;
srand(time(NULL));
for (int i = 0; i < n; i++) {
array[i] = rand() % 100 + 1;
printf("num: %i\n", array[i]);
}
for (int i = 0; i < n; i++) {
printf("%i\n", array[i]);
}
return array;
}
Here is my output for this:
num: 39
num: 2
num: 15
num: 74
num: 80
num: 29
num: 14
num: 16
num: 8
num: 11
num: 2
39
2
15
74
80
29
14
16
973747761
909588276
2614
This memory allocation
int* array = malloc(n);
allocates not enough memory for an array with n elements of the type int, You have to write
int* array = malloc( n * sizeof( int ) );
Also the parameter should have unsigned integer type. Otherwise the user can pass a negative integer that will result in undefined behavior.
It is better to declare the parameter as having the type size_t. It is the type of the parameter of the function malloc.
And the function should do one thing: allocate and initialize an array. It is the caller of the function that will decide whether to output the array provided that the function did not return a null pointer.
So the function can look like
int * create( size_t n )
{
const int MAX_VALUE = 100;
int *array = malloc( n * sizeof( int ) );
if ( array != NULL )
{
srand( ( unsigned int )time( NULL ) );
for ( size_t i = 0; i < n; i++ )
{
array[i] = rand() % MAX_VALUE + 1;
}
}
return array;
}
Here is a demonstrative program.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int * create( size_t n )
{
const int MAX_VALUE = 100;
int *array = malloc( n * sizeof( int ) );
if ( array != NULL )
{
srand( ( unsigned int )time( NULL ) );
for ( size_t i = 0; i < n; i++ )
{
array[i] = rand() % MAX_VALUE + 1;
}
}
return array;
}
int main(void)
{
size_t n = 0;
printf( "Enter the size of an array: " );
scanf( "%zu", &n );
int *array = create( n );
if ( array != NULL )
{
for ( size_t i = 0; i < n; i++ )
{
printf( "%d ", array[i] );
}
putchar( '\n' );
}
free( array );
return 0;
}
Its output might look like
Enter the size of an array: 10
75 36 30 75 53 49 42 52 61 9
Though it is better to declare the function such a way that the user can determine the maximum value himself. That is the function can look like
int * create( size_t n, int max_value )
{
int *array = malloc( n * sizeof( int ) );
if ( array != NULL )
{
srand( ( unsigned int )time( NULL ) );
for ( size_t i = 0; i < n; i++ )
{
array[i] = rand() % max_value + 1;
}
}
return array;
}
Issues with your code:
malloc expects a size_t, you are directly giving an int. So you should technically do:
int *array = malloc(sizeof(int) * n);
This basically says that allocate n blocks of sizeof(int) bytes each.
What you are doing is allocating n bytes of data. The program is not guaranteed to run always and you are running out of bounds. If you were lucky you would get a Segmentation Fault in one of the runs.
You aren't allocating enough space. malloc(n) allocates n bytes. You need space for n ints! Use malloc(n * sizeof(int)), or more preferably: malloc(n * sizeof(*array)) (so you don't need to repeat the type) instead.

free() in dynamic memory

Do I use correctly free() in the code below? Is it a memory leak? Is it a problem use free() in the main part and not in the function? If yes there is a method to free in the function and not in main?
This code copy an array in another one.
int *copy(const int *arr,int n);
int main(){
int *p_arr1,*p_arr2;
int n,i;
printf("Insert size of array: ");
scanf("%d",&n);
p_arr1 = calloc(n,sizeof(int));
for(i=0;i<n;i++){
printf("Insert element %d of the array: ",i+1);
scanf("%d",p_arr1+i);
}
p_arr2 = copy(p_arr1,n);
for(i=0;i<n;i++){
printf("%d ",*p_arr2);
p_arr2++;
}
free(p_arr1);
free(p_arr2);
return 0;
}
int *copy(const int *arr,int n){
int i;
int *new;
new = calloc(n, sizeof(int));
for(i=0;i<n;i++){
new[i] += arr[i];
}
return new;
}
As long as you have the pointer returned by malloc (or in your case calloc) you can pass it to free when and wherever you want, it doesn't have to be in the same function.
However, after the loop where you print the contents of p_arr2, you no longer have the pointer returned by calloc inside the function, because you modify the pointer in the loop.
You need to use a temporary pointer variable for the loop:
int *p_arr2_tmp = p_arr2;
for (size_t i = 0; i < n; ++i)
{
printf("%d ", *p_arr2_tmp);
++p_arr2_tmp;
}
// Now we can free the memory pointed to by the original p_arr2 pointer
free(p_arr2);
Or you could use simple array indexing instead:
for (size_t i = 0; i < n; ++i)
{
printf("%d ", p_arr2[i]);
}
// The pointer p_arr2 wasn't modified, so it can be passed to free
free(p_arr2);
In this loop
for(i=0;i<n;i++){
printf("%d ",*p_arr2);
p_arr2++;
}
the value of the pointer p_arr2 is being changed, So using the changed pointer in a call of free results in undefined behavior.
You should write
for(i=0;i<n;i++){
printf("%d ", p_arr2[i] );
}
Also it is unclear why you are using the compound operator += in the function instead of the operator =.
new[i] += arr[i];
The function can be defined the following way
int * copy( const int *arr, size_t n )
{
int *new_arr = malloc( n * sizeof( int ) );
if ( new_arr != NULL )
{
memcpy( new_arr, arr, n * sizeof( int ) );
}
return new_arr;
}
If you want to use a pointer in the loop that outputs the newly created array then it can look the following way
for ( const int *p = p_arr2; p != p_arr2 + n; ++p )
{
printf( "%d ",*p );
}
putchar( '\n' );
If the aim is to write a program that uses only pointers and excludes using of the subscript operator and indices then your program can look the following way
#include <stdio.h>
#include <stdlib.h>
int * copy( const int *arr, size_t n )
{
int *new_arr = malloc( n * sizeof( int ) );
if ( new_arr != NULL )
{
for ( int *p = new_arr; p != new_arr + n; ++p )
{
*p = *arr++;
}
}
return new_arr;
}
int main(void)
{
size_t n;
printf( "Insert size of array: " );
scanf( "%zu", &n );
int *p_arr1 = calloc( n, sizeof( int ) );
for ( int *p = p_arr1; p != p_arr1 + n; ++p )
{
printf( "Insert element %d of the array: ", ( int )( p - p_arr1 + 1 ) );
scanf( "%d", p );
}
int *p_arr2 = copy( p_arr1, n );
if ( p_arr2 != NULL )
{
for ( const int *p = p_arr2; p != p_arr2 + n; ++p )
{
printf( "%d ",*p );
}
putchar( '\n' );
}
free( p_arr2 );
free( p_arr1 );
return 0;
}
The program output might look like
Insert size of array: 10
Insert element 1 of the array: 0
Insert element 2 of the array: 1
Insert element 3 of the array: 2
Insert element 4 of the array: 3
Insert element 5 of the array: 4
Insert element 6 of the array: 5
Insert element 7 of the array: 6
Insert element 8 of the array: 7
Insert element 9 of the array: 8
Insert element 10 of the array: 9
0 1 2 3 4 5 6 7 8 9

Bucket Sort Seg Fault

I'm trying to implement a bucket sort using a resizable vector function that I made. The vector works fine, but I get a segmentation fault anytime I try to run my sort function. Can anyone help me remedy this?
Notes about code: K=# of buckets in this case 10. find_max and find_min do exactly what you'd expect. vector_int_construct initializes an array and vector_int_push_back pushes integers to the end of the array. vector_int_sort just calls on a merge_sort function I created that also works fine on its own.
typedef struct {
size_t size;
size_t maxsize;
int* array;
}
vector_int_t;
void bucket_sort( int* a, size_t size )
{
int min = find_min( a, size );
int max = find_max( a, size );
size_t range = (( max - min ) / K );
vector_int_t buckets[K];
for( size_t i = 0; i < K; i++ ) {
vector_int_construct( &buckets[i] );
for( size_t j = 0; j < range; j++ ) {
vector_int_push_back( &buckets[i], a[j] );
}
}
for( size_t i = 0; i < K; i++ ) {
vector_int_sort( &buckets[i] );
}
size_t cnt = 0;
while( cnt != size ) {
for( size_t i = 0; i < K; i++ ) {
for( size_t j = 0; j < vector_int_size( &buckets[i] ); j++ ) {
a[cnt] = buckets[i].array[j];
cnt++;
}
}
}
}
int main()
{
size_t size = 4;
int a[] = { 19, 95, 4, 23 };
// Print out array before
printf( "Before sorting: " );
ece2400_print_array( a, size );
// Call sort
bucket_sort( a, size );
// Print out array after
printf( "After sorting: " );
ece2400_print_array( a, size );
return 0;
}

Remove even numbers from array in c

Hello i'm trying for about 2 hours to create a program which will remove even numbers from a dinamyc allocated array(with malloc)in c.Can somebody help me with some tips or create the code.
p.s. this is my first topic here, so feel free to give me some tips about how to correctly post a qustion.
Let's assume that you already allocated dynamically an array of n elements and initialized it.
In this case the function that removes elements with even values can look the following way
size_t remove_even( int *a, size_t n )
{
size_t m = 0;
for ( size_t i = 0; i < n; i++ )
{
if ( a[i] % 2 != 0 )
{
if ( i != m ) a[m] = a[i];
++m;
}
}
return m;
}
It can be called the following way
size_t m = remove_even( p, n );
for ( size_t i = 0; i < m; i++ ) printf( "%d ", a[i] );
printf( "\n" );
where p is the pointer to your dynamically allocated array of n elements.
The function actually removes nothing. It simply moves odd elements to the beginning of the array.
You can then use standard C function realloc to delete physically the removed elements.
For example
int *tmp = realloc( p, m * sizeof( int ) );
if ( tmp != NULL ) p = tmp;
Here is a demonstrative program
#include <stdlib.h>
#include <stdio.h>
size_t remove_even( int a[], size_t n )
{
size_t m = 0;
for ( size_t i = 0; i < n; i++ )
{
if ( a[i] % 2 != 0 )
{
if ( i != m ) a[m] = a[i];
++m;
}
}
return m;
}
#define N 10
int main( void )
{
int *a = malloc( N * sizeof( int ) );
for ( size_t i = 0; i < N; i++ ) a[i] = i;
for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
printf( "\n" );
size_t m = remove_even( a, N );
int *tmp = realloc( a, m * sizeof( int ) );
if ( tmp != NULL ) a = tmp;
for ( size_t i = 0; i < m; i++ ) printf( "%d ", a[i] );
printf( "\n" );
free( a );
}
Its output is
0 1 2 3 4 5 6 7 8 9
1 3 5 7 9
There are some things which you need to check before you try to code something, but I see that there is no code which you showed use.
SO is not a tutorial site, so this means that you should show us some code which actually does compile and ask here if there are some problems with that code.
Any way until than, this code should give you an Idea about how to check if a Number is odd or even:
#include<stdio.h>
#include<stdlib.h>
int main(void){
int n;
printf("Enter an integer:> ");
if((scanf("%d", &n)) != 1){
printf("Error, Fix it!\n");
exit(1);
}
if (n%2 == 0){
printf("Even\n");
}else{
printf("Odd\n");
}
return 0;
}
The whole story here is not about checking if Numbers inside an Array are odd or even, is about to find a way to check if a number is odd or even and only then you should check if inside that array there are odd or even numbers. I hope you understand my point.
One easy way to remove even numbers from an array in C is to create a new array of all odd elements starting from 1 to the maximum element present in the original array and then compare the original array and odd elements array (and do intersection) and put it in another array with same elements present in both arrays.
Here is the program:
#include<stdio.h>
int main(){
int a[20],n,i,max,j,k=0,l=0;
printf("enter limit of array ");
scanf("%d",&n);
printf("enter the elements ");
for (i=0;i<n;i++){
scanf("%d",&a[i]);
}
max=a[0];
for (i=0;i<n;i++){
if (a[i]>max){
max=a[i];
}
}
int b[max],c[n],count=0;
for (j=2;j<=max;j=j+2){
c[k++]=j;
count++;
}
for (i=0;i<n;i++){
for (j=0;j<count;j++){
if (a[i]==c[j])
b[l++]=a[i];
}
}
for (i=0;i<count;i++){
printf("%d ",b[i]);
}
return 0;
}

Resources