I am trying to make a program that will read characters from standard input until EOF (the end-of-file mark) is read.
And after that function I have:
#include <stdio.h>
int main(int agc, char *agv[]) {
int x;
int count = 0;
while ((x = getchar()) != EOF){
count++;
In your main(), the lines marked are function declarations, not function calls. You will probably need to replace them with calls to the functions.
int main(int argc, char *argv[]) {
int x;
int count = 0;
while ((x = getchar()) != EOF){
count++;
}
prHeader(FILE *out); // Declaration
prCountStr(FILE *out, int code, char *str, int count); // Declaration
prCountChr(FILE *out, int code, char chr, int count); // Declaration
prTotal(FILE *out, int count); // Declaration
return 0;
}
You are also going to need to have an array (counters, for sake of argument) of 256 integers, all initialized to zero, and your loop will increment the entry in counters corresponding to the character just read. Fortunately, getchar() returns a positive value for every possible input character.
In C, you should seldom define a function in a header; in your case, you should not define the functions in a header. The declarations should be there, but the definitions should not be there. You should have another source file, presumably common.c, which defines the functions. You would then need to compile both the file containing the main() function and common.c, and you'd need to link both object files to create the program. (In the short term, you can avoid that by leaving the functions in the header and simply compiling the code that defines the main() function, but that is subverting the point of a header file.) The majority of the variable definitions should be in common.c and not in common.h too.
You have other work to do too; the BADFILE and related macros are not yet used. It also appears you might need to parse the command line options.
Related
The function readFile(filename) reads the contents of the file and stores it in heap using malloc, it returns char* datatype. I want to store the content in an array in main so that I can count the words. How do I do so? This is the code:
int main()
{
char *char1;
char1 = readFile("test1.txt");
printf("%s", char1[0]); //This does not print anything
CountWords(*char1, &Alpha, &SentChk, &punct, &Words, &totalSents, &onlyVowel_e);
/*function header of CountWords: void CountWords(char ch, int *Alpha, int *SentChk, int *punct,
int *Words, int *totalSents, int *onlyVowel_e);*/
printf("%d", Words);
printf("%d", totalSents);
return 0;
}
When you call "Countwords", your arguments cant be seen by the main as they arent defined there. Even if you use them in your other funtion - this is a different scope. Maybe you could return a char*[] holding these paramaters you want to return. Or better yet, define all of those arguments in main, have your first function pass them "by reference". This way you have the values put in a place where you can access them later for your "Counwords"
I just started with C and am tasked with using a header to house a prototype for a function. The problem is that nothing happens when I'm expecting a prompt for input. I didn't get an error and would like to know where to look at first to solve my problem. This is what I have so far.
LAB2.c
#include <stdio.h>
#include "LAB2HEADER.h"
int main(){
double *p;
double array [10];
p = array;
const int size = 10;
void input(p,size);
return 0;
}
LAB2HEADER.h
#ifndef LAB2HEADER_H_
#define LAB2HEADER_H_
void input (double *array,const int size);
#endif
LAB2HEADER.c
#include <stdio.h>
#include "LAB2HEADER.h"
void input (double *array,const int size){
for (int i = 0; i < size ; i++)
{
printf("Input a value");
scanf("%lf", &array[i]);
}
}
A lot of the notes I look at seem to only either use Int as a parameter or have a function with no needed parameters, could my mistake be in my array pointer is it a problem with the way I made my function?
void input(p,size);
This line makes no sense. If this is supposed to be a function call, you need to remove void.
Also, since your print statement does not end with a newline, nor do you flush stdout before reading in the value, your prompt might still be in the output buffer and not be output until you hit the newline AFTER entering the value.
My textbook mentions: There must be at least one statement in the executable part of main function.
1)
#include <stdio.h>
void main(){ int c; }
2)
#include <stdio.h>
void main(){ int c; c=0; }
The above two codes result in runtime error.
3)
#include <stdio.h>
void main(){
int c; c=5; printf("%d",c); }
The above code runs fine. What is the possible reason?
First,
1 The function called at program startup is named main. The implementation declares no
prototype for this function. It shall be defined with a return type of int and with no
parameters: int main(void) { /* ... */ } or with two parameters (referred to here as argc and argv, though any names may be
used, as they are local to the function in which they are declared):
int main(int argc, char *argv[]) { /* ... */ }
or equivalent;10) or in some other implementation-defined manner.
C 2011 Online Draft, ยง5.1.2.2.1 Program Startup
Unless your compiler documentation specifically lists it as a valid signature, using void main() leads to undefined behavior, which may be where your runtime errors are coming from.
Secondly, the current C standard does not require that main contain any executable statements.
This question already has answers here:
Message "warning: implicit declaration of function"
(10 answers)
Closed 2 years ago.
I have two questions here regarding my C program:
1) In main(), the lines C = enterChar();, N = enterNum();, leftJustifiedPic(C, N);, rightJustifiedPic(C, N); are all giving me implicit declaration of function. What does that even mean? I'm used to Java and is it a little bit different in C with regards to the code?
2) In method enterChar(), Im getting conflicting types for 'enterChar' error and again do not understand what it means and why it happens. I'm working on Eclipse (Cygwin-GCC) if it has anything to do with the problem.
Could smb please detail me on this types of errors and warnings? I appreciate it!
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("Welcome to the menu!");
printf("The menu is:\n1. Enter/Change Character\n2. Enter/Change Number\n3. Print Triangle Type 1(Left Justified)\n4. Print Triangle Type 2(Right Justified)\n5. Quit");
printf("\n");
printf("Now enter a number from the menu from 1 through 5: \n");
int num = 0;
scanf("%d", &num);
char C;
int N = 0;
switch(num){
case 1:
C = enterChar();
break;
case 2:
N = enterNum();
break;
case 3:
leftJustifiedPic(C, N);
break;
case 4:
rightJustifiedPic(C, N);
break;
default:
printf("Smth is wrong!");
}
return 0;
}
char enterChar(){
printf("Enter your input as a character. Only 'C' and 'c' are allowed!\n");
char input = 0 ;
scanf("%c", &input);
while(input != 'c' || input != 'C'){
if(input != 'C' || input != 'c'){
printf("You have to enter 'C' or 'c'. Try again!");
}
}
return input;
}
1) You haven't declared the functions before you use them, and the dialect of C that you are using has "implicit function declarations". This means the function are implicitly declared to return int and take any number of parameters of any type.
2) Because you have an implicit function declaration int enterChar(), that clashes with the definition char enterChar().
The solution is to provide function declarations before main().
char enterChar(); // and other function declarations
int main(void) {
....
}
// function definitions
char enterChar() { .... }
Depending on your use-case, it may be worth investigating using a more recent version of C, which doesn't have these implicit function declarations (e.g. C99 or C11)
When the prototype of a function is not declared, the compiler assumes that the return type is an int.
That is what it calls an implicit declaration.
and then, you go to declare enterChar that returns a char. Since the compiler had used an implicit declaration when it was called it in main, it complains about the conflicting types.
You can resolve that problem by providing an explicit declaration of the function before using it in main.
char enterChar();
It's a good practice to provide explicit declarations of all functions before they are used.
Functions must at least be declared before they are called; if possible, they should be defined before they are called.
When the functions are defined in the same source file from which they are called, move the definition of the function to precede the caller, like so:
char enterChar( void ) // void indicates function takes no arguments
{
// body of enterChar
}
int enterNum( void )
{
// body of enterNum
}
int main( void )
{
...
c = enterChar();
...
N = enterNum();
...
}
Yes, this makes the code read "backwards", but it eliminates some headaches.
When functions are defined in a different source file from which they are called, make sure you have a declaration of that function (using prototype syntax!) in place before the call. The declaration may appear at file scope (outside of any function), or within the function from which the call is made:
// enterChar and enterNum are *defined* in a different source file
int enterNum( void ); // declaration at file scope, valid for remainder
// of file
int main( void )
{
char enterChar( void ); // declaration within a block, only valid for
// duration of current block
...
c = enterChar();
...
}
In the case above, the declaration of enterNum is valid over the entire file, while the declaration for enterChar is only valid within the body of main; if any other function in the same source file wants to call enterChar, it must also have a declaration before the call. Either way, the declaration must precede the call.
The usual practice for handling declarations of functions defined in a different source file is to create a header file which contains the function declarations (not definitions!) and include that header in the file that defines the calling function(s):
/**
* main.c
*/
#include <stdio.h>
#include "utils.h" // contains declarations for enterChar and enterNum
int main( void )
{
...
c = enterChar();
...
N = enterNum();
}
Header file:
/**
* utils.h
*/
#ifndef UTILS_H // Include guard; prevents header file from being processed
#define UTILS_H // more than once per translation unit
char enterChar( void ); // void in the argument list indicates the function takes no arguments
int enterNum( void ); // an empty argument list in a declaration specifies that
// the function takes an *unspecified* number of arguments
// which is not the same thing, and not necessarily safe
#endif
Implementation file:
/**
* utils.c
*/
#include <stdio.h>
#include <stdlib.h>
#include "utils.h" // including our own header to make sure our declarations
// and definitions line up.
char enterChar( void )
{
// body of enterChar
}
int enterNum( void )
{
// body of enterNum
}
You'll notice that utils.c also includes utils.h. This is to make sure that our declarations and definitions are in sync.
You have "forward references" to undeclared functions. They need a function prototype, or implementing before being called. Without knowing what the function takes or returns, the compiler assumes int types, although I suspect some compilers will flag an error anyway.
You only posted one function, so I limit my example to that.
#include <stdio.h>
#include <string.h>
char enterChar(); // function prototype
int main(void)
{
char C;
//...
C = enterChar(); // function call
//...
return 0;
}
char enterChar() // function implementation
{
char input = 0;
//...
return input;
}
This is my code that I am compiling in C. Currently I have a global variable 'code' that is an array of structs(struct instruction). I've been trying to instead make this a local variable in main and pass it as a parameter. Also I believe this means I will need to have read file return a struct instruction*. I would greatly appreciate it if someone could explain, or show me how to properly use 'code' as a local variable. Also I am interested in what makes local variables better or more efficient than global variables. Thanks!
#include<stdio.h>
#include <stdlib.h>
typedef struct instruction{
int op; //opcode
int l; // L
int m; // M
} instr;
FILE * ifp; //input file pointer
FILE * ofp; //output file pointer
instr code[501];
void read_file(instr code[]);
char* lookup_OP(int OP);
void print_program(instr code[]);
void print_input_list(instr code[]);
int main(){
read_file(code);
print_input_list(code);//used for debugging
print_program(code);
}
void read_file(instr code[]){
int i = 0;
ifp = fopen("input.txt", "r");
while(!feof(ifp)){
fscanf(ifp,"%d%d%d",&code[i].op, &code[i].l, &code[i].m);
i++;
}
code[i].op = -1; //identifies the end of the code in the array
fclose(ifp);
}
You have to move your declarations inside the functions that need them:
#include <stdio.h>
#include <stdlib.h>
typedef struct instruction{
int op; //opcode
int l; // L
int m; // M
} instr;
void read_file(instr code[]);
char* lookup_OP(int OP);
void print_program(instr code[]);
void print_input_list(instr code[]);
int main(){
instr code[501]; // code[] declaration moved HERE!!!!
read_file(code);
print_input_list(code);//used for debugging
print_program(code);
}
void read_file(instr code[]){
int i = 0;
FILE * ifp; //ifp FILE* declaration moved HERE!!!!
ifp = fopen("input.txt", "r");
while(!feof(ifp)){
fscanf(ifp,"%d%d%d",&code[i].op, &code[i].l, &code[i].m);
i++;
}
code[i].op = -1; //identifies the end of the code in the array
fclose(ifp);
}
I've moved ifp declaration inside readfile() and code inside main().
The variable ofp has been removed, because it is not used.
If you are using ofp inside another function, declare it there.
Simple enough.
No real change in efficiency as you have currently coded it.
The only change is the storage for code will be from the stack
int main(){
instr code[501];
read_file(code);
print_input_list(code);//used for debugging
print_program(code);
}
I'll go ahead and try to answer the last part of the question:
Also I am interested in what makes local variables better or more
efficient than global variables.
There are a few differences between Local and Global defined variables.
Initialization. Global variables are always initialized to zero, where as local variables will have an unspecified/indeterminate value prior to being assigned. They don't have to be initialized as stated previously.
Scope. Global variables can be accessed by any function in the file (and even out of the file by using extern, without passing a reference to it. So, in your example you didn't need to pass a reference to code to the functions. The functions could have just accessed it normally. Local variables are defined only in the current block.
For example:
int main() {
int j = 0;
{
int i = 0;
printf("%d %d",i,j); /* i and j are visible here */
}
printf("%d %d",i,j); /* only j is visible here */
}
This would not compile, because i is no longer visible in the main code block. Things could get tricky when you have global variables named the same as local variables. It's allowed but not recommended.
Edit: Local variable initialization changes based on comments. Changed text in italics above.