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; }
}
Related
So i have a piece of code where i want to store 5 random names no longer than 10 letters each
void printname(char *s);
int main() {
char NAME[10][5];
int NAMECOUNTER=0;
while(NAMECOUNTER<5) {
scanf("%s",NAME[NAMECOUNTER]);
printname(&NAME[NAMECOUNTER]);
NAMECOUNTER++;
}
}
void printname(char *s) {
printf("Hello %s\n",*s);
return;
}
And lets say i want the name to print itself through function Printname. Why does this not work and prints "Hello (null)"?
One problem I see
char NAME[10][5];
Should be
char NAME[5][11];
This way you're declaring 5 name slots, each with 10 char max. The extra space is for the string null terminator.
You have
void printname(char *s) {
printf("Hello %s\n",*s);
return;
}
and you need
void printname(char *s) {
printf("Hello %s\n",s); // Took off the * from the *s
return;
}
because s is already your pointer.
I give 6 glitches to fix. See comments prefacing #<num>
#include <stdio.h>
#include <stdlib.h>
void printname(char *s);
int main() {
char NAME[5][11] = {0}; // #1 value initialize to zero
// #2 the second dimension should be 11, since 10 letters plus null-character
int NAMECOUNTER=0;
while(NAMECOUNTER<5) {
scanf("%10s",NAME[NAMECOUNTER]); // #3 %10s width specifier, limit the length of name up to 10 character long
while ( (ret = getchar()) != '\n') ; // #4 trim exceeding characters
printname(NAME[NAMECOUNTER]); // #5 no &
NAMECOUNTER++;
}
}
void printname(char *s) {
printf("Hello %s\n",s); // #6 no *
return;
}
Your code doesn't even print anything to me, it just freeze and closes. Also it's not so clear.
You are mistyping the "NAME" array inside printname. This function does not have a return value, since it has a void return, so you shouldn't type any return. Also you can save some code lines writing it before main function which is the best practice:
void printname(){
//todo
}
int main(){
return 0;
}
This is a better way to implement your function:
void printname(char Names[5][11], int index){
printf("Hello %s\n", Name[index]);
}
You could replace the while structure with for structure, since it is the best application for the purpose in that case:
Your code piece:
while(NAMECOUNTER<5) {
scanf("%s",NAME[NAMECOUNTER]);
printname(&NAME[NAMECOUNTER]);
NAMECOUNTER++;
}
You don't have to put "&" in the first argument of printname.
Best:
for(NameCounter = 0; NameCounter < 5; NameCounter++){
scanf("%s",NAME[NAMECOUNTER]);
printname(NAME[NAMECOUNTER]);
}
Also make sure to keep your code indentation clear. This is your final code:
void printname(char Names[][11], int index){
printf("Hello %s\n", Names[index]);
}
int main(){
char NAME[5][11];
int NAMECOUNTER;;
for(NAMECOUNTER = 0; NAMECOUNTER < 5; NAMECOUNTER++){
scanf("%s", NAME[NAMECOUNTER]);
printname(NAME, NAMECOUNTER);
}
}
I have two source files: counter.c and main.c:
counter.c:
#include <stdio.h>
int counter(void) {
for(int i = 0; i < 5; i++)
printf("%d\n", i);
return 0;
}
main.c:
#include <stdio.h>
int counter(void);
int main(void) {
char *line;
counter();
return 0;
}
What I want to do is to have each line that counter() prints to be assigned to the line variable so I can do printf("%s\n", line) myself in main.c.
(edit) Unfortunately, this example doesn't translate well to my actual code so maybe I'll just put it here:
https://github.com/venetwork/venet/blob/master/venet-show.c
What I need is to access the result of running this code on a line by line basis in a different source file (GTK3 GUI). The main function for my combined code will be in this file so main() in venet-show.c should be changed to, say, show(). As of this moment I just use an IO Channel (https://developer.gnome.org/glib/stable/glib-IO-Channels.html) to "stream" the output of venet-show.c to the GUI but I want to get ride of it. Any ideas?
So we pass an allocated memory address and not a pointer like you had to the function. This has storage for the result. Use the return snprintf to advance the pointer so not to overwrite previous results.
#include <stdio.h>
int counter(char *answer, size_t array_len) {
for(int i = 0; i < 5; i++)
{
size_t chars_printed = snprintf(answer, array_len, "%d\n", i);
answer+=chars_printed;
array_len-=chars_printed;
}
return 0;
}
int main(void) {
char line[10000];
counter(line, sizeof(line));
printf("%s", line);
return 0;
}
I need to read a word from main function and convert the characters in UCASE if the first character is LCASE and vice versa using the user defined function.I tried ways for returning the array from function but still I am lacking some core ideas. Please debug this program and explain the way it works.
#include <stdio.h>
#include <string.h>
int* low (char str)
{
int i;
for (i=1; i<strlen(str);i++)
{
if(str[i]<91)
{
str[i]=str[i]+32;
}
else
{
}
}
return &str;
}
int* high (char str[50])
{
int i;
for (i=0; i<strlen(str);i++)
{
if(str[i]>91)
{
str[i]=str[i]-32;
}
else
{
}
}
return &str;
}
void main()
{
char str[50];
char* strl;
printf("Enter any string....\n");
scanf("%s",str);
if (str[0]<91)
{
*strl=low(str);
}
else
{
*strl=high(str);
}
printf("Converted string is %s.",*strl);
}
There is already a problem here:
So if you are saying this code is perfect and you want us to debug it and explain how (on earth) this works, then here you go.
In function int* low (char str), you have if(str[i]<91). Thats a problem right there. str is a char received as an argument, and hence str[i] is a straight compile-time error.
Another one to deal with is the return statement.
You have a statement:
return &str;
which would return the address of str, which by the way is a char, whereas function low is supposed to return a pointer to an int.
The same is applicable to high function as well.
Suggestion: Leave aside this bad code and get a beginner level C programming book first. Read it and the try some codes out of it.
A few inputs for improvement: (Which you may not comprehend)
change
void main()
to
int main(void)
Why? Refer this legendary post: What should main() return in C and C++?
Secondly, int both functions you are using strlen() in loop which will always return a fixed value. So, instead of
for (i=0; i<strlen(str);i++)
I'd suggest,
size_t strlength = strlen(str);
for (i=0; i < strlength; i++)
You can try the code and method as below:
#include <stdio.h>
#include <string.h>
char* caseConverter (char *str)
{
int i;
for (i=0; i<strlen(str);i++)
{
if(str[i]>=65 && str[i]<=90)
{
str[i]=str[i]+32; //To lower case
}
else if((str[i]>=97 && str[i]<=122))
{
str[i]=str[i]-32; //To upper case
}
else
printf("%c is not an alphabet \n",str[i]);
}
return str;
}
void main()
{
char inputStr[50]= "Stubborn";
char* opStr= caseConverter(inputStr);
printf("Converted string is %s",opStr);
}
I am trying to code the printf function. The problem is that my code is getting very messy and I need some help to try to make it organized and working (hopefully). I have been told that I should use "array of function pointers" so I tried below (ft_print_it) as you can see but I do not know how to how to structure my code so that I can use a big array of function pointer to put every function like int_decimal_octal and friends. Can you help me on that? Where can I call them from?
Also, I realized the little function below (cast_in_short) is giving me the same result as printf if I write the output with my ft_putnbr. My second question is thus: Can I make my printf work with little functions like this? Thank you so much.
int cast_in_short(int truc)
{
truc = (short)truc;
return (truc);
}
/*
here in the main I noticed that I get the same behaviour
between my putnbr and printf thanks to my little function
cast_in_short. This is the kind of function I want to use
and put into an array of pointer of functions in order
to make my printf work
*/
int main()
{
int n = 32769;
n = cast_in_short(n);
ft_putnbr(n);
printf("\n");
return (0);
}
/* function to launch ft_print_it */
int ft_print_str_spec(va_list ap, char *flag)
{
if (ft_strlen(flag) == 1)
ft_putstr(va_arg(ap, char *));
else
{
ft_nbzero(ap, flag, 0);
ft_putstr(va_arg(ap, char *));
}
return (1);
}
int ft_print_oct(va_list ap, char *flag)
{
if (ft_strlen(flag) == 1)
ft_putnbr(decimal_octal((va_arg(ap, int))));
else
{
ft_nbzero(ap, flag, 1);
ft_putnbr(decimal_octal((va_arg(ap, int))));
}
return (1);
}
#include "libft.h"
#include <stdarg.h>
#include <stdio.h>
char *ft_strjoin2(char const *s1, char const c);
#include "libft.h"
#include <stdarg.h>
#include <stdio.h>
int decimal_octal(int n) /* Function to convert decimal to octal */
{
int rem;
int i;
int octal;
i = 1;
octal = 0;
while (n != 0)
{
rem = n % 8;
n /= 8;
octal += rem * i;
i *= 10;
}
return (octal);
}
I think the best way to organize your code to avoid the function like your "flag_code" is to use an array of structure. With structure that contain a char (corresponding to the flag) and a function pointer.
For example :
typedef struct fptr
{
char op;
int (*ptr)(va_list);
} fptr;
And instatiate it like that (with { 'flag', name of the corresponding function} ) :
fptr fptrs[]=
{
{ 's', ft_print_nb_spec },
{ 'S', ft_print_nb_up },
{ 0, NULL }
};
Then when you know have char after the % (the flag) you can do something like this :
int i = -1;
while (fptrs[++i].op != flag && fptrs[i].op != 0);
if (fptrs[i].op != 0)
{
fptrs[i].ptr();
}
For exemple if flag = 'S' the while loop will stop when i = 1 and when you call fptrs[1].ptr() you will call the corresponding function in the structure.
I think instead of making your code messy by using function pointers, because in the end you cannot specialize printf function without providing the format, in C there is no function overloading or template functions. My suggestion is to special printf function by type.
// print seperator
void p (int end)
{ printf(end?"\n":" "); }
// print decimal
void pi (long long n)
{ printf("%lld",n); }
// print unsigned
void pu (unsigned long long n)
{ printf("%llu",n); }
// print floating point
void pf (double n)
{ printf("%g",n); }
// print char
void pc (char n)
{ printf("%c",n); }
// print string
void ps (char* n)
{ printf("%s",n); }
Test try here
pi(999),p(0),pf(3.16),p(0),ps("test"),p(1);
Output
999 3.16 test
Another option
In theory you can define polymorphic print function in a struct, in case you can do something like this. I haven't tested this yet.
struct Node
{
enum NodeType {Long,Double,Char,String} type;
union {long l,double d,char c,char* s};
};
void p(Node* n)
{
switch (n->type)
{
case Node::NodeType::Long: printf("%ld", n->l);
case Node::NodeType::Double: printf("%g",n->d);
case Node::NodeType::Char: printf("%c",n->c);
case Node::NodeType::String: printf("%s",n->s);
}
}
Using printf and without using any looping or branching?
Recursion is your friend:
int print_char_by_char(char * p)
{
*p && print_char_by_char(p+1);
printf("%c", *p);
return 1;
}
int main(void)
{
print_char_by_char("alk");
return 0;
}
Extending the answer of #alk, you can use recursion and pointers to function in order to avoid the use of logical operators:
#include <stdio.h>
void dummy(char *p);
void print(char *p);
void (*fp[])(char *) = {dummy, print};
void dummy(char *p)
{
(void)p;
}
/**
* Read *p as bool (0 or 1) using bitwise operators
* Call print() recursively if 1
* Call dummy() if 0 and exits from function
*/
void print(char *p)
{
char i = *p;
i |= i >> 4;
i |= i >> 2;
i |= i >> 1;
printf("%c", *p);
fp[i & 1](p + 1);
}
int main(void)
{
print("Hello world\n");
return 0;
}
Well, your question is
How do you print a string in C character by character?
Using printf and without using any looping or branching?
The simplest answer for that is
#include<stdio.h>
int main()
{
char a[]="blablabla";
printf("%s",a);
return 0;
}
This is the answer to your question. If this is not what you wanted, then Specify your exact question giving more details.
#qwe2004, tell your professor that the Stack Overflow community agrees that it can't be done. If he says it can be done, we are all interested in seeing his clever and cunning way of doing it, and learn. (Tell him also we will be critical of hidden branching and logical tests.)