We just learnt in school about function pointers in C and i wanted to try them out in a test program. The idea is obviously pretty simple. However, when i try to use result = (*funcPtr)(); i get an STATUS_ACCESS_VIOLATION exception but i can't tell what i did wrong. Any ideas on what i'm missing?
#include <stdio.h>
int fun1();
int fun2();
int (*funcPtr)(void);
int fun1() {
return 1;
}
int fun2() {
return 2;
}
int main(void) {
int input,result = 0;
scanf("%d",input);
if(input == 1) {
funcPtr = &fun1;
} else if(input == 2) {
funcPtr = &fun2;
}
result = (*funcPtr)();
printf("%d\n",result);
}
You forgot a & before input in the scanf. Therefore scanf writes not to the address of the input variable, but to its value (and the variable is uninitialized a this point).
Change that line to:
scanf("%d", &input);
to pass a pointer to input to scanf and not the value of input.
And as already pointed out by other users, do not forget to handle inputs other than 1 and 2. Otherwise you will call your uninitialized funcPtr variable, which most likly results in a Segmentation fault.
Related
There are some problems thatconfuse me:
The callee function needs return a structure, but there is not a structure statment in caller function.
If i have to write the declaration in the calling function,it can not be called packaging function.
If i return a structure pointer by callee function, but the structure is in the stack of the called function and will be destroyed after the end, which is not safe. Sometimes i get some warning or even wrong!
I have a limited ideas but it not good. I put the structure into the heap by malloc and return the void*pointer. But this gave birth to a new problem :after each call to this function, in the caller, I cannot release the heap through the free() function,the complier can not identify variable name of structure pointer. I think it verey dangerous. I want when the callee function quit,it can be released by itself.
This is the first time I came to this website to ask questions and I just came into contact with c language,If there is something stupid please point it out.
I have to write the structure declaration outside. This program for judging prime number, and I want to package the founction "judging_number". I do not want to write the structure declaration when I want to call the founction "judging_number".
Please give me some help, I would be very grateful.
Sorry, this is my fault. I compiled it with clang++, I saved it as *.cpp, but I wrote c code in it.
What I mean is, can I put the declaration in the called function to realize the function modularization, how can I not declare a structure before calling the function? Is there any way I can not write a declaration. Like use founction in stdio.h.It is as convenient as using the functions of the standard library. Only need to write a line of function call and pass parameters, the called function can return multiple results.
#include <stdio.h>
struct boundary{
int L;
int R;
};boundary *range;
int *get_number()
{
int *nPtr = (int *)malloc(sizeof(int));
do
{
printf("Please enter a vaild number for judging prime number.Or enter the number 1 to quit.\r\n");
scanf("%d", nPtr);
if (*nPtr == 1)
{
exit(1);
}
} while (*nPtr < 1);
printf("The object is %d\r\n", *nPtr);
return nPtr;
}
int judg_number(int N,boundary range){
if (N%range.L==0&&N!=2){
printf("The number %d is a composite number.\r\n", N);
}
else{
printf("The number %d is a prime number.\r\n", N);
}
return 0;
}
boundary* get_range(int N){
boundary *Ptr = (boundary *)malloc(sizeof(boundary));
*Ptr = {2,N-1};
printf("The range is between %d and %d .\r\n", Ptr->L, Ptr->R);
return Ptr;
}
int main(int argc,char**argv,char**env){
int*N;
while(1){
N=get_number();
range=get_range(*N);
judg_number(*N, *range);
free(N);
free(range);
}
getchar();
getchar();
return 0;
}
You dont need dynamic memory allocation here. If you want to retun an int, retun an int. If you want to retun a stuct return a struct.
You probably want this:
#include <stdio.h>
#include <stdlib.h>
struct boundary {
int L;
int R;
};
struct boundary range;
int get_number()
{
int n;
do
{
printf("Please enter a vaild number for judging prime number.Or enter the number 1 to quit.\r\n");
scanf("%d", &n);
if (n == 1)
{
exit(1);
}
} while (n < 1);
printf("The object is %d\r\n", n);
return n;
}
int judg_number(int N, struct boundary range) {
if (N % range.L == 0 && N != 2) {
printf("The number %d is a composite number.\r\n", N);
}
else {
printf("The number %d is a prime number.\r\n", N);
}
return 0;
}
struct boundary get_range(int N) {
struct boundary b = { 2, N - 1 };
printf("The range is between %d and %d .\r\n", b.L, b.R);
return b;
}
int main(int argc, char** argv, char** env) {
int N;
while (1) {
N = get_number();
range = get_range(N);
judg_number(N, range);
}
getchar();
getchar();
return 0;
}
BTW:
boundary get_range(int N) {... is invalid in C but valid in C++. In C it should be struct boundary get_range(int N) {...
I have a project in which I have to make a basic database in C. My problem lies that keep passing a variable n from function to function and at one point the value changes.
I have made a test program which illustrates the same issue I'm having:
#include <stdio.h>
#include <stdlib.h>
void functionTWO(int *n)
{
printf("\n%d",*n);
}
functionONE(int *n)
{
int i=0;
i++;
i++;
*n = i;
printf("\n%d", *n);
functionTWO(&n);
}
int main()
{
int n=0;
printf("%d",n);
functionONE(&n);
return 0;
}
The n in the second function is displayed as a very very high number, e.g.:
0
2
2752268
Now, I know this probably is intended, but could you guys kindly explain why this happens this way?
In your functionONE(), n is already a pointer. You don't need to pass the address of the pointer if you intend to change that value-at-the-address.
As an advice, always check the data types and enable the compiler warnings to help you.
functionONE()
your are passing a address of address. So it's printing address of n.
Now you want a correct output then n as double pointer **n.
void functionTWO(int **n)
{
printf("\n%d",**n);
}
First of all, in C int & n is not the reference of n, it is it's address.Now, what you've done is created an int - sent it's address to functionONE - did something to the value in that address and then sent the the argument's address to functionTWO, instead of sending the argument itself, becuase it's already a pointer. Do this instead:
#include <stdio.h>
#include <stdlib.h>
void functionTWO(int *n)
{
printf("\n%d",*n);
}
functionONE(int *n)
{
int i=0;
i++;
i++;
*n = i;
printf("\n%d", *n);
functionTWO(n); // <-- send the pointer, not it's address
}
int main()
{
int n=0;
printf("%d",n);
functionONE(&n);
return 0;
}
In functionONE, n is int *, just a pointer, when you do functionTWO(&n);, you get the address of n, so it output a big value.
The value being printed in functionTWO function is the address of the pointer variable n declared in functionONE.In that case you can either modify functionTWO like this
void functionTWO(int **n)
{
printf("\n%d",**n);
}
or
Just pass the value of the pointer variable like this
functionTWO(n);
Basically, why does it not just print the integers that are entered. Right now it just prints garbage value, but I do not know why it cannot access the values stored after it leaves the function. It only seems to get messed up after leaving the getIntegersFromUser function. If I run the for loop in the getIntegers function it does it properly, but why not in the main function?
Thanks in advance for your help.
#include <stdio.h>
#include <stdlib.h>
void getIntegersFromUser(int N, int *userAnswers)
{
int i;
userAnswers =(int *)malloc(N*sizeof(int));
if (userAnswers)
{ printf("Please enter %d integers\n", N);
for (i=0;i<N; i++)
scanf("%d", (userAnswers+i));
}
}
int main()
{
int i, M=5;
int *p;
getIntegersFromUser(M, p);
for (i=0;i<5;i++)
printf ("%d\n", p[i]);
return 0;
}
Also, this is a homework question, but it's a "Bonus Question", so I'm not trying to "cheat" I just want to make sure I understand all the course material, but if you could still try to give a fairly thorough explanation so that I can actually learn the stuff that would be awesome.
Pointers are passed by value. The function is using a copy of your pointer, which is discarded when the function ends. The caller never sees this copy.
To fix it, you could return the pointer.
int *getIntegersFromUser(int N)
{
int *userAnswers = malloc(...);
...
return userAnswers;
}
/* caller: */
int *p = getIntegersFromUser(M);
Or you could pass your pointer by reference so the function is acting on the same pointer, not a copy.
void getIntegersFromUser(int N, int **userAnswers)
{
*userAnswers = (int *) malloc(N*sizeof(int));
...
}
/* caller: */
int *p;
getIntegersFromUser(N, &p);
I'm trying to create two functions. The first function accepts integer inputs from the user until they are between 0 and 100. The seconds function display the validation to the stdOut.
However, it keeps giving me an error saying "Expected expression" when I call the function.
#include <stdio.h>
// function prototype for the function input
int input(int);
// function prototype for the function validate
int validate(int);
//main function
int main(void)
{
//calling the function input
input(int x)
//calling the function validate
validate(int y)
return 0;
}
// Function definition for input
int input(int a)
{
int r;
printf("Enter the int value of r\n");
scanf("%d",&r);
}
// Function definition for validate
int validate(int b)
{
int r;
if(r>= 0 && r<= 100)
printf("Valid number");
else
printf("Invalid");
}
There is at least one bug on almost every line of this program.
This is a standard problem for which there is a whole lot of incorrect advice out there (most importantly, only the strtol/strtoul/strtod family of functions should be used to convert strings to numbers; never use the atoi family and never use scanf) so I am going to give a complete worked example of how to write this program correctly, including proper use of comments.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
long read_number_in_range(const char *prompt, long lo, long hi)
{
// a signed 64-bit number fits in 21 characters, +1 for '\n', +1 for NUL
char buf[23], *endp;
long rv;
for (;;) {
puts(prompt);
if (!fgets(buf, sizeof buf, stdin)) {
perror("stdin");
exit(1);
}
errno = 0;
rv = strtol(buf, &endp, 10);
if (endp != buf && (*endp == '\0' || *endp == '\n')
&& !errno && rv >= lo && rv <= hi) {
return rv;
}
// if we get here, fgets might not have read the whole line;
// drain any remainder
if (!strchr(buf, '\n')) {
int c;
do c = getchar();
while (c != EOF && c != '\n');
}
puts("?Redo from start");
}
}
int main(void)
{
long val = read_number_in_range("Enter the int value of r", 0, 100);
// do something with val here
return 0;
}
Read on for line-by-line nitpicking of the original program.
#include <stdio.h>
Correct.
// function prototype for the function input
Comment redundant with code.
int input(int);
Function signature incorrect (see comments on body of function).
// function prototype for the function validate
Comment redundant with code.
int validate(int);
Function signature incorrect (see comments on body of function).
//main function
Comment redundant with code.
int main(void)
{
Correct.
//calling the function input
Comment redundant with code.
input(int x)
Variables cannot be declared inside function call expressions.
Return value of function is ignored.
Missing semicolon at end of line.
//calling the function validate
Comment redundant with code.
validate(int y)
Value returned from input should be passed to validate, presumably, instead of a new uninitialized variable.
Variables cannot be declared inside function call expressions.
Return value of function is ignored.
Missing semicolon at end of line.
return 0;
}
Correct.
// Function definition for input
Comment redundant with code.
int input(int a)
{
Parameter a is unnecessary.
int r;
Correct.
printf("Enter the int value of r\n");
Minor: use puts when there is nothing to format.
scanf("%d",&r);
Never use scanf.
}
Missing return r;.
// Function definition for validate
Comment redundant with code.
int validate(int b)
{
Function has no return value, so should be void validate(int b).
int r;
Unnecessary variable.
if(r>= 0 && r<= 100)
r should be b on this line.
printf("Valid number");
else
printf("Invalid");
Minor: again, puts.
}
Correct.
You have some stray ints in your calls, they need to go.
The calls should probably be:
x = input();
validate(x);
You can't pass an integer to a function and expect it to change in the caller's context, that is not how C's pass-by-value semantics work. You should just return the number from input() instead, i.e. its prototype should be int input(void);.
You need to add semicolons at the end of each line of code in your main() function, and also remove the type specifier in the function calls. Also, don't forget to declare the variables x and y somewhere:
int main(void)
{
int x=0;
int y=0;
//calling the function input
input(x);
//calling the function validate
validate(y);
return 0;
}
I bet the compiler asks you for an expression in some place where you write a function declaration with a missing semicolon.
//calling the function input
input(int x)
//calling the function validate
validate(int y)
Neither of these is a function call.
#include <stdio.h>
int input(int*);
int validate(int);
int main(void){
int x;
input(&x);
if(validate(x))
printf("Valid number");
else
printf("Invalid");
return 0;
}
int input(int *r){
printf("Enter the int value of r\n");
scanf("%d", r);
return *r;
}
int validate(int r){
return r>= 0 && r<= 100;
}
I found this puzzle in a C aptitude paper.
void change()
{
//write something in this function so that output of printf in main function
//should always give 5.you can't change the main function
}
int main()
{
int i = 5;
change();
i = 10;
printf("%d", i);
return 0;
}
Any solutions.?
define?
#include <stdio.h>
void change()
{
//write something in this function so that output of printf in main function
//should always give 5.you can't change the main function
#define printf_ printf
#define printf(a, b) printf_("5");
}
int main()
{
int i = 5;
change();
i = 10;
printf("%d", i);
return 0;
}
This is a POSIX answer that really does what the problem asks :)
It won't work on some architectures/compilers but it does here.
#include <stdio.h>
void
change () {
void _change();
_change();
}
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <sys/mman.h>
void
_change()
{
int main();
uintptr_t m=(uintptr_t)main;
uintptr_t ps=sysconf(_SC_PAGESIZE);
m/=ps;
m*=ps;
mprotect((void*)m,ps,PROT_READ|PROT_WRITE|PROT_EXEC);
char *s=(char*)(intptr_t)main;
s=memchr(s,10,ps);
*s=5;
mprotect((void*)m,ps,PROT_READ|PROT_EXEC);
}
int
main() {
int i=5;
change();
i=10;
printf ("%d\n",i);
return 0;
}
EDIT: This should make it more robust for people with boycotting headers.
void change()
{
//write something in this function so that output of printf in main function
//should always give 5.you can't change the main function
#define i a=5,b
}
Here's a really cheap answer:
void
change()
{
printf("%d", 5);
exit(0);
}
:-P
Here's another possibility:
void change()
{
char const *literal = "%d";
char * ptr = (char*)literal;
ptr[0] = '5';
ptr[1] = 0;
}
This is much more portable than changing the return address, but requires you to (a) have a compiler that pools string literals (most do), and (b) have a compiler that doesn't place constants in a read-only section, or be running on an architecture with no MMU (unlikely these days).
Anybody thought of using atexit?
void change (void)
{
static int i = 0;
if (i == 0) atexit (change);
if (i == 1) printf ("\r5 \b\n");
++i;
}
Note that there is no terminating newline in the main function, if we send 2 backspace characters to stdout, the 10 will be erased, and only the 5 will be printed.
Invoke the requisite #include, and replace the comment with the parenthesis-unbalanced text:
}
int printf(const char *s, ...) {
return fprintf(stdout,"%d",5);
Tested successfully. Thanks to dreamlax and Chris Lutz for bugfixes.
You have a local variable i in the stack that has a value of 5 to begin with.
With change(), you need to modify the next instruction to be 5 so you would need to buffer override to that location where 10 is set, and have it set to 5.
The printf("%d", i); call in main() doesn't end its output in a newline, the behavior of the program is implementation-defined.
I assert that on my implementation, a program that fails to write a terminating newline for the final line always prints 5 followed by a newline as its last line.
Thus, the output will always be 5, whatever the definition of change(). :-)
(In other words, what's the point of such questions, unless they're meant to run on particular hardware, compiler, etc.?)
void change()
{
#define printf(x,y) fprintf(stdout,x,y-5)
}
Simple:
void change()
{
printf("%d\n", 5);
int foo;
close(0);
close(1);
dup2(foo, 1);
dup2(foo, 0);
}
Slightly more sophisticated:
void change()
{
int *outfd = malloc(2 * sizeof(int));
char buf[3];
pipe(outfd);
if(!fork())
{
read(outfd[0], buf, 2);
if(buf[0] == '1' && buf[1] == '0')
{
printf("5\n");
}
else
{
write(1, buf, 2);
}
while(1);
}
else
{
close(1);
dup2(outfd[1], 1);
}
}
I suspect that the "correct" answer to this is to modify the return address on the stack within the change() function, so that when it returns the control flow skips the i=10 command and goes straight to the printf.
If so then that is a horrible, ugly question and the (non-portable) answer requires knowledge of the architecture and instruction set used.
How about something like this: (x86 only)
change()
{
__asm__( "mov eax, [ebp+4]\n\t"
"add eax, 4\n\t"
"mov [ebp+4], eax\n\t" );
}
Loving the answers in here. I got it to work in two lines.
void change()
{
//write something in this function so that output of printf in main function
//should always give 5.you can't change the main function
/* print a 5 */
printf("5\n");
/* Close standard output file descriptor */
close(1);
}
int main()
{
int i = 5;
change();
i = 10;
printf("%d", i);
return 0;
}
The 10 will never reach the output because after the change() function prints a 5, the stdout file descriptor is closed.
People can verify that using the following online C compiler.
http://www.tutorialspoint.com/compile_c_online.php
here is a different one:
void change()
{
#define printf(x,y) printf("5",x,y);
}
do I get the "smallest #define to solve a silly problem award"?
I am not sure this would always work, but what about locating the i variable on the stack like this:
void change()
{
int j, *p;
for (j=-100, p=&j; j<0; j++, p++)
if (*p == 10) { *p = 5; break; }
}