Storing **array into another array (function) in C - c

My task is to enter a sentence and every 2nd word is to be stored into a second array. I managed to send the array into a function, but now I don't know how to store words with strcpy.
First array is mat1 and second array is mat2.
void function(char **mat1, char *mat2, int n, int *j)
{
int i, j2=0;
printf("\n");
for(i=0;i<n;i++)
{
printf("%s ", mat1[i]);
printf("\n");
if(i==0 || i%2==0)
{
mat2[j2]=(char*)malloc(10);
strcpy(&mat2, mat1);
j2++;
}
}
}
In main, I did this:
char *mat1[10], mat2[10], mat3[10];
mat1[i]=(char*)malloc(10);
scanf("%s", mat1[i]);
function( mat1,&mat2[0], n, &j);
I'm not sure if I need to malloc mat2 and then to do something with strcpy. I need to return mat2 and printf words in main.

Firstly you should change type types of mat2 to which are similar to ones of mat1.
Then, allocate buffers and copy strings using array access to their elements.
void function(char **mat1, char **mat2, int n, int *j)
{
int i, j2=0;
printf("\n");
for(i=0;i<n;i++)
{
printf("%s ", mat1[i]);
printf("\n");
if(i==0 || i%2==0)
{
mat2[j2]=(char*)malloc(10);
strcpy(mat2[j2], mat1[i]);
j2++;
}
}
*j = j2; /* probably you want this */
}
char *mat1[10], *mat2[10], mat3[10];
function( mat1, mat2, n, &j);

Related

Two array merge into a third array in c

For some Reason the Program Crashes at the Loop used to merge the two arrays in main.
though maybe this question is a foolish in one(idk it didn't allow me to post as my program is mostly code so now i am blabbering).
(Well it still doesn't so here's a Picture of a Cat
CAT )
//To make two arrays of user Defined Size and merge them in a third array
#include<stdio.h>
#include<stdlib.h>
void array(int**,int);
void ini(int**,int);
void display(int **,int);
int main()
{
int *a1,*a2,*a3,s1,s2,i,j;
printf("Enter Size of Array 1\n");
scanf("%d",&s1);
printf("Enter Size of Array 2\n");
scanf("%d",&s2);
ini(&a1,s1);
ini(&a2,s2);
ini(&a3,s1+s2);
printf("Enter Elements of Array 1\n");
array(&a1,s1);
printf("Array 1:\n");
display(&a1,s1);
printf("Enter Elements of Array 2\n");
array(&a2,s2);
printf("Array 2:\n");
display(&a2,s2);
for(i=0;i<s1;i++)
{
a3[i]=a1[i];
}
for(i=0,j=s1;i<s2&&j<s1+s2;i++,j++)
{
a3[j]=a2[i];
}
printf("Merged Array:\n");
display(&a3,s1+s2);
return 0;
}
void ini(int **a,int s)
{
*a=(int*)calloc(s,sizeof(int));
}
void array(int **a,int s)
{
int i;
for(i=0;i<s;i++)
{
printf("Enter Element at position %d\n",i+1);
scanf("%d",&a[i]);
}
}
void display(int **a,int s)
{
int i;
for(i=0;i<s;i++)
{
if(i==s-1)
printf("%d\n",a[i]);
else
printf("%d\t",a[i]);
}
}
a1, a2, and a3 is a pointer of an integer type variable, which stores the starting address of your buffer.
a1[index] is the value in the address of a1 with 'index' as the offset.
Since you were passing &a to your array() and display() function, you were passing the address of your variable into the function instead of passing the address of your buffer.
You could change your array() and display() to:
void array(int *a,int s)
{
int i;
for(i=0;i<s;i++)
{
printf("Enter Element at position %d\n",i+1);
scanf("%d", &(a[i]));
}
}
void display(int *a,int s)
{
int i;
for(i=0;i<s;i++)
{
if(i==s-1)
printf("%d\n", a[i]);
else
printf("%d\t", a[i]);
}
}
and call it like this:
array(a1,s1);
display(a1,s1);

Accepting values of array in a function and using it in another function, How is this Works in C?

in a program to accept an array and display it on the console using functions getArray() and displayArray() how this program works as it Accepts values of array in function getArray() and uses it in the function displayArray() without returning any values from the first function?
I tried this program and failed to get result, then found this one in youTube comment section and I tried it and got results! I want to know how this program works ?
Q:Write a program to accept an array and display it on the console using function?
a.Program should contain 3 functions including main() function,
main() - {
Declare an array.
Call function getArray().
Call function displayArray() }.
getArray() -
Get values to the array.
displayArray() -
Display the array values
#include <stdio.h>
#include <stdlib.h>
void getArray(int);
void displayArray(int);
int main(void) {
int limit;
printf("Enter The Size of the Array :");
scanf("%d",&limit);
getArray(limit);
displayArray(limit);
return EXIT_SUCCESS;
}
void getArray(int limit){
int i,a[100];
printf("Enter The Values of Array :\n");
for(i=0;i<limit;i++){
scanf("%d",&a[i]);
}
}
void displayArray(int limit){
int i,b[100];
printf("Your Array is :\n");
for(i=0;i<limit;i++){
printf(" %d\t",b[i]);
}
printf("\n");
}
Array a in getArray is a local variable that gets destroyed when it goes out of scope. Array b in displayArray is also a local variable (local to displayArray) and has no relationship with a in getArray. You need to pass the same array to both functions.
One way could be to allocate the needed memory for the array in main and pass that, along with the number of elements in the array, to the two functions.
Example:
#include <stdio.h>
#include <stdlib.h>
// a is now a pointer to the first element in the array:
void getArray(int *a, int limit) {
printf("Enter The Values of Array :\n");
for(int i = 0; i < limit; i++) {
scanf("%d", &a[i]);
}
}
// b is now a pointer to the first element in the array:
void displayArray(int *b, int limit) {
printf("Your Array is :\n");
for(int i = 0; i < limit; i++) {
printf(" %d\t", b[i]);
}
putchar('\n');
}
int main(void) {
int limit;
printf("Enter The Size of the Array :");
if(scanf("%d", &limit) != 1 || limit < 1) return EXIT_FAILURE;
// allocate memory for `limit` number of `int`s:
int *arr = malloc(limit * sizeof *arr);
if(arr == NULL) return EXIT_FAILURE;
getArray(arr, limit); // pass arr + limit
displayArray(arr, limit); // pass arr + limit
free(arr); // and free the memory when done
return EXIT_SUCCESS;
}
#include<stdio.h>
void getArray(int);
void displayArray(int);
int array[100];
void main()
{
int limit;
printf("enter the array size you want\n");
scanf("%d",&limit);
getArray(limit);
displayArray(limit);
}
void getArray(int limit)
{
printf("enter the array element you want\n");
for(int i=0;i<limit;i++)
{
scanf("%d",&array[i]);
}
}
void displayArray(int limit)
{
for(int i=0;i<n;i++)
{
printf("%d",array[i]);
printf("\t");
}
}

How to pass arrays to a function in C

I am taking a number in the main function, make it an array in make_array function. In the palindrome function, I need to check the array which i made in the make_array function but it is not visible in the palindrome function.
How can I solve this problem?
#include<stdio.h>
#define N 5
void make_array(int n);
int palindrome(int ar[],int size);
int main()
{
int num;
printf("Enter a number to check: ");scanf("%d",&num);
make_array(num);
if(palindrome(/*Don't know what should I write here*/))
printf("It is palindrome");
else
printf("It is not palindrome");
}
void make_array(int n)
{
int arr[N];
int digit,i=0;
while(n>0){
digit=n%10;
arr[i]=digit;
n/=10;
i++;
}
printf("Array: ");
for(i=0; i<N; i++)
printf("%d ",arr[i]);
}
int palindrome(int ar[],int size)
{
int i,j;
int temp[N];
j=N;
for(i=0; i<N; i++)
temp[i]=ar[i];
for(i=0; i<N; i++){
if(temp[j-1]!=ar[i])
return 0;
j--;
}
return 1;
}
The best way is to leave allocation to the caller. Then you can simply do
int main()
{
int num;
printf("Enter a number to check: ");scanf("%d",&num);
int array[num];
fill_array(num, array);
where fill_array does what "make_array" does in your code, minus the allocation part.
void fill_array(int num, int array[num]);
The palindrome function could be rewritten similarly:
int palindrome(int size, int array[size])
All of this uses the concept of variable-length arrays (VLA).
I have done some modification in your code so please refer it.
#include<stdio.h>
#include "stdafx.h"
#define N 5
int make_array(int n, int *arr);
int palindrome(int ar[],int size);
int main()
{
int num;
int arr[N];
int iRet;
printf("Enter a number to check: ");scanf_s("%d",&num);
iRet = make_array(num, arr);
if(palindrome(arr, iRet))
printf("It is palindrome");
else
printf("It is not palindrome");
}
int make_array(int n, int *arr)
{
//int arr[N];
int digit,i=0;
while(n>0){
digit=n%10;
arr[i]=digit;
n/=10;
i++;
}
printf("Array: ");
for(int j=0; j<i; j++)
printf("%d ",arr[j]);
return i;
}
int palindrome(int ar[],int size)
{
int i,j;
int temp[N];
j=size;
for(i=0; i<size; i++)
temp[i]=ar[i];
for(i=0; i<size; i++){
if(temp[j-1]!=ar[i])
return 0;
j--;
}
return 1;
}
The problem is with your make array function. When a function is called, the stack grows down and registers and pointers are allocated to save the point from which that function was called, now, here you send n by value and your function creates a place on the stack for an array that you fill- BUT- when your function returns- the stack pointer returns back up to the caller( if your function has a return value it will be saved in a pre-allocated place, but other than that all of the other function data on stack is unavailable.).
So in general, if you want a function to create an array that could be used later on it must be allocated on heap you can either return int* or send foo(int**) to the function that will hold the add. of the new allocated array.
another option is to allocate that array[N] in your main, and send foo(int arr[], int n, size_t size) to the function. Since the array was allocated by the caller in main- this memory will be valid for all of the main function life.
so option 1)
int main()
{
int num;
int* array;
printf("Enter a number to check: ");scanf("%d",&num);
array = make_array(num, N);
if(palindrome(array, N))
printf("It is palindrome");
else
printf("It is not palindrome");
free(array); /*free heap allocation */
}
int* make_array(int n, size_t size)
{
int* arr;
int digit ,i=0;
arr = malloc(sizeof(int)*size);
if(NULL == arr)
{
return NULL; /* malloc failed*/
}
while(n>0 && i<size){
digit=n%10;
arr[i]=digit;
n/=10;
i++;
}
printf("Array: ");
for(i=0; i<N; i++)
printf("%d ",arr[i]);
return arr;
}
or 2)
int main()
{
int num;
int array[N];/*array saved on stack in main function */
printf("Enter a number to check: ");scanf("%d",&num);
make_array(array,num, N);
if(palindrome(/*Don't know what should I write here*/))
printf("It is palindrome");
else
printf("It is not palindrome");
}
void make_array(int* arr, int n, size_t size)
{
int digit,i=0;
if(NULL == arr)/*if arr is not a valid pointer*/
{
return;
}
while(n>0 && i<size){
digit=n%10;
arr[i]=digit;
n/=10;
i++;
}
printf("Array: ");
for(i=0; i<N; i++)
printf("%d ",arr[i]);
}

Passing a 2d array with pointers and accessing it gives segmentation fault

im trying to pass a 2D array from main to a function and trying to print it letter by letter
but it keeps giving me segmentation fault
note: the question im trying to solve as mentioned a function with parameter { ArrPrintMatrix(char *(p)[7]) }
so help me by keeping the above thing in mind
#include<stdio.h>
ArrPrintMatrix(char **p,int n) {
int i,j;
for(i=0;i<n;i++) {
for(j=0;j<10;j++) {
printf("%c ",p[i][j]);
}
}
}
main() {
int i;
char c[2][10];
puts("enter two strings");
for(i=0;i<2;i++)
scanf("%s",c[i]);
ArrPrintMatrix((char **) c,2);
}
You should use char p[2][10] not char** p
The following code could work:
#include <stdio.h>
void ArrPrintMatrix(char p[2][10], int n) {
int i;
for (i = 0; i < n; ++i)
printf("%s\n",p[i]);
}
int main() {
int i;
char c[2][10];
puts("enter two strings");
for(i=0;i<2;i++)
scanf("%s",c[i]);
ArrPrintMatrix(c,2);
return 0;
}
you need to change the type of the p var in the print function, and you should also set the array to zero so if the strings that are printing are less than 10 chars with terminator- garbage values are not displayed.
void ArrPrintMatrix(char p[][10],int n) {
int i,j;
for(i=0;i<n;i++) {
for(j=0;j<10;j++) {
printf("%c ",p[i][j]);
}
}
}
int main() {
int i;
char c[2][10]= {0};
puts("enter two strings");
for(i=0;i<2;i++)
scanf("%s",c[i]);
ArrPrintMatrix( c,2);
return 0;
}

How to update values of an array in C

Here's my problem :
I have a program where the user have to fill this :
a 2d array of a list of elements from which i can at most take one element ( we'll call it exclusionArr )
a 2d array of a list of elements from which i have to at least take one element ( we'll call it inclusionArr )
an array with the elements i have to keep ( we'll call it keepArr )
an array with the elements i can't use ( we'll call it throwArr )
Now on the first step i need to check if any row of exclusionArr contain an element of keepArr and if it does then i need to add every element of that row but that one in throwArr.
One row cannot contain more than one element of keepArr, i'll make a function to check for that and return an error if it is. ( you can at most keep one item from the rows of exclusionArr so having 2 elements of keepArr on the same row is a problem )
I need help to add element to an array, i can't seem to be able to store those values in my array (more like i don't really know how to, still new to C).
Here's the function i made so far :
void interdiction(int *throwArr[], int *throw_size, int keepArr[], int keep_size, int x, int y, int exceptionArr[x][y]) {
int i, j, k, count=0;
while(count<keep_size) {
for(i=0;i<x;i++) {
for(j=0;j<y;j++) {
if (exceptionArr[i][j] == keepArr[count]) {
for (k=0;k<y;k++) {
if(k!=j) {
printf("\nElement %d of exclusion %d inserted in throwArr",exceptionArr[i][k], i);
*throw_size+=1;
throwArr[*throw_size]=exceptionArr[i][k];
}
else printf("\nelement to keep found in exclusion %d in position %d", i, j);
}
}
}
}
count++;
}
}
I would like it to change the throwArr that i put in the function so that it adds on the already existing array every element on the current row except the element that's in keepArr.
I don't know if it's relevant or not but for throwArr when initializing it i allocate a lot of extra memory so i could perform changes without running out of space so i don't know if i need to realloc memory in the function for the changes done.
Any help would be greatly appreciated !
EDIT : Here's the full code
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
void interdiction(int *throwArr, int throw_size, int *keepArr, int keep_size, int x, int y, int exclusionArr[x][y]);
static int compare (void const *a, void const *b);
void noDuplicate( int arr[], int *size );
void xclusion_alloc (int x, int y, int(**aptr)[x][y]);
void xclusion_print (int x, int y, int array[x][y]);
void xclusion_fill (int x, int y, int array[x][y]);
void main(){
int throw_size, keep_size, rexc, lexc;
int i, j;
int nbObjets=7, *throwArr, *keepArr, (*exclusionArr)[rexc][lexc];
printf("\nHow many exclusions :");
scanf("%d", &rexc);
printf("\nHow many elements in each exclusion :");
scanf("%d", &lexc);
xclusion_alloc(rexc,lexc,&exclusionArr);
xclusion_fill(rexc,lexc,*exclusionArr);
xclusion_print(rexc,lexc,*exclusionArr);
printf("\nHow many elements do we have to keep :");
scanf("%d", &keep_size);
keepArr=malloc(nbObjets*sizeof(int));
printf("\nWhat are they :");
for(i=0;i<keep_size;i++){
scanf("%d",&keepArr[i]);
}
qsort(keepArr, keep_size, sizeof *keepArr, compare);
noDuplicate(keepArr, &keep_size);
printf("\nHow many elements we can't use :");
scanf("%d", &throw_size);
throwArr=malloc(nbObjets*sizeof(int));
printf("\nWhat are they :");
for(i=0;i<throw_size;i++){
scanf("%d",&throwArr[i]);
}
qsort(throwArr, throw_size, sizeof *throwArr, compare);
noDuplicate(throwArr, &throw_size);
interdiction(throwArr, throw_size, keepArr, keep_size, rexc, lexc, *exclusionArr);
printf("\nOur array of elements we can't use : ");
for (i=0;i<throw_size;i++){
printf("%d ", throwArr[i]);
}
}
static int compare (void const *a, void const *b){
int const *pa = a;
int const *pb = b;
return *pa - *pb;
}
void interdiction(int *throwArr, int throw_size, int *keepArr, int keep_size, int x, int y, int exclusionArr[x][y]){
int i, j, k, count=0;
while(count<keep_size){
for(i=0;i<x;i++) {
for(j=0;j<y;j++) {
if (exclusionArr[i][j] == keepArr[count]) {
for (k=0;k<y;k++){
if(k!=j){
printf("\nElement %d of exclusion %d inserted in the array of elements we can't use",exclusionArr[i][k], i);
throw_size+=1;
throwArr[throw_size]=exclusionArr[i][k];
}
else printf("\nelement to keep found in exclusion n°%d in position %d", i, j);
}
}
}
}
count++;
}
}
void noDuplicate( int arr[], int *size ) {
int i=0, j=0;
for (i = 1; i < *size; i++) {
if (arr[i] != arr[j]) {
j++;
arr[j] = arr[i];
}
}
*size = (j + 1);
}
void xclusion_alloc (int x, int y, int(**aptr)[x][y]) {
*aptr = malloc( sizeof(int[x][y]) );
assert(*aptr != NULL);
}
void xclusion_fill (int x, int y, int array[x][y]) {
int i, j;
for(i=0; i<x; i++) {
for(j=0; j<y; j++) {
scanf("%d", &array[i][j]);
}
}
}
void xclusion_print (int x, int y, int array[x][y]) {
int i,j;
for(i=0; i<x; i++) {
printf("\nExclusion n°%d :", i);
printf(" { ");
for(j=0; j<y; j++) {
printf("%d ", array[i][j]);
}
printf("}");
printf("\n");
}
}
Sadly the output i'm getting is like this :
How many exclusions :3
How many elements in each exclusion :2
5 3
2 7
4 1
Exclusion n░0 : { 5 3 }
Exclusion n░1 : { 2 7 }
Exclusion n░2 : { 4 1 }
How many elements do we have to keep :1
What are they :5
How many elements we can't use :1 2
What are they :
element to keep found in exclusion n░0 in position 0
Element 3 of exclusion 0 inserted in the array of elements we can't use
Our array of elements we can't use : 2
I managed to make it work by making the following changes to my function :
void interdiction(int **throwArr, int *throw_size, int *keepArr, int keep_size, int x, int y, int exclusionArr[x][y]){
int i, j, k, count=0;
while(count<keep_size){
for(i=0;i<x;i++) {
for(j=0;j<y;j++) {
if (exclusionArr[i][j] == keepArr[count]) {
for (k=0;k<y;k++){
if(k!=j){
printf("\nElement %d of exclusion %d inserted in the array of elements we can't use",exclusionArr[i][k], i);
(*throwArr)[*throw_size]=exclusionArr[i][k];
*throw_size+=1;
}
else printf("\nelement to keep found in exclusion n°%d in position %d", i, j);
}
}
}
}
count++;
}
}
Okay I think you need to change those lines as following. Also you made a mistake when you were testing your program.
void interdiction(int *throwArr, int throw_size, int *keepArr, int *keep_size, int x, int y, int exclusionArr[x][y]);
interdiction(throwArr, throw_size, keepArr, &keep_size, rexc, lexc, *exclusionArr);
void interdiction(int *throwArr, int throw_size, int *keepArr, int *keep_size, int x, int y, int exclusionArr[x][y]) {
...
throwArr[*throw_size]=exclusionArr[i][k]; // these two lines switched order
*throw_size+=1;
...
}

Resources