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.
Related
I want to pass a 2D array already filled with chars to a different method to do something with it.
Background: I am trying to implement GameOfLife. And I have already successfully implement the gameboard with a random amount of living cells. But now I want to pass the board(Array) to a different method to continue working with it. How to do so?
//wow das wird hurenshon
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
void spielStarten(int x, int amountOfLiving){
char feld[x][x];
for(int i = 0; i < x; i++){
for(int j = 0; j < x; j++){
feld[i][j] = 'o';
}
}
for(int i = 0; i < amountOfLiving; i++){
int a = (rand()%x);
int b = (rand()%x);
feld[a][b] = 'x';
}
printf("Gameboard: \n");
for(int i = 0; i < x; i++){
for(int j = 0; j < x; j++){
printf("%c ", feld[i][j]);
}
printf("\n");
}
spielRun(feld);
}
void spielRun(char feld[][]){
int neighbCount;
char feldNew[][] = feld[][];
for(int i = 0; i < x; i++) {
for(int j = 0; j < x; j++) {
checkForNeighbours(feld[x][y]);
// in progress
}
}
}
int main(int argc, char* argv[]){
srand(time(NULL));
int x = 16;
if(argc < 2 || argc > 3){
printf("2. Argument eine Zahl fuer Feldgroesse eingeben\n");
printf("1. Argument eine Zahl 0-10 fuer ungefähre prozentuale Belegung mit lebenden
Zellen eingeben \n");
return 0;
}
if(argv[2] != NULL){
x = atoi(argv[2]);
}
int i;
i = atoi(argv[1]);
i = (x^2)*(0,1*i);
spielStarten (x,i);
return 0;
}
In the last line of the Method "Spiel starten" i want to give the array to the next Method "spielRun".
Edit: thanks to an other user I found this struture:
void printarray( char (*array)[50], int SIZE )
But it doesn't work for me since I can´t hardcode the number, because the arraysize depends on a user input.
thanks!
The difficulty here is that the size of your array is not known statically (once upon a time, your code would even not compile for the same reason).
That, combined with the fact that 2D-arrays are not arrays of 1D arrays (contrarily to what happen when you malloc a int ** and then every int * in it), and so it doesn't make sense not to specify the size when passing it to a function.
When using arrays of arrays (technically, pointers to a bunch of pointers to ints), like this
void f(int **a){
printf("%d %d %d\n", a[0][0], a[1][0], a[0][1]);
}
int main(){
int **t=malloc(10*sizeof(int *));
for(int i=0; i<10; i++) t[i]=malloc(20*sizeof(int));
f(t);
}
That code is useless, it prints only unitialized values. But point is, f understands what values it is supposed to print. Pointers arithmetics tells it what a[1] is, and then what a[1][0] is.
But if this 2D-array is not pointers to pointers, but real arrays, like this
void f(int a[][20]){
printf("%d %d %d\n", a[0][0], a[1][0], a[0][1]);
}
int main(){
int t[10][20];
f(t);
}
Then, it is essential that the called function knows the size (or at least all sizes, but for the first dimension) of the array. Because it is not pointers to pointers. It is an area of 200 ints. The compiler needs to know the shape to deduce that t[5][3] is the 5×20+3=103th int at address t.
So, that is roughly what is (better) explained in the link that was given in comments: you need to specify the size.
Like I did here.
Now, in your case, it is more complicated, because you don't know (statically) the size.
So three methods. You could switch to pointers to pointers. You could cast your array into a char * and then do the index computation yourself (x*i+j). Or with modern enough C, you can just pass the size, and then use it, even in parameters, declaration
void f(int x, int a[][x]){
printf("%d %d %d\n", a[0][0], a[1][0], a[0][1]);
}
int main(){
int t[10][20];
f(t);
}
Anyway, from an applicative point of view (or just to avoid segfault) you need to know the size. So you would have had to pass it. So why not pass it as first parameter (Note that the function in which you have this size problem, spielRun, does refers to a x, which it doesn't know. So, passing the size x would have been your next problem anyway)
So, spielRun could look like this (not commenting in other errors it contains)
void spielRun(int x, char feld[][x]){
int neighbCount;
char feldNew[][] = feld[][]; // Other error
for(int i = 0; i < x; i++) {
for(int j = 0; j < x; j++) {
checkForNeighbours(feld[i][j]); // Corrected one here
// in progress
}
}
}
And then calls to this spielRun could be
spielRun(x, feld);
Note that I address only the passing of array of size x here. There are plenty of other errors, and, anyway, it is obviously not a finished code. For example, you can't neither declare a double array char newFeld[][] = oldFeld[][]; nor affect it that way. You need to explicitly copy that yourself, and to specify size (which you can do, if you pass it).
I am also pretty sure that i = (x^2)*(0,1*i); does not remotely what you expect it to do.
Right, this is (the last) assignment for my C introduction web class.
The assignment presents the main program, does not explain anything about it and tells you to write a function to print and sum the array in it.
However I don't really understand what is going on in the main program.
Translated for your convenience;
Source code:
#include <stdio.h>
#include <stlib.h>
void print_count(int *, int);
int main(int argc, char *argv[]) {
int x, sum = 0, size = 0, array[5];
if (argc == 6) {
/* Program name and parameters received from command line */
for (x = 0; x < argc - 1; x++) {
array[x] = atoi(argv[x + 1]);
}
print_count(array, size);
} else {
printf("Error\n");
}
return 0;
}
Now I am completely clueless as to how to start writing the program requested and what variables to call/how to write the function.
Edit3: completed exercise
void print_count(int *array, int size) {
int i;
int sum = 0;
printf("Elements: ");
for (i = 0; i <= size; i++) {
printf("%d ", (array[i]);
sum = sum += array[i]);
}
printf("\nSum = %d ", sum);
return 0;
}
I would like to understand what is going on in the main program and preferably come to an answer on how to actually write the function by myself.
This:
array[5] = atoi(argv[x+1]);
is clearly wrong, it always tries to assign to array[5] which is out of bounds. It should be:
array[x] = atoi(argv[x + 1]);
This converts the x + 1:th argument from string format into an integer, and stores that in array[x]. If you're not familiar with the standard function atoi(), just read the manual page.
So if you start the program like this:
./myprogram 1 2 3 4 5
That has 6 arguments (the first is the name itself), and will end up with array containing the numbers one through five.
Then in the summing function, the first line should be something like:
void print_count(int *array, int size)
so that you give names to the arguments, which makes them usable in the function. Not providing names is an error, I think.
And it doesn't need to "interact" with main() more than it already does; main() calls print_count(), passing it a pointer to the first element of array and the length of the array, that's all that's needed to compute the sum.
Your print_count function has a few issues:
The loop runs one step too far: i should vary between 0 and size-1 included. The standard idiom for this loop is:
for (i = 0; i < size; i++) {
...
Incrementing sum is simply done with:
sum += array[i];
There is an extra ( on the first printf line.
You should print a newline after the output.
Returning 0 from a void function is invalid.
Here is a corrected version:
void print_count(int *array, int size) {
int i;
int sum = 0;
printf("Elements: ");
for (i = 0; i < size; i++) {
printf("%d ", array[i]);
sum += array[i]);
}
printf("\nSum = %d\n", sum);
}
the following proposed code:
cleanly compiles.
explains what is being accomplished at each step of the 'main()' function.
properly outputs error messages to 'stderr'.
implements the typical method to announce an error in the number of command line parameters.
Now the proposed code with explanatory comments:
#include <stdio.h> // printf(), fprintf()
#include <stdlib.h> // atoi(), exit(), EXIT_FAILURE
void print_count(int *, int);
int main(int argc, char *argv[])
{
if (argc != 6)
{
fprintf( stderr, "USAGE: %s int1 int2 int3 int4 int5\n", argv[0] );
exit( EXIT_FAILURE );
}
// implied else, correct number of arguments
// only declare variables when they are needed
int array[5];
// place each command line parameter into 'array',
// except program name
// I.E. skip the program name in argv[0]
for( int i = 1; i < argc; i++ )
{
// array[] index starts at 0, but loop counter starts at 1
array[i-1] = atoi(argv[i]);
} // end for( each value pointed at by argv[], except program name )
// print sum of command line parameters to stdout
int size = argc-1; // number of command line parameters after program name
print_count(array, size);
return 0;
} // end function: main
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
Getting problem with return (huge) value. I have already checked at the enthernet, but found nothing :( Hoping that here I could find answer to my question. I am just beginner, so hard to do something right if you dont know what is wrong ((
#include <stdio.h>
#include <math.h>
void MasivaIzveide (int *masivs, int x )
{
int i, reiz,n1,n2;
srand(time(NULL));
/* nosaka cik elementu masiva bus */
printf("Ievadi, divus masiva emelentus, kuri bus '0' starp kuram bus summa\n\n");
printf("\n Pirmais elements=");
scanf("%d", &n1);
printf("\n Otrais elements=");
scanf("%d", &n2);
for ( i = 0; i < x; i++ )
{
masivs[ i ] = rand() % 200-100 ; /* random vertibas katram masiva skaitlim*/
masivs[n1]= 0;
masivs[n2]=0;
printf("Loceklis[%d] = %d\n", i, masivs[i] );
}
return;
}
void Reizinajums (int *masivs, int x) {
int i, reiz;
reiz=masivs[2];
for (i=4; i < x; i=i+2) {
reiz=reiz*masivs[i] ;
}
printf("\n\nReizinajums ir %d\n\n\n\n ", reiz);
return;
}
void main(){
int i,j,s;
int masivs[i];
printf("Tiks izveidots masiivs\n\n\n\n");
MasivaIzveide(masivs,15);
Reizinajums(masivs,15);
return;
}
The problem is at the line (reiz=reiz*masivs[i] ;)
I am using pointers aswell.
Thanks for help.
This is a mistake:
int i,j,s;
int masivs[i];
You are declaring masivs with the dimension i but that is an uninitialized variable. That causes undefined behaviour. Perhaps you meant:
int masivs[15];
You should also check that n1 and n2 are in the correct range before using them as array indices.
What I am trying to do is use a structure to create and display a 2D array of characters in the function 'function1( )'. This array will be sent back to the main( ) so I can use it further in my program. However my program is plagued with problems. I am having trouble with pointers. I assume my problem is somewhere with either my pointers or my variables. I've tried several combinations with no effort. As a beginner, it probably is some odd combination that is not coming to my mind.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 13
#define COL 16
typedef struct letter_array {
char** letters;
struct letter_array *ltr_ptr;
} larray;
void function1 (larray ** letter1[*][16]);
int function2 (larray letter2[][16]);
int function3 (larray letter3[][16]);
void function4 (int hor_ans, int ver_ans);
int main (void)
{
larray letter_list;
int vert, hori, **lptr;
lptr = malloc(ROW*sizeof(int*));
for(vert = 0; vert<ROW; vert++)
{
lptr [vert] = malloc(COL*sizeof(int));
}
printf("\n \t\t\t *** Hello! ***");
printf("\n This program will create a random selection of 180 upper-case"
" characters. \n\n");
function1(&letter_list); //Problem #1
printf("\n\nThank you for using my random character array program. \n"
"\t\t Have a good day! \n");
return ( 0 ) ;
}
void function1 (larray **letter1 [][16])
{
int i, z, funptr;
srandom((unsigned)time(NULL));
for(i=0; i<12; i++)
{
letter1 [i] <- (int*) funptr; // Problem #2-3
for(z=0; z<15; z++)
{
letter1[i][z] = random( )%26+'A'; // Problem #4
printf("%c ", letter1[i][z]);
}
printf("\n");
}
return ;
}
The errors are below and commented.
warning:passing argument 1 of 'function1' from incompatible pointer type
warning: cast to pointer from integer of different size
error: wrong type argument to unary minus
warning: assignment makes pointer from integer without a cast
I hope this helps.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 13
#define COL 16
typedef struct letter_array {
char** letters;
struct letter_array *ltr_ptr;
} larray;
void function1 (larray * letter1); // here you just need a pointer to the structure
int function2 (larray letter2[][16]);
int function3 (larray letter3[][16]);
void function4 (int hor_ans, int ver_ans);
int main (void)
{
larray letter_list;
int vert, hori;
letter_list.letters = malloc(ROW*sizeof(int*)); // allocate memory to the char pointer in the structure
for(vert = 0; vert<ROW; vert++)
{
letter_list.letters[vert] = malloc(COL*sizeof(int)); // allocate the second 2D
}
printf("\n \t\t\t *** Hello! ***");
printf("\n This program will create a random selection of 180 upper-case"
" characters. \n\n");
function1(&letter_list); //Problem #1 pass a pointer to the structure
printf("\n\nThank you for using my random character array program. \n"
"\t\t Have a good day! \n");
return ( 0 ) ;
}
void function1 (larray *letter1) // just needs a pointer to the structure
{
int i, z;
srandom((unsigned)time(NULL));
for(i=0; i<ROW; i++) // used ROW
{
//letter1->letters[i] <- (int*) funptr; // Problem #2-3 this line not needed as near as i can tell
for(z=0; z<COL; z++) // used COL
{
letter1->letters[i][z] = random( )%26+'A'; // Problem #4 dereference pointer to member char **
printf("%c ", letter1->letters[i][z]);
}
printf("\n");
}
return ;
}