Create a function to copy n char like strcpy in C - c

#include <stdio.h>
#include <stdlib.h>
void nhap(char* &scr, int *n)
{
do
{
printf("Input the string length:\n");
scanf_s("%d", n);
} while (n < 0);
scr = (char*)malloc(*n * sizeof(char));
for (int i = 0; i < *n; i++)
{
scanf_s("%c", (scr + i));
}
}
void xuat(char* scr, int n)
{
printf("\nThe content of string: ");
for (int i = 0; i < n; i++)
{
printf("%c", *(scr + i));
}
}
char* StringNCopy(char* dest, char* scr, int n)
{
if (n == NULL)
{
return NULL;
}
dest = (char*)realloc(dest, n * sizeof(char));
for (int i = 0; i < n; i++)
{
for (int j = *(scr + n); j > 0; j--)
{
*(dest + i) = *(scr + j);
}
}
*(dest + n) = '\0';
return dest;
}
void main()
{
char *a;
char *b=NULL;
int n;
nhap(a, &n);
xuat(a, n);
StringNCopy(b, a, 4);
printf("%s", *b);
free(a);
}
Excuse me, I have a problem, I want to create a function likes strcpy but there is some errors I can't fix by myself. I think it will copy n elements from char* scr to char* dest, but when I run my code, it crashed. Can you help me to fix the code and explain to me. I'm very thankful.

The for loops should be in this way
for (int i = 0; i < n; i++)
{
*(dest + i) = *(scr + i);
}
You dont need nested for loops for this, because you just need to traverse the array once and copy the values.
Corrected program
#include <stdio.h>
#include <stdlib.h>
void nhap(char* &scr, int *n)
{
do
{
printf("Input the string length:\n");
scanf("%d", n);
} while (n < 0);
scr = (char*)malloc((*n+1) * sizeof(char)); //allocated size should be n+1
fflush(stdin);
for (int i = 0; i < *n; i++)
{
scanf("%c", (scr+i ));
}
}
void xuat(char* scr, int n)
{
printf("\nThe content of string: ");
for (int i = 0; i < n; i++)
{
printf("%c", *(scr + i));
}
}
void StringNCopy(char* &dest, char* &scr, int n) //no need to return the string aas you can pass it as reference
{
if (n == NULL)
{
return;
}
dest = (char*)realloc(dest, (n+1) * sizeof(char)); //alloted size should be n+1
for (int i = 0; i < n; i++)
{
*(dest + i) = *(scr + i); //no need of nested loops
}
*(dest + n) = '\0';
}
int main()
{
char *a;
char *b=NULL;
int n;
nhap(a, &n);
xuat(a, n);
StringNCopy(b, a, 4);
printf("\n6%s", b);
free(a);
}
Tested and working fine.Observe the errors mentioned in comments

Related

Delete elements from an input array

The question is how to delete elements whichs their values equal to an integer x.
In c++, i'm using reference and it works ok, but then when i changed to C, it can't release output.
Here is my code.
Please let me know what I'm wrong, thank you guys !
#include <stdio.h>
#include <conio.h>
void Input_array(int a[], int n)
{
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
}
void Output_array(int a[], int n)
{
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
}
int find_pos(int a[], int n, int x)
{
for (int i = 0; i < n; i++)
{
if (a[i] == x)
{
return i;
}
}
return -1;
}
void delete_pos(int a[], int *n, int pos)
{
int cnt=0;
for (int i = pos; i < *n - 1; i++)
//{
a[i] = a[i + 1];
*n=*n-1;
}
void delete_elmts(int a[], int *n, int x){
for(int i=0; i<n;){
if (a[i]==x)
{
delete_pos(a, *n, i);
}
else
i++;
}
}
int main()
{
int n, x;
scanf("%d%d", &n, &x);
int a[n];
Input_array(a, n);
delete_elmts(a, &n, x);
Output_array(a, n);
}
Use the correct types
Use standard functions like memcpy or memmove as they are much more efficient
void Input_array(size_t size, int *arr)
{
for (size_t i = 0; i < size; i++)
arr[i] = i;
}
void Output_array(size_t size, int *arr)
{
for (size_t i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
size_t delete_pos(const size_t size, const size_t pos, int *arr)
{
size_t newsize = size;
if(arr && size && pos < size)
{
memmove(arr + pos, arr + pos + 1, sizeof(*arr) * (size - pos));
newsize--;
}
return newsize;
}
size_t delete_elmts(const size_t size, const size_t pos, size_t nelements, int *arr)
{
if(arr && nelements && pos < size - 1)
{
if(pos + nelements > size) nelements = size - pos;
memmove(arr + pos, arr + pos + nelements, sizeof(*arr) * (size - pos - nelements));
}
return size - nelements;
}
#define SIZE 10
int main()
{
size_t size = SIZE;
int a[SIZE];
for(size_t i = 0; i < SIZE + 2; i ++)
{
Input_array(SIZE, a);
size = delete_pos(SIZE, i, a);
Output_array(size, a);
}
for(size_t i = 0; i < SIZE + 2; i ++)
{
for(size_t len = 0; len < SIZE + 1; len++)
{
printf("pos = %2zu, len = %2zu: ", i, len);
Input_array(SIZE, a);
size = delete_elmts(SIZE, i, len, a);
Output_array(size, a);
}
printf("\n");
}
}

Why this C-Program for selection sort gives wrong output?

This program for selection sort gives unfavorable output, I tried a lot but unable to find my mistake, The output, I'm getting through this is not sorted, one or more elements are at wrong position(or they are not sorted)...Please help me to find my mistake.
#include <stdio.h>
void swap(int *p1, int *p2)
{
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
int *get_least(int *p, int i, int count)
{
int temp = *(p + i), key = 0;
int *index;
for (i; i < count; i++)
{
if (temp > *(p + i))
{
temp = *(p + i);
index = (p + i);
key++;
}
}
if (key == 0)
{
return (p + 1);
}
return (index);
}
void sel_sort(int *p, int count)
{
for (int i = 0; i < count - 1; i++)
{
swap((p + i), get_least(p, i, count));
}
}
int main()
{
int num[10], count;
printf("ENTER INPUT LIMIT:\n");
scanf("%d", &count);
printf("ENTER YOUR NUMBERS:\n");
for (int i = 0; i < count; i++)
{
scanf("%d", &num[i]);
}
sel_sort(num, count);
printf("OUTPUT AFTER SORTING:\n");
for (int i = 0; i < count; i++)
{
printf("%d ", num[i]);
}
return (0);
}
I'm getting this output:
As you mentioned in comments, You want to return address. now, When you return (p+i) as an address, Your i value get changed and holds the last incremented value from for loop, so the returned address is diffrent from what You supposed to return.

C: Why doesn't this code work?

Need help with this code it should return c[] with the number's of a[] % b[] = 0 but it doesn't work.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int *divide(int a[], int a_size, int b[], int b_size)
{
int i = 0, j = 0, k = 0, counter = 0, *c;
c = (int*)malloc(b_size * sizeof(int));
for (i = 0; i < b_size; i++)
{
for (j = 0; j < a_size; j++)
{
if (a[j] % b[i] == 0)
counter++;
}
c[k] = counter;
k++;
counter = 0;
}
for (int t = 0; t < b_size; t++)
{
printf("%d ", c[t]);
}
printf("\n");
}
main ()
{
int *a, *b, a_size, b_size;
printf("Enter size of a:\n");
scanf ("%d", &a_size);
a = (int*)malloc(a_size * sizeof(int));
printf("\nEnter size of b:\n");
scanf("%d", &b_size);
b = (int*)malloc(b_size * sizeof(int));
printf("\nEnter elements of a:\n");
for (int i = 0; i < a_size; i++)
{
scanf("%d", &a[i]);
}
printf("\nEnter elements of b:\n");
for (int j = 0; j < b_size; j++)
{
scanf("%d", &b[j]);
}
divide(&a, a_size, &b, b_size);
}
There was some errors in your code.
You want your fonction *divide(...) to return a new array containing the operation a[i] % b[i], but your function doesn't return anything, so you have to return it. It seems more logical to print the new array in the main, than in the function while doing it.
When you pass the variables to your function be careful to pass int*, not int **.
Here is a sample of code which works (you didn't say what to do if a_size and b_size were different so I assume we only use the smallest size and don't treat the number after) :
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int *divide(int a[], int a_size, int b[], int b_size)
{
int i = 0, stop, *c;
if (b_size <= a_size)
{
c = (int*)malloc(b_size * sizeof(int));
stop = b_size;
}
else
{
c = (int*)malloc(a_size * sizeof(int));
stop = a_size;
}
while (i < stop)
{
c[i] = a[i] % b[i];
i++;
}
return (c);
}
int main ()
{
int *a, *b, a_size, b_size;
int *result = NULL;
int stop;
int i = 0;
printf("Enter size of a:\n");
scanf ("%d", &a_size);
a = (int*)malloc(a_size * sizeof(int));
printf("\nEnter size of b:\n");
scanf("%d", &b_size);
b = (int*)malloc(b_size * sizeof(int));
printf("\nEnter elements of a:\n");
for (int i = 0; i < a_size; i++)
{
scanf("%d", &a[i]);
}
printf("\nEnter elements of b:\n");
for (int j = 0; j < b_size; j++)
{
scanf("%d", &b[j]);
}
result = divide(a, a_size, b, b_size); //not &a neither &b because it would be a char** instead of a char*
if (a_size < b_size)
stop = a_size;
else
stop = b_size;
while (i < stop)
{
printf("%d ", result[i]);
i++;
}
return 0;
}

free() crashes the code

#include <stdio.h>
#include <stdlib.h>
void printingArr(int** arr, int rows);
void sortingEachOneOfThem(int** pArr, int rows);
void sortingTheWholeArray(int** pArr, int rows);
void bubbleSort(int* arr);
void freeArray(int **a, int m);
int main(void)
{
int** pArr = 0;
int numOfRows = 0;
int sizes = 0;
printf("Enter number of rows: ");
scanf("%d", &numOfRows);
pArr = (int**) malloc(sizeof(int*) * numOfRows);
if (pArr == NULL)
{
printf("Unsuccessful malloc!\n");
return 1;
}
for (int i = 0; i < numOfRows; i++)
{
printf("Enter array length for row %d: ",i);
scanf("%d", &sizes);
pArr[i] = (int*) malloc(sizeof(int) * sizes + 1);
if (pArr[i] == NULL)
{
printf("Unsuccessful malloc!\n");
return 1;
}
pArr[i][0] = sizes;
for (int k = 1; k < sizes + 1; k++)
{
printf("Enter value for array: ");
scanf("%d", &pArr[i][k]);
}
}
printingArr(pArr, numOfRows);
sortingEachOneOfThem(pArr, numOfRows);
printingArr(pArr, numOfRows);
sortingTheWholeArray(pArr, numOfRows);
printingArr(pArr, numOfRows);
for (int i = 0; i < numOfRows; i++)
{
if (pArr[i] != NULL)
{
free(*(pArr + i));
}
}
//free(pArr);
system("pause");
return 0;
}
/*
this amazing, wonderfull piece of program prints the array given
input: int** arr, int rows
output: none
*/
void printingArr(int** arr, int rows)
{
int i = 0;
int k = 0;
for (i = 0; i < rows; i++)
{
for (k = 0; k <= arr[i][0]; k++)
{
printf("%d ", arr[i][k]);
}
printf("\n");
}
printf("\n");
}
/*
This beautiful function sorts the whole array, but its length of rows like a pyramid
input: int** arr, int rows
output: none
*/
void sortingTheWholeArray(int** pArr, int rows)
{
int* temp = 0;
int i = 0, k = 0;
for (i = 0; i < rows - 1; i++)
{
for (k = 0; k < rows - 1; k++)
{
if (pArr[k][0] > pArr[k + 1][0])
{
temp = pArr[k];
pArr[k] = pArr[k + 1];
pArr[k + 1] = temp;
}
}
}
}
/*
This little small function sorts every row of the array of arrays given to it
input: int** arr, int rows
output: none
*/
void sortingEachOneOfThem(int** pArr, int rows)
{
int i = 0;
for (i = 0; i < rows; i++)
{
bubbleSort(pArr[i]);
}
}
/*
This little piece of a code is a bubble sort, sorts the array given to it :)
input: int* arr, int rows
output: none
*/
void bubbleSort(int* arr)
{
int i = 1, k = 0;
for (i = 1; i < arr[0] - 1; i++)
{
for (k = 1; k <= arr[0] - i; k++)
{
if (arr[k] > arr[k + 1])
{
arr[k] += arr[k + 1];
arr[k + 1] = arr[k] - arr[k + 1];
arr[k] -= arr[k + 1];
}
}
}
}
the free at the end crashes my code, showing this error:
https://i.stack.imgur.com/nqxBG.png
the same usage of the function free() on another code worked good, but not here. I have tried running through it in step by step mode, it crashes at the first free. Dr. memory shows this: https://i.stack.imgur.com/rSZJr.png
another link: https:// i.stack. imgur.com/ZX2Ne.png (paste it without the spaces in the middle, Can't post more than 2 links)
what can I do?
This:
pArr[i] = (int*) malloc(sizeof(int) * sizes + 1);
under-allocates. Adding a single byte to the size of an array of int makes little sense. You probably meant:
pArr[i] = malloc((sizes + 1) * sizeof *pArri[i]);
Don't cast the return value of malloc(), and use sizeof on the left-hand side.

Trying to implement a word search in C

As the title says, I'm trying to make a word search in C. However, when I run what I have, I'm getting an aborted(core dumped) message.
My code:
void lefttoright(int rowcol, char **matrix, char* find){
int i, j, k, q, len, count = 0;
len = strlen(find);
for (i = 0; i < rowcol; i++){
for (j = 0; j < rowcol; j++){
if (matrix[i][j] == find[0]){
char* correct = malloc(sizeof(char) * 20);
for (q = j; q < rowcol; q++){
for (k = 0; k < len; k++){
if (matrix[i][q] == find[k]){
correct[k] = matrix[i][q];
}
}
if (strcmp(correct, find) == 0){
count++;
printf("%s\n", correct);
printf("%d\n", count);
}
}
free(correct);
}
else continue;
}
}
printf("%d", count);
}
.
if (strcmp(correct, find) == 0){
count++;
printf("%s\n", correct);
printf("%d\n", count);
}
prints
bagel
1
bagel
2
bagel
3
bagel
4
bagel
5
bagel
6
bagel
7
bagel
8
bagel
9
bagel
10
bagel
11
bagel
12
bagel
13
Aborted (core dumped)
What is making it abort? Also, what do I need to do differently to make count == 1 (the word only appears once)?
My entire program if needed:
#include <stdio.h>
#include <stdlib.h>
#include "scanner.h"
#include <string.h>
#include <ctype.h>
char** matrixMaker(int argc, char **argv);
void displayMatrix(int rowcol, char **matrix);
void lefttoright(int rowcol, char **matrix, char* find);
int main(int argc, char **argv){
FILE *fp = fopen(argv[2], "r");
int rowcol = atoi(argv[1]);
int a, i = 0, j;
unsigned char cha;
char **matrix;
matrix = malloc( sizeof(char *) * rowcol);
for (a=0; a<20; a++)
matrix[a] = malloc( sizeof(char) * rowcol);
for (i = 0; i < rowcol; i++){
for (j = 0; j < rowcol; j++){
cha = tolower((unsigned char)readChar(fp));
matrix[i][j] = cha;
}
}
char* find = malloc(sizeof(char) * 20);
displayMatrix(rowcol, matrix);
printf("Enter a word to find in the puzzle : \n");
scanf("%s", find);
while(find[i]){
putchar(tolower((unsigned char)find[i]));
i++;
}
lefttoright(rowcol, matrix, find);
free(matrix);
return 0;
}
void displayMatrix(int rowcol, char **matrix){
int r,c;
for (r = 0; r < rowcol; ++r){
for (c = 0; c < rowcol; ++c){
printf("%c",matrix[r][c]);
}
printf("\n");
}
}
void lefttoright(int rowcol, char **matrix, char* find){
int i, j, k, q, len, count = 0;
len = strlen(find);
for (i = 0; i < rowcol; i++){
for (j = 0; j < rowcol; j++){
if (matrix[i][j] == find[0]){
char* correct = malloc(sizeof(char) * 20);
for (q = j; q < rowcol; q++){
for (k = 0; k < len; k++){
if (matrix[i][q] == find[k]){
correct[k] = matrix[i][q];
}
}
if (strcmp(correct, find) == 0){
count++;
printf("%s\n", correct);
printf("%d\n", count);
}
}
free(correct);
}
else continue;
}
}
printf("%d", count);
}

Resources