The program stops and I get a "merge.exe has stopped working" message. I simplefied everything but the problem seems to occur when calling the function...
#include <stdio.h>
#include <stdlib.h>
#define br 1000
int sort(int *list[],int broi);
int merge(int list1[],int list2[],int broi1,int broi2);
int main()
{
int i,n,m,a1[br],a2[br],a;
printf("gimme n: ");
scanf("%d",&n);
printf("gimme m: ");
scanf("%d",&m);
for(i=0;i<n;i++)
{
printf("gimme element %d ot list1: ",i+1);
scanf("%d",&a1[i]);
}
for(i=0;i<m;i++)
{
printf("gimme element %d ot list2: ",i+1);
scanf("%d",&a2[i]);
}
sort(&a1,n);
sort(&a2,m);
merge(a1,a2,n,m);
return 0;
}
int sort(int *list[],int broi)
{
int i,j,c;
for (i = 0; i < broi-1; i++)
{
for (j = 0; j < broi-i-1; j++)
{
if (*list[j] > *list[j+1])
{
c=*list[j];
*list[j]=*list[j+1];
*list[j+1]=c;
}
}
}
return 1;
}
int merge(int list1[],int list2[],int broi1,int broi2)
{
printf(" AAAAAA");
return 1;
}
In the sort() function is pretty self-explanatory and it even works!
But whatever I put in merge() it just won't won't work and it breaks the whole program.
In the sort() function is pretty self-explanatory and it even works! ? NO it won't work. Read the compiler warning by compiling with -Wall it says
reo.c:4:5: note: expected ‘int **’ but argument is of type ‘int *’ as you are passing address of a1 & catching with array of pointer. Instead just pass array name and catch with pointer.
Make function call looks like
sort(a1,n);/*just pass the array name */
sort(a2,m);
And definition of sort()
int sort(int *list,int broi){ /* take list is ptr variable */
int i,j,c;
for (i = 0; i < broi-1; i++) {
for (j = 0; j < broi-i-1; j++) {
if (list[j] > list[j+1]) {
c=list[j];
list[j]=list[j+1];
list[j+1]=c;
}
}
}
}
int *list[] makes list an array of pointers to int. In your main function &a1 (for example) create a pointer to an array of int, of type int (*)[1000]. int** (from the first) is not the same as int (*)[1000].
Simple solution? Don't pass a pointer to the array! This is very seldom needed.
And anyway because of operator precedence an expression like *list[i] is the same as *(list[i]), and if you have a pointer to an array you want (*list)[i]. So, many wrongs don't make a right.
Your compiler should have been shouting warnings about this to you.
Related
so I'm trying to make a 2d binary matrix that is the size provided by stdin and that has randomly assigned indexes for the 0 and 1, however, their cannot be more than size/2 zeroes or ones.
For example
an input of 2
could output
1 0
0 1
Now I was going to originally just use the argument int arr[][n] in init but this idea failed since passing in the matrix just resulted in my program going on some sort of an infinite loop when I attempted to access matrix again inside of the main function. I believe this happened because the lifespan of matrix expired when init concluded? So my question here is why is what I'm doing now producing the below error and how can I fix this up?
note: expected ‘int * (*)[(sizetype)(n)]’ but argument is of type ‘int (*)[(sizetype)(dim)][(sizetype)(dim)]’
7 | int init(int n, int* arr[][n]);
My code
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int init(int n, int* arr[][n]);
int main(){
time_t t;
srand((unsigned) time(&t));
int dim;
printf("Enter a positive even integer: ");
scanf("%d",&dim);
if(dim<2||dim>80){
return 1;
}
int matrix[dim][dim];
init(dim,&matrix);
return 0;
}
int init(int n, int* arr[][n]){
int numZeroes,numOnes;
int zero_or_one;
for(int row=0;row<n;row++){
numZeroes=0;
numOnes=0;
for(int col=0;col<n;col++){
if(numZeroes<n/2 && numOnes<n/2){
zero_or_one=rand()%2;
*arr[row][col]=zero_or_one;
if(zero_or_one==1){
numOnes++;
}
if(zero_or_one==0){
numZeroes++;
}
}
else{
if(numZeroes==n/2 && numOnes<n/2){
*arr[row][col]=1;
}
if(numZeroes<n/2 && numOnes==n/2){
*arr[row][col]=0;
}
}
}
}
for(int row=0;row<n;row++){
for(int col=0;col<n;col++){
printf("%d ",*arr[row][col]);
}
printf("\n");
}
return 0;
}
The function should be declared like
void init(int n, int arr[][n]);
(the return type int of the function does not make a great sense.)
and called like
init(dim, matrix);
Within the function instead of statements like this
*arr[row][col]=zero_or_one;
you have to write
arr[row][col]=zero_or_one;
I've been trying to make a write to array method in C, but it does not seem to be returning what I expect.
How many numbers would you like to short?: 3
Checking for the i: 0: 1
Setting the number to temp 1
Checking for the i: 1: 2
Setting the number to temp 2
Checking for the i: 2: 3
Setting the number to temp 3
Setting the array2 to *array
0: 6487440
1: 0
2: 6480512
----------------------------------
Proces exited after 1.741 seconds with return value 3
And this is the code
int array_size;
void getArray(int *array[]);
void printArray(int array[]);
void main() {
printf("How many numbers would you like to short?: ");
scanf("%d", &array_size);
int input[array_size];
getArray(&input);
printArray(input);
}
void getArray(int *array[]) {
int i, temp;
int array2[array_size];
for(i = 0; i < array_size; i++) {
printf("Checking for the i: ");
printf("%d: ", i);
scanf("%d", &temp);
printf("Setting the number to temp %d\n", temp);
array2[i] = temp;
}
printf("Setting the array2 to *array\n");
*array = array2;
}
void printArray(int array[]) {
int i;
for(i = 0; i < array_size; i++) {
printf("%d: %d\n", i, array[i]);
}
}
I have also tried using
scanf("%d", &*array[i]);
but it does not work either.
Any ideas as to what I'm doing wrong?
Thanks in advance!
You are doing so many things wrong over here. First of all passing an array is not passing array will be simply
getArray(&input); --> getArray(input);.
The 1D-array when passed to a function decays into pointer - making it possible to retain any change made to the array (via pointer) in the called function.
void getArray(int *array) {
int i, temp;
for(i = 0; i < array_size; i++) {
printf("Checking for the i: ");
printf("%d: ", i);
scanf("%d", &array[i]);
}
}
This will do whatever you wanted to do. But earlier the assignment was wrong because the automatic variables are deallocated once the function reaches the }. So accessing it outside the function scope results in undefined behavior.
To give you a more elaborate idea, there are few things (Mostly the error message is being discussed).
If you compiled your code, then you would get some error. Now look at the error message.
error: cannot convert 'int (*)[array_size]' to 'int**' for argument '1' to 'void getArray(int**)'.
&input is nothing but int(*)[array_size]. It means it is a pointer to an array of array_size integers.
From looking at the error message you might think , but where from int** coming here in the argument of getArray()?
Well you were passing int* array[] (you declared that function will receive this as parameter) which means array is an array of int*-s. Now it decays into the pointer to it's first element.
Now wait, what is the element here? It's a pointer.
And what is pointer to pointer? Yes, it's int**.
Simply there is an error thrown - complaining that it can't convert.
Look at where you have decalred array2. As soon as you exit the scope of getArray(), the memory for it is deallocated. So when you try to access it later you end up with whatever is in memory at that moment.
I am writing C code to take user parameters and build an integer array from them. I ask the user to provide the array length and each element's value.
Running the following code causes an error at the printArray() function call. Following the debugger into printArray(), the Segmentation Fault itself occurs at printf("%d", intArray[i])
NOTE: The array is correctly printed when I copy the printArray() code into main() instead of making a function call. This makes me think that I have an issue with global variables and/or pointers. I am still learning C, so your guidance is appreciated.
How can I fix this? See debugger output at the bottom for more info.
void printArray();
int arraySize;
int* intArray;
int main() {
printf("Enter array length:\n");
scanf("%d", &arraySize);
int* intArray = (int*) malloc(sizeof(int)*arraySize);
printf("Enter an integer value for each array element:\n");
for (int i = 0; i < arraySize; i++) {
printf("Enter element %d:\n", i);
scanf("%d", &intArray[i]);
}
printArray();
return 0;
}
void printArray() {
printf("[");
for (int i = 0; i < arraySize; i++) {
printf("%d", intArray[i]);
}
printf("]\n");
}
I think you have redeclared intArray variable in main()
int* intArray = (int*) malloc(sizeof(int)*arraySize);
by doing this, the scope of this variable is only in the main function and printArray() does not know about this definition. So printArray() tries to access intArray variable which you have declared globally(which does not have definition) and thus leading to segmentation fault.
So just give intArray = (int*) malloc(sizeof(int)*arraySize);
I am relatively new to C and can't figure out what is wrong with the code?
I am getting 2 warnings during compile time and Segmentation fault core dump error during run time. Can anyone explain why? I am running Ubuntu as a virtual machine. And is this the correct way to declare/pass an array into a function?
#include <stdio.h>
//Loop handlers
int i, j, m, n;
int c;
int cap[26];
//Funtions prototype
void countingChars(void);
void vertcalHistogram(int [], int size); //Warning: expected ‘int *’ but argument is of type ‘int’ (helloworld)
void dashes(void);
int main (void)
{
countingChars();
vertcalHistogram( cap[26], 26); //Warning: passing argument 1 of ‘vertcalHistogram’ makes pointer from integer without a cast [enabled by default] (helloworld)
//dashes();
getchar();
return 0;
}
void countingChars(void)
{
while((c = getchar()) != EOF)
{
if(c >= 65 && c <= 90)
++cap[c - 65];
if(c >= 97 && c <= 122)
++cap[c - 97];
for(i = 0; i < 26; i++)
printf("%d", cap[i]);
printf("\n");
}
}
void dashes(void)
{
printf("\n");
printf("\n");
for(i = 0; i < 40; i++)
printf("_");
printf("\n");
for(i = 0; i < 40; i++)
printf("_");
}
void vertcalHistogram(int cap[], int size)
{
for(i = 0; i < size; i++)
{
printf("||");
for(j = 0; j < cap[i]; j++)
printf("*");
printf(" ~~ %d", cap[i]);
printf("\n");
}
}
cap[26] is the 27th element of cap, and since cap[] is an array of int, the 27th element is of type int. You need to pass cap, not cap[26].
Also, you would do yourself a great favour to enable the "treat all warnings as errors" option of your compiler, so as to not even try running your program if you get warnings.
Also, try this: #define COUNTOF(x) (sizeof(x)/sizeof((x)[0])) so then you can call your function like this: vertcalHistogram( cap, COUNTOF(cap) );
The correct way is to pass the address of array itself or the address of the first element:
vertcalHistogram( cap, 26);
or
vertcalHistogram( &cap[0], 26);
But it doesn't seem to be necessary since cap is a global variable in your code.
cap[26] is outside the bounds of the array. Remember C indexing starts from 0. So for an array of size 26, 0 to 25 is the valid index range.
cap[26] means the int at index 26 in the cap array.
If you want to pass cap, write cap:
verticalHistogram(cap, 26);
cap[26] is 1 element passed the last element of char array cap[]. Original code is passing a char and not an array. Certainly not what is intended.
void vertcalHistogram(int [], int size);
int cap[26];
...
vertcalHistogram( cap[26], 26); // bad
...
void vertcalHistogram(int cap2[], int size) // Changed name for clarity
In C, arrays are not truly passed to functions.
Detail: Instead use the following. The array cap is a formal parameter to vertcalHistogram(). C does not pass arrays, instead it converts the array to the address and type of the first element. This actual parameter is passed to the function. The function receives the address as cap2[].
vertcalHistogram( cap, 26); // good
I have been struggling for a while with my program. I am trying to find horizontal pairs in an array that is setup in function1. My goal is to change the original array in another function. Then process that array to find a horizontal pair.
One problem that has occurred is when I run the program, the result is zero. Another problem is the gcc warning in function 1, warning: comparison between pointer and integer. The other problem is another gcc warning (marked by the **) warning: passing argument 1 of 'function1' from incompatible pointer type.
I appreciate any help, as a beginner, I have spent several hours on this problem and have tried to find solutions, but trying to use pointers and using struct and typedef have not worked. :(
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void function1 (int letter1[][16]);
void function2 (int letter2[][16]);
int main ( void )
{
int letter_array [13][16];
printf("\n \t\t Hello!");
printf("\n This program will create a random selection of 180 upper-case"
" characters. \n");
**function1(&letter_array);**
function2(letter_array);
return ( 0 ) ;
}
void function1 (int letter1 [][16])
{
int i, z;
srandom((unsigned)time(NULL));
for(i=0; i<=11; i++)
{
for(z=0; z<=14; z++)
{
letter1 [i][z] = random( )%26+65;
printf("%c ", letter1 [i][z]);
}
printf("\n");
}
return ;
}
void function2 (int letter2 [][16])
{
int a,b;
int m=0;
for( a = 0; a <= 11; a++)
{
for( b = 0 ; b <= 14; b++)
{
if (letter2 == (letter2 + 1))
m++;
}
}
printf("\nThe number of horizontal pairs of characters"
" are: %d", m);
return ;
Just remove the ampersand & from the argument.
Change
function1(&letter_array);
to
function1(letter_array);
EDIT:
Also change
if (letter2 == (letter2 + 1))
to
if (letter2[a][b] == (letter2[a][b+1]))
The warning is occurring because you are passing a pointer to an array[][16] into function1 instead of the array itself. This can be resolved by removing the &:
function1(letter_array);
The program is returning 0 because of the return statement at the end of your main function.