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.)
Related
The code doesn't work in my Xcode compiler. It says *&point expected '('. I really don't know what goes wrong. It should have worked.
#include<stdio.h>
#include<stdlib.h>
void transformCopy(int *point);
void transformTrue(int *&point);
int main(){
int *a,*b,i=0;
transformTrue(a);
transformCopy(b);
for(i=0;i<5;i++) {a[i]=i;}
for(i=0;i<5;i++){printf("%d ",a[i]);}
printf("\n");
for(i=0;i<5;i++) {b[i]=i;}
for(i=0;i<5;i++){printf("%d ",b[i]);}
printf("\n");
return 0;
}
void transformCopy(int *point){
point=(int*)malloc(5*sizeof(int));
}
void transformTrue(int *&point){
point=(int*)malloc(5*sizeof(int));
}
*&point expected '('.
References do not exist in C ( void transformTrue(int *&point) ), this is C++ code, not C
If you want to have the equivalent in C you have to use void transformTrue(int **point) and you have to call transformTrue(&a);
If I change your code to do in C what it is done in C++ (see comments) :
#include<stdio.h>
#include<stdlib.h>
void transformCopy(int *point);
void transformTrue(int ** point); /* ** rather than *& */
int main(){
int *a,*b = 0,i=0;
transformTrue(&a); /* &a rather than just a */
transformCopy(b);
for(i=0;i<5;i++) {a[i]=i;}
for(i=0;i<5;i++){printf("%d ",a[i]);}
printf("\n");
for(i=0;i<5;i++) {b[i]=i;}
for(i=0;i<5;i++){printf("%d ",b[i]);}
printf("\n");
return 0;
}
void transformCopy(int *point){
point=(int*)malloc(5*sizeof(int));
}
void transformTrue(int ** point){ /* ** rather than *& */
*point=(int*)malloc(5*sizeof(int)); /* *point = rather than point = */
}
transformTrue(&a) modifies the value of a, but transformCopy(b); does nothing except locally (and a memory leak) and back in main the value of b is still 0, the program will crash when you will try to write in invalid addresses
one possibility is to change transformCopy like that :
int * transformCopy(){
return (int*)malloc(5*sizeof(int));
}
and of course the call to have b = transformCopy();
This question already has answers here:
How to find the size of an array (from a pointer pointing to the first element array)?
(17 answers)
Closed 6 years ago.
Ok, so the idea of the task I have (I am the student) is to allow user to insert a string of words in this form: num1_num2_num3..._numN. The code should create an array X, give it memory dynamically and then I should fill X with numbers from string user inserted. Simple as that. Well, in the function stringuniz() I thought I had it all figured out but it simply wont work. It gets the first number well but it then stops and I think its because of the break. Break behaves (if I am right) like it breaks the entire code and not just the loop. Do you guys have an idea why is this happening?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void stringuniz(char *);
int *x;
int main(){
char s[50];
int i;
puts("Unesite string brojeva u formatu br1_br2_...brN: ");
gets(s);
stringuniz(s);
for(i=0;i<(sizeof(x)/sizeof(int));i++)
printf("%d",x[i]);
}
void stringuniz(char *s){
int duz,c=0,i,j,k=0,m=0;
char b[10];
duz=strlen(s);
for(i=0;i<duz;i++)
if(s[i]=='_')
c++;
x=(int*)malloc((c+1)*sizeof(int));
if(x==NULL) exit(1);
for(i=0;i<c+1;i++){
for(j=m;j<duz;j++){
if(s[j]!='_'){
b[k++]=s[j];
m++;
}
else{
b[k]='\0';
x[i]=atoi(b);
k=0;
m++;
break;
}
}
}
}
This
(sizeof(x)/sizeof(int)
won't give you the size of the array. sizeof(x) is the bytesize of int* (likely 4 or 8).
You'll need to remember the size as implied by the number of _ in the string.
Also you have some off-by-one errors in there and for future reference, you might want to choose more descriptive variable names for code you decide to post publicly.
The code worked for me once I changed it to:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void stringuniz(char *);
int *x;
int x_size = 0;
int main(){
char s[50];
int i;
puts("Unesite string brojeva u formatu br1_br2_...brN: ");
fgets(s,50,stdin);
stringuniz(s);
for(i=0;i<x_size;i++)
printf("%d\n",x[i]);
}
void stringuniz(char *s){
int duz,c=0,i,j,k=0,m=0;
char b[10];
duz=strlen(s);
for(i=0;i<duz;i++)
if(s[i]=='_')
c++;
x=malloc((c+1)*sizeof(int));
x_size = c+1;
if(x==NULL) exit(1);
for(i=0;i<=c+1;i++){
for(j=m;j<=duz;j++){
if(s[j]!='_' && s[j]!='\0'){
b[k++]=s[j];
m++;
}
else {
b[k]='\0';
x[i]=atoi(b);
k=0;
m++;
break;
}
}
}
}
void stringuniz(char *);
int *x;
int main(){
[...]
}
void stringuniz(char *s){
[...]
}
I don't know why many ppl teach it this way, but there is absolute no use in having main somewhere in the middle of a source file, and putting it at the end also allows you to get rid of the forward declarations. So, I would write it this way:
int *x;
void stringuniz(char *s){
[...]
}
int main(){
[...]
}
Then you should start using the space character more.
stringuniz(s);
for(i=0;i<(sizeof(x)/sizeof(int));i++)
printf("%d",x[i]);
In a comment, alain already pointed out, that sizeof(x) will return the size of a pointer. So, you need a different way to figure out the size of the array. One way is to add a variable size_t x_len; besides int * x;. Also, you should use curley brackets even for one line statements, believe me, not only makes it the code more readable, it also prevents introducing bugs on later changes.
for (i = 0; i < x_len; i++) {
printf("%d", x[i]);
}
.
void stringuniz(char *s){
int duz,c=0,i,j,k=0,m=0;
char b[10];
b will hold the word the user enters. If his word is longer then 9 characters, you get a buffer overflow here.
duz=strlen(s);
for(i=0;i<duz;i++)
if(s[i]=='_')
c++;
You are counting the number of words here. So, please use more descriptive names like num_words instead of c. BTW: This is the x_len mentioned above.
x=(int*)malloc((c+1)*sizeof(int));
No need to cast return value of malloc. Actually it might hide bugs. Also, I would use sizeof(*x) instead of sizeof(int), because if you change the type of x, in your statement, you also would have to change the malloc call. In my statement, the malloc call doesn't need to be touched in any way.
x = malloc((c+1) * sizeof(*x));
if(x==NULL) exit(1);
for(i=0;i<c+1;i++){
for(j=m;j<duz;j++){
if(s[j]!='_'){
b[k++]=s[j];
You are constantly overwriting b with the next word being read. Since you're not using it anyway, you can just skip this line.
m++;
}
else{
b[k]='\0';
x[i]=atoi(b);
k=0;
m++;
break;
And this break; only breaks out of the innermost for (j-loop.
}
}
}
}
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);
}
}
I bought a Programming book at a yard sale for $2 because I've always wanted to learn how to code but don't have the money and resources for school. I've gotten through the first few chapters just fine, but I've also had the solutions to the problems I was working on. But the chapter is missing a few of the pages after the chapter summary when they start listing problems. I was wondering if you guys could help me out.
Here is the problem. Note: Needs to use a recursive function.
#include <stdio.h>
#include <stdlib.h>
void binaryPrinter(int value, int *numberOfOnes);
void print(char c);
//You do not need to modify any code in main
int main()
{
char value;
int result = 1;
while(result != EOF)
{
result = scanf("%c",&value);
if(result != EOF && value != '\n')
{
print(value);
}
}
}
//#hint: This is called from main, this function calls binaryPrinter
void print(char c)
{
}
//#hint: this function is only called from print
void binaryPrinter(int value, int *numberOfOnes)
{
}
void print(char c)
{
int n = CHAR_BIT;
binaryPrinter((unsigned char)c, &n);
putchar('\n');
}
void binaryPrinter(int value, int *numberOfOnes)
{
if((*numberOfOnes)--){
binaryPrinter(value >> 1, numberOfOnes);
printf("%d", value & 1);
}
}
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; }
}