equating addresses of a 2d array and a 1d array in c - c

This prog is to accept an array of chars n compress them....(aaaabbbcc-->a4b3c2)....my prog is showing error at the point where im equating the addr of the 2d array to 1d array. This is my code:
/* size1 defined as 5 and size2 as 10.... (consts)*/
void compress(char data[SIZE1][SIZE2]);
int main()
{
char data[SIZE1][SIZE2];
printf("Enter a 5x10 matrix of characters:\n");
scanf("%c", &data);
compress(data[SIZE1][SIZE2]);
_getch();
return 0;
}
void compress(char data[SIZE1][SIZE2])
{
int hold[SIZE1*SIZE2];
int cnt = 0;
hold[SIZE1*SIZE2] = data[SIZE1][SIZE2];
for (int i = 0; i < (SIZE1*SIZE2); i++)
{
if (hold[i] == hold[i + 1])
{
cnt++;
continue;
}
else
{
printf("%c%d", hold[i], cnt);
}
}
}
This didn't work so I tried to use pointers:
void compress(char data[SIZE1][SIZE2])
{
int *hold[SIZE1*SIZE2];
int cnt = 0;
hold = data[SIZE1][SIZE2];
for (int i = 0; i < (SIZE1*SIZE2); i++)
{
if (*(hold+i) == *(hold+i+1))
{
cnt++;
}
else
{
printf("%c%d", *(hold+i), cnt);
}
}
}
I thought that the addrs of 2d arrays are stored linearly, hence they can be directly =to that of 1d.But the error says "'=':left operand must be an l-value".Im very new to pointers.Any help or corrections ....pls?

#include <stdio.h>
#define SIZE1 3
#define SIZE2 3
void compress(char data[SIZE1][SIZE2]);
int main(){
char data[SIZE1][SIZE2];
printf("Enter a %dx%d matrix of characters:\n", SIZE1, SIZE2);
for(int i=0;i<SIZE1;++i)
for(int j=0;j<SIZE2;++j)
scanf("%c", &data[i][j]);//aaaabbbcc
compress(data);
(void)getchar();
return 0;
}
void compress(char data[SIZE1][SIZE2]){
char *hold = &data[0][0];
int cnt = 1, size = SIZE1*SIZE2;
for (int i = 0; i < size; i++){
if (i < size -1 && hold[i] == hold[i + 1]){
cnt++;
//continue;
} else {
printf("%c%d", hold[i], cnt);//a4b3c2
cnt = 1;
}
}
}

Related

Why do i get segmentation fault 11?

Why do I get segmentation fault 11? I get it quite often, and I know this time it is about the function. If anyone can help, please do, the code is down below! I am trying to make a program, that WITH A FUNCTION, can rearrange an array in ascending order and then print it in main in reverse order.
#include "stdio.h"
void changxr(int *counter, int *arrsize, int *j, int *arr[]);
int main()
{
int a, i, j, counter;
int arrsize;
int arr[100];
printf("pick an arraysize: \n");
scanf("%d", &arrsize);
printf("type %d numbers \n", arrsize);
for (counter = 0; counter < arrsize; counter++)
{
scanf("%d", &arr[counter]);
}
for (int c = arrsize - 1; c >= 0; c--)
{
printf("%d ", arr[c]);
}
changxr(&counter, &arrsize, &j, &arr[&counter]);
for (counter = arrsize - 1; counter >= 0; counter--)
{
printf("%d ", arr[counter]);
}
}
void changxr(int *counter, int *arrsize, int *j, int *arr[])
{
int a;
for (*counter = 0; *counter < *arrsize; *counter++)
{
for (*j = *counter + 1; *j < *arrsize; *j++)
{
if (*arr[*counter] > *arr[*j])
{
a = *arr[*counter];
*arr[*counter] = *arr[*j];
*arr[*j] = a;
}
}
}
}
New code:
#include "stdio.h"
void changxr(int arrsize, int *arr[]);
int main()
{
int a, i, j, counter;
int arrsize;
int arr[100];
printf("pick an arraysize: \n");
scanf("%d", &arrsize);
printf("type %d numbers \n", arrsize);
for (counter = 0; counter < arrsize; counter++)
{
scanf("%d", &arr[counter]);
}
for (int c = arrsize - 1; c >= 0; c--)
{
printf("%d ", arr[c]);
}
changxr(arrsize, &arr[counter]);
for (counter = arrsize - 1; counter >= 0; counter--)
{
printf("%d ", arr[counter]);
}
}
void changxr(int arrsize, int *arr[])
{
int a, counter, j;
for (counter = 0; counter < arrsize; counter++)
{
for (j = counter + 1; j < arrsize; j++)
{
if (*arr[counter] > *arr[j])
{
a = *arr[counter];
*arr[counter] = *arr[j];
*arr[j] = a;
}
}
}
}
This is what I got from debugging:
"Program received signal SIGSEGV, Segmentation fault.
0x0000555555555355 in changxr (arrsize=3, arr=0x0) at main.c:33
33 for(j=counter+1; j<arrsize; j++) { if(*arr[counter]>*arr[j]){
(gdb) continue"
You do not need two levels of indirection (int *arr[], *arr[counter], *arr[j]). When arr is passed to a function, it will decay to a pointer-to-its-first-element, or more simply, an int *.
&arr[counter] is also an int *, but it is the address of the array element one past the elements you've initialized. This would start your sorting function in the incorrect place.
Your program segfaults because it attempts to use this value as an int ** (int *[]).
gcc -Wall highlights this clearly:
prog.c: In function ‘main’:
prog.c:24:22: warning: passing argument 2 of ‘changxr’ from incompatible pointer type [-Wincompatible-pointer-types]
24 | changxr(arrsize, &arr[counter]);
| ^~~~~~~~~~~~~
| |
| int *
prog.c:3:32: note: expected ‘int **’ but argument is of type ‘int *’
3 | void changxr(int arrsize, int *arr[]);
| ~~~~~^~~~~
Things to do:
Simply pass the array and the length of the array to your function.
Use a single level of indirection in your function definition, and when accessing the array.
Use a variable-length array.
Use an auxiliary function for printing.
Declare variables when you need them, in the correct scope.
You should also consider checking the return value of scanf is the expected number of successful conversions.
The refactored code:
#include <stdio.h>
void changxr(int *a, size_t length)
{
for (size_t i = 0; i < length; i++) {
for (size_t j = i + 1; j < length; j++) {
if (a[i] > a[j]) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
void print_reverse(int *a, size_t length)
{
printf("[ ");
while (length--)
printf("%d ", a[length]);
printf("]\n");
}
int main(void)
{
size_t size;
printf("Pick an array length: ");
if (1 != scanf("%zu", &size) || size == 0) {
fprintf(stderr, "Invalid length input.\n");
return 1;
}
int array[size];
printf("Enter %zu numbers:\n", size);
for (size_t i = 0; i < size; i++) {
if (1 != scanf("%d", array + i)) {
fprintf(stderr, "Invalid integer input.\n");
return 1;
}
}
printf("Array (in reverse): ");
print_reverse(array, size);
changxr(array, size);
printf("Array, Sorted (in reverse): ");
print_reverse(array, size);
}

printTriangle with alphabets

#include <stdio.h>
int inputNumber();
void printTriangle(int size, char ch[]);
int main()
{
char arr_char[] = {'a','e','i','o','u'};
int number;
number = inputNumber();
printTriangle(number,arr_char);
return 0;
}
int inputNumber()
{
int size;
printf("Input Size: ");
scanf("%d",&size);
printf("===\nTriangle Size is %d\n===\n",size);
return size;
}
void printTriangle(int size, char ch[5])
{
int i,j;
for(i=0;i<size;i++)
{
for(j=0;j<size;j++)
{
if(j <= 4)
{
printf("%s ",ch[j]);
}
if(j > 4 )
{
printf("# ");
}
}
}
}
This is what it supposed to look like. And I'm confused as what I did wrong because it only work with inputNumber but not with printTriangle. a e i o u # # # please go easy on me since I'm kinda new to this.
The segmentation fault is caused by an incorrect format string (%s should be %c). The output format doesn't match expectations as the inner loop condition is wrong and you need a newline after you print each line (after inner loop):
#include <stdio.h>
#define LEN 5
int inputNumber() {
int size;
printf("Input Size: ");
scanf("%d",&size);
printf("===\nTriangle Size is %d\n===\n",size);
return size;
}
void printTriangle(int size, char ch[]) {
for(int i = 0; i < size; i++) {
for(int j = 0; j <= i; j++) {
printf("%c ", j < LEN ? ch[j] : '#');
}
printf("\n");
}
}
int main() {
char arr_char[LEN] = {'a','e','i','o','u'};
int number;
number = inputNumber();
printTriangle(number,arr_char);
return 0;
}
Consider using the type unsigned instead of int as negative size, row (i) and column (j) doesn't make sense.
Here is an alternatively implementation of printTriangle() that does a bit of work upfront to generate the last row, then use a prefix of that last row to print all rows:
void printTriangle(unsigned size, char ch[]) {
// use malloc if size is large (say >4k),
// or you don't want to use a variable length array (VLA)
char str[2 * size];
for(unsigned column = 0; column < size; column++) {
str[2 * column] = column < LEN ? ch[column] : '#';
str[2 * column + 1] = ' ';
}
for(unsigned row = 0; row < size; row++) {
printf("%.*s\n", 2 * row + 1, str);
}
}

C code function calling not working

Ok I need to write two functions iterative and recursive to count negative elements in an array and then I need to build main. I was only able to write the recursive function but I cannot call it from main, it is an error somewhere. Can someone help me out solve it and help me with the iterative method?
#include <stdio.h>
main()
{
int vektor[100];
int i, madhesia;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
/* Input array elements */
printf("Elementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
int ret = numero(vektor, madhesia);
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(array, size)
{
int count = 0;
for (int j = 0; j < size; j++)
{
if (array[j] < 0)
{
count++;
}
}
return count;
}
A working piece of code is this.You really need to take a look at pointers and the way they work.
Here you can see that I have a pointer ->pointing-< at the start of the array , so by passing the starting address of the array , and the length of the array , your functions knows what it is needed to be done.
#include <stdio.h>
int numero(int* array, int size);
int* recursive_count(int* array, int size , int* counter );
int main()
{
int vektor[100];
int* vekt_ptr = &vektor[0];
int i, madhesia;
int counter;
counter=0;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
/* Input array elements */
printf("Elementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
//int ret = numero(vekt_ptr, madhesia);
recursive_count(vekt_ptr, madhesia , &counter );
int ret = counter;
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(int* array, int size)
{
int count = 0;
int j;
for (j = 0; j < size; j++)
{
if (array[j] < 0)
{
count++;
}
}
return count;
}
int* recursive_count(int* array, int size , int* counter )
{
size--;
if(array[size] < 0 )
{
(*counter)++;
}
if(size==0)
{
return NULL;
}
return recursive_count(array++, size , counter );
}
Let's assume that you want to create dynamically an array of X length.
The compiler is going to have some memory for your array , depending on the length.
You initialize your array , lets say [2][45][1][-5][99]
When you call the function you have to pass where this is stored in memory.
int* vekt_ptr = &vektor[0]; -s going to give as something like 0x56c2e0.
This number is the address of your array , which is the address of the starting point of the array.This is equal with the address of first byte.
So when your function starts , it knows where your array starts and how long it is.
For starters according to the C Standard the function main without parameters shall be declared like
int main( void )
Any function used in a program shall be declared before its usage.
This function declaration of the function definition
int numero(array, size)
{
// ...
}
is invalid because the types of the parameters array and size are undefined.
For the size of an array and for the count of elements it is better to use an unsigned integer type like for example size_t or at least unsigned int.
The program can look the following way
#include <stdio.h>
#define N 100
size_t iterative_numero( const int array[], size_t size );
size_t recursive_numero( const int array[], size_t size );
int main( void )
{
int vektor[N];
size_t madhesia = 0;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%zu", &madhesia);
if ( N < madhesia ) madhesia = N;
/* Input array elements */
printf("Elementet: ");
for ( size_t i = 0; i < madhesia; i++ )
{
scanf( "%d", &vektor[i] );
}
size_t ret = iterative_numero(vektor, madhesia );
printf("\nTotal negative elements in array = %zu\n", ret);
ret = recursive_numero(vektor, madhesia );
printf("Total negative elements in array = %zu\n", ret);
return 0;
}
size_t iterative_numero( const int array[], size_t size )
{
size_t count = 0;
for ( size_t i = 0; i < size; i++)
{
if ( array[i] < 0 )
{
count++;
}
}
return count;
}
size_t recursive_numero( const int array[], size_t size )
{
return size == 0 ? 0 : ( array[0] < 0 ) + recursive_numero( array + 1, size - 1 );
}
the program output might look like
Madhesia e vektorit: 10
Elementet: 0 -1 2 -3 4 -5 6 -7 8 -9
Total negative elements in array = 5
Total negative elements in array = 5
First of all what you did is the iterative method, not recursive. Here I have called a recursive function from the main function.
#include <stdio.h>
int main()
{
int vektor[100];
int i, madhesia;
/* Input size of array */
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
/* Input array elements */
printf("\nElementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
printf("\nno of elements:%d",madhesia);
printf("\n");
for (i = 0; i < madhesia; i++)
{
printf("%d", vektor[i]);
}
printf("\n");
i=0;
int ret = numero(vektor,madhesia,0,i);
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(int array[],int size,int count,int j)
{
if (j<=size-1)
{
if(array[j]<0)
{
count++;
j++;
numero(array,size,count,j);
}
else
{
j++;
numero(array,size,count,j);
}
}
return count;
}
Put function prototype of numero() before main() to be able to call it. Declare function parameters with type:
int numero(int array[], int size);
int main() {
...
#include<stdio.h>
int numero(int *, int); //Function Prototype (1)
int main() //Return Type (2)
{
int vektor[100];
int i, madhesia;
printf("Madhesia e vektorit: ");
scanf("%d", &madhesia);
printf("Elementet: ");
for (i = 0; i < madhesia; i++)
{
scanf("%d", &vektor[i]);
}
int ret = numero(vektor, madhesia);
printf("\nTotal negative elements in array = %d", ret);
return 0;
}
int numero(int* array,int size) //Parameters Data Type (3)
{
int count = 0;
for (int j = 0; j < size; j++)
{
if (array[j] < 0)
{
count++;
}
}
return count;
}
Errors:
You have declared the function after "main()" so the program doesn't know that there is a function, so you have to give the function prototype before "main()" so that the program knows there is function ahead.
You missed writing the return type of "main()" which is integer.
In the function declaration you forgot to write the data type of the parameters.
NOTE: The array is always passed by reference so it has to taken in an integer pointer instead of a normal integer.
Some possible implementations:
int iterativeCountNegativeIntegers (int *array, int size)
{
int result = 0;
for (int i = 0; i < size; ++ i)
if (array[i] < 0)
result += 1;
return result;
}
int recursiveCountNegativeIntegers (int *array, int size)
{
if (size == 0)
return 0;
int partial = *array < 0;
return partial + recursiveCountNegativeIntegers(array+1, size-1);
}
The same, condensed:
int iterativeCountNegativeIntegers_1 (int *array, int size)
{
int result = 0;
while (--size >= 0)
result += *array++ < 0;
return result;
}
int recursiveCountNegativeIntegers_1 (int *array, int size)
{
return (size == 0) ? 0
: (*array < 0) + recursiveCountNegativeIntegers_1(array+1, size-1);
}

How to input an array manually in a function in c?

In my code the following function exists:
int Count_border(int loc[], int search[], int search_c){
int count = 0, i, j;
for(j = -1; j < 2; j += 2){
if(In_array(BOARD[loc[0] + j][loc[1]], search, search_c) == 1) count++;
}
for(j = -1; j < 2; j += 2){
if(In_array(BOARD[loc[0]][loc[1] + j], search, search_c) == 1) count++;
}
return count;
}
In this function I am searching for values in the array search. How it is done doesn't matter for this question. My question is however, how can I input a "manual" array, like this: Count_border(con_input, {-1, 0, 1}, 3);
This syntaxis isn't allowed by the compiler. And I don't want to create an array before the function, I really want to hardcode it.
Thank you for your help!
EDIT:
Now I am getting this error:
In function 'main':
file.c:40:1: error: expected ';' before '}' token
}
^
file.c:85:1: error: expected declaration or statement at end of input
}
Where this is my whole code, PLEASE help me out.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void Put(int letter, int number);
void Set(int letter, int number, int who);
void Init_board();
int Count_border(int loc[], int search[], int search_c);
int In_array(int val, int arr[], int size);
int BOARD[9][9]; // 0 = empty, 1 = me, 2 = enemy
int STONES[2][81][9][9], STONE_COUNTER[2];
int main(void){
char input[5];
int con_input[2], t;
Init_board();
memset(STONES, 0, sizeof(STONES));
memset(STONE_COUNTER, 0, sizeof(STONE_COUNTER));
scanf("%s", input);
if(strcmp(input,"Start") == 0){
Put(4, 4);
}
scanf("%s", input); //get the first input after start
do{
con_input[0] = input[0]-'a'; /* Convert the input */
con_input[1] = input[1];
Set(con_input[0], con_input[1], 2);
t = Count_border(con_input, (int[]){-1, 0, 1}, 3);
printf("%i\n", t);
scanf("%s", input); /* Get the next input */
} while(strcmp(input, "Quit") != 0)
}
void Init_board(){
int i,j;
memset(BOARD, -1, sizeof(BOARD));
for(i = 0; i < 9; i++){
for(j = 0; j < 9; j++){
BOARD[i][j] = 0;
}
}
}
void Put(int letter, int number){
char t = letter + 'a';
printf("%c%i\n", t, number);
//fflush(stdout);
Set(letter, number, 1);
}
void Set(int letter, int number, int who){
BOARD[letter][number] = who;
}
int Count_border(int loc[], int search[], int search_c){
int count = 0, i, j;
for(j = -1; j < 2; j += 2){
if(In_array(BOARD[loc[0] + j][loc[1]], search, search_c) == 1) count++;
}
for(j = -1; j < 2; j += 2){
if(In_array(BOARD[loc[0]][loc[1] + j], search, search_c) == 1) count++;
}
return count;
}
int In_array(int val, int arr[], int size){
int i;
for (i=0; i < size; i++) {
if (arr[i] == val)
return 1;
}
return 0;
}
/* notes:
fflush(stdout);
*/
If you have a C99 (or newer) compiler just do
Count_border(con_input, (int[]){-1, 0, 1}, 3);
this (int[]){ something } is called a compound literal in C jargon and defines a temporary object (here an int array with 3 elements) that you can pass to your function.
Something like this?
#include <stdio.h>
void f(char arr[]);
int main(int argc, char *argv[])
{
f((char [4]){'1', '2', '3', '5'});
return 0;
}
void f(char arr[4])
{
int i;
for (i = 0; i < sizeof(arr)/sizeof(*arr); i++)
printf("%c ", arr[i]);
putchar('\n');
}

Mergesort An Array of Strings in C

I'm trying to implement a merge sort for an array of strings entered from standard input, and am at a loss at what is wrong. Right now I'm facing a segmentation fault. How should I modify my code?
main() {
char temp;
int i = 0;
char Strings[NUM][LEN];
printf("Please enter %d strings, one per line:\n", NUM);
for (i; i < 25; i++) {
fgets(&Strings[i][0], LEN, stdin);
}
i = 0;
puts("\nHere are the strings in the order you entered:");
for (i; i < 25; i++) {
printf("%s\n", Strings[i]);
}
mergesort(Strings, NUM);
i = 0;
puts("\nHere are the strings in alphabetical order");
for (i; i < 25; i++) {
printf("%s\n", Strings[i]);
}
}
int mergesort(char list[NUM][LEN], int length) { // First part
mergesort_r(0, length, list);
return 0;
}
int mergesort_r(int left, int right, char list[NUM][LEN]) { // Overloaded portion
if (right - left <= 1) {
return 0;
}
int left_start = left;
int left_end = (left + right) / 2;
int right_start = left_end;
int right_end = right;
mergesort_r( left_start, left_end, list);
mergesort_r( right_start, right_end, list);
merge(list, left_start, left_end, right_start, right_end);
}
int merge(char list[NUM][LEN], int left_start, int left_end, int right_start, int right_end) {
int left_length = left_end - left_start;
int right_length = right_end - right_start;
char *left_half[left_length];
char *right_half[right_length];
int r = 0;
int l = 0;
int i = 0;
for (i = left_start; i < left_end; i++, l++) {
strcpy(left_half[l], list[i]);
}
for (i = right_start; i < right_end; i++, r++) {
strcpy(right_half[r], list[i]);
}
for (i = left_start, r = 0, l = 0; l < left_length && r < right_length; i++) {
if (strcmp(left_half[l], right_half[r]) < 0) {
strcpy(list[i], left_half[l++]);
} else {
strcpy(list[i], right_half[r++]);
}
}
for ( ; l < left_length; i++, l++) {
strcpy(list[i], left_half[l]);
}
for ( ; r < right_length; i++, r++) {
strcpy(list[i], right_half[r]);
}
return 0;
}
I'm not sure if it's that I'm passing in my array incorrectly, or maybe it's that I am not even executing swaps properly. I'm at my wits end with this and could use some advice.
should be
char left_half[left_length][LEN];
char right_half[right_length][LEN];
#include<stdio.h>
#include<stdlib.h>
#include<string.h> //To use the string functions like strcmp and strcpy
#define MAX 10 // This is the default size of every string
void Merge(char* arr[],int low,int mid,int high) //Merging the Array Function
{
int nL= mid-low+1;
int nR= high-mid;
char** L=malloc(sizeof(char *)*nL);
char** R=malloc(sizeof(char *)*nR);
int i;
for(i=0;i<nL;i++)
{
L[i]=malloc(sizeof(arr[low+i]));
strcpy(L[i],arr[low+i]);
}
for(i=0;i<nR;i++)
{
R[i]=malloc(sizeof(arr[mid+i+1]));
strcpy(R[i],arr[mid+i+1]);
}
int j=0,k;
i=0;
k=low;
while(i<nL&&j<nR)
{
if(strcmp(L[i],R[j])<0)strcpy(arr[k++],L[i++]);
else strcpy(arr[k++],R[j++]);
}
while(i<nL)strcpy(arr[k++],L[i++]);
while(j<nR)strcpy(arr[k++],R[j++]);
}
void MergeSort(char* arr[],int low,int high) //Main MergeSort function
{
if(low<high)
{
int mid=(low+high)/2;
MergeSort(arr,low,mid);
MergeSort(arr,mid+1,high);
Merge(arr,low,mid,high);
}
}
int main()
{
printf("\nEnter the size of the array desired: ");
int size; //This is the String array size
scanf("%d",&size);
char** arr= malloc(sizeof(char *)* size); //Creating required string array
printf("\nEnter the strings of the array: ");
int i;
for(i=0;i<size;i++)
{
arr[i]=malloc(sizeof(char)*MAX);
printf("\nEnter String: ");
scanf("%s",arr[i]);
}
MergeSort(arr,0,size-1);
printf("\nThe Sorted Array is: ");
for(i=0;i<size;i++)printf("%s ->",arr[i]);
return 0;
}
This is a Working solution to the same problem. Hope it Helps!
Cheers! :)
This solution of yours might give a memory error for long inputs or repeated executions. You need to free the allocated memory or not dynamically allocate it in the first place.
The latter is an easier option. What you can do is find the length of the longest string in the array of strings before hand and pass it as an argument to the merge sort and merge function.
Let's say that length is LEN.
Then instead of dynamically allocating memory for the L and R array, just declare it as:
char L[nL][LEN] and char R[nR][LEN].
It might take a slightly larger stack memory but avoids crashing the program.

Resources