Why is my %d specifier putting the "-" after the number? [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
I am trying to make a C implementation of the printf function. Why does my %d specifier return
+2048 - 0 - 1337-!
instead of
-2048 - 0 - -1337!
when I run
int main() {
int ret_val = my_printf("%d - %d - %d!\n", 2048, 0, -1337);
return ret_val;
}
This is my %d specifier code
{
int value = va_arg(args, int);
char buffer[32];
int index = 0;
if (value < 0)
{ //Repair this
buffer[index++] = '-';
value = -value;
}
if (value == 0)
{
buffer[index++] = '0';
}
else
{
while (value > 0)
{
buffer[index++] = '0' + (value % 10);
value /= 10;
}
}
for (int i = 0; i < index / 2; i++)
{
char temp = buffer[i];
buffer[i] = buffer[index - i - 1];
buffer[index - i - 1] = temp;
}
write(1, buffer, index);
size += index;
break;
}
I have tried switching these 2 lines with each

The reason for the symptoms reported by the OP has been quickly and correctly addressed by #EricPostpischil in the comments section.
The problem with writing code from the wrong perspective is that one winds up writing far too much code. Then, lost in the fog of verbose code, patches and bandages are applied that don't quite fulfil the need.
Simply fill the 32-byte buffer from right to left, prefix the minus sign if necessary, and write the correct number of bytes to the output.
int val = va_arg( args, int );
int absVal = abs(val);
char buf[ 32 ];
int i = sizeof buf;
do buf[--i] = (char)('0' + (absVal%10)); while((absVal/= 10) > 0);
if( val < 0 )
buf[--i] = '-';
write( 1, buf + i, sizeof buf - i );
No muss, no fuss trying to reverse the array... or most of it...

Related

String or file entropy [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to write string\file entropy calculator. Here is code I wrote but it doesn't work:
double entropy(char* buf)
{
int* rgi = (int*)_alloca(256);
int* pi = rgi + 256;
double H = 0.0;
double cb = sizeof(buf);
for (int i = sizeof(buf); --i >= 0;)
{
rgi[buf[i]]++;
}
while (--pi >= rgi)
{
if (*pi > 0)
{
H += *pi * log2(*pi / cb);
}
}
return -H / cb;
}
What am I doing wrong?
I think you have 4 problems
1) The allocated memory is never initialized
2) Too little memory is allocated as you only allocate 1 byte for each integer
3) Use of char for buf may be a problem as char may be signed
4) sizeof(buf) gives you the size of a char pointer but not the size of the buffer
Besides that I think you make the code too complicated by iterating backwards.
Try this:
double entropy(unsigned char* buf, size_t bufsize)
{
int* rgi = (int*)_alloca(256 * sizeof *rgi);
memset(rgi, 0, 256 * sizeof *rgi);
double H = 0.0;
double cb = bufsize;
for (size_t i = 0; i < bufsize; ++i)
{
rgi[buf[i]]++;
}
for (int i = 0; i < 256; ++i)
{
if (rgi[i] > 0)
{
H += rgi[i] * log2(rgi[i] / cb);
}
}
return -H / cb;
}

While loop doesn't initialize [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I've got a problem. Here is a function that processes the width of a wide-string. My program is entering an infinite loop after BREAKPOINT 1. What's wrong with my loop?
static void ft_wstr_width(void)
{
wchar_t *temp;
size_t delta;
size_t len;
size_t i;
wint_t wc;
len = ft_wstrlen(g_ws);
delta = (size_t)g_fmt.width - ft_wstrsize(g_ws);
printf("(%d %zd)\n", g_fmt.width, ft_wstrsize(g_ws));
temp = (wchar_t *)malloc(sizeof(wchar_t) * (len + delta + 1));
temp[len + delta] = L'\0';
if (g_fmt.flags[0])
{
wc = (QWSZ ? L'0' : L' ');
i = 0;
while (i < delta);
{
temp[i] = wc;
++i;
}
ft_wcopy(temp, g_ws, delta, len);
}
else
{
printf("[bp0]"); getchar(); // BREAKPOINT 0
ft_wcopy(temp, g_ws, 0, len);
i = len;
printf("[bp1]"); getchar(); // BREAKPOINT 1
while (i < len + delta);
{
printf("[bp2]"); getchar(); // BREAKPOINT 2
temp[i] = L' ';
++i;
}
}
printf("[bp3]"); getchar(); // BREAKPOINT 3
free(g_ws);
g_ws = temp;
}
-----UBUNTU TERMINAL OUTPUT-----
stanislav:gh_ft_printf >>: ./a.out
(15 3)
[bp0]
[bp1] No reaction here (program keeps running) and
^C <---- I have to kill the process with Ctrl+C
while (i < len + delta);
Semi-colon.

what does "not all control paths return a valueā€¯ mean in this program? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I wrote a code that takes inputs until an EOF integer (999999 in this case) is typed. Then it sorts the numbers and searches for our needle (an integer) in that array of integers (called haystack). Now I am facing a problem in my searching algorithm. While compiling it shows me a warning:
'search': not all control paths return a value
I think it means that the function might not return anything in some cases but the problem is that i can't think of any such case. I even checked my program with a lot of values and it always gave me the correct output. Can anyone help me figure out where the problem lies. I was use some windows native tools compiler for this.
Also if anyone has seen the CS50 pset3 find problem which is related to this, I used the same search function there too but while compiling the code in CS50 IDE the program never showed whether it found the needle in haystack. It only arranged them in increasing order and then stopped after that.
#include <stdio.h>
#include "cs50.h"
#include <stdlib.h>
bool search(int value, int values[], int n);
void sort(int values[], int n);
// maximum amount of hay
#define MAX 65536
int main(int argc, string argv[])
{
// ensure proper usage
if (argc != 2)
{
printf("Usage: ./find needle\n");
return -1;
}
// remember needle
int needle = atoi(argv[1]);
// fill haystack
int size;
int haystack[MAX];
for (size = 0; size < MAX; size++)
{
// wait for hay until EOF
printf("\nhaystack[%i] = ", size);
int straw = GetInt();
if (straw == 999999)
{
break;
}
// add hay to stack
haystack[size] = straw;
}
printf("\n");
// sort the haystack
sort(haystack, size);
// try to find needle in haystack
if (search(needle, haystack, size))
{
printf("\nFound needle in haystack!\n\n");
return 0;
}
else
{
printf("\nDidn't find needle in haystack.\n\n");
return 1;
}
}
/**
* Returns true if value is in array of n values, else false.
*/
bool search(int value, int values[], int n)
{
/* TODO: implement a searching algorithm */
int first = 0;
int last = n;
int middle = (first + last) / 2;
while (first + 1 < last)
{
if (value == values[middle])
{
return true;
break;
}
if (value == values[first])
{
return true;
break;
}
if (value == values[last])
{
return true;
break;
}
if (value < values[middle])
{
last = middle;
middle = (first + last) / 2;
}
if (value > values[middle])
{
first = middle;
middle = (first + last) / 2;
}
}
if (first + 1 >= last)
{
return false;
}
}
/**
* Sorts array of n values.
*/
void sort(int values[], int n)
{
// TODO: implement an O(n^2) sorting algorithm
for (int j = 1; j < n; j++)
{
for (int i = 0; i < (n - 1); i++)
{
if( values[i + 1] < values[i])
{
int b = values[i + 1];
values[i + 1] = values[i];
values[i] = b;
}
}
}
for (int k = 0; k < n; k++)
{
printf("haystack[%d] = %d ", k, values[k]);
}
}
The compiler does not execute your code. It does not do value tracking. While you can reason about the values of variables and expressions, this is generally an unsolvable problem for the compiler.
Your compiler tells you that it doesn't know what to return from search when control reaches the function's closing }.
BTW, it is a bad idea to write a function named sort, since the C Standard Library contains a function with the same name.

Markov chain (c code on windows fails) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to get work this piece of code from Kernighan's book The practice of programming on my workstation(windows 7 + vs2015 community edition)
I get a strange error.
void generate(int nwords) {
State *sp;
Suffix *suf;
char *prefix[NPREF];
char *w = NULL;
int i, nmatch;
for (i = 0; i < NPREF; i++)
prefix[i] = NONWORD;
for (i = 0; i < nwords; i++) {
sp = lookup(prefix, 0);
nmatch = 0;
for (suf = sp->suf; suf != NULL; suf = suf->next) {
if (rand() % ++nmatch == 0) {
w = suf->word;
}
if (nmatch == 0)
printf("internal error: no suffix %d %s", i, prefix[0]);
if (strcmp(w, NONWORD) == 0)
break;
printf("%s ", w);
memmove(prefix, prefix + 1, (NPREF - 1) * sizeof(prefix[0]));
prefix[NPREF - 1] = w;
}
}
}
for (suf = sp->suf; suf != NULL; suf = suf->next)
Unhandled exception at 0x000000013F5C1564 in CompareCandCsharp.exe:
0xC0000005: Access violation reading location 0x0000000000000010.
My implementation is similar to described here - Working with arrays and reading text files
Seems algorithm works - but on my computer it fails. I can't find mindfull porpose for this. Could you please give your suggestions.
After several hours of debugging I have found a small mistake in expected method.
for (suf = sp->suf; suf != NULL; suf = suf->next) {
if (rand() % ++nmatch == 0) {
w = suf->word;
}
There is no bracket after if in this line so all other code in method try set w many times and of course it leads to memory errors =). Thanx for minusing my question before reading it =))

Caesar Cipher Algorith Shifting C [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
So I was writing a C program to make use of caesar algorithm using a custom table, where I will give the table and shifting will be done using that table e.g the text "abc" according to table "abc" with key=1 should be ciphered as bca, however i am having difficulty on the last characters if key+index of letter is higher than the length of the table stored here is my code
void encrypt (char table[],char entext[],char text[],int key)
{
int i,j;
int k = strlen(table);
//int result = (key + k);
for (i=0;i<strlen(table);++i)
{
j = 0;
if (text[i]!='\0')
{
while (text[i]!=table[j])
{
j++;
}
if ((j+key)>k)
{
j=(j+key)%k;
//j = (result - j);
}
else
j = j + key;
entext[i] = table[j];
}
}
entext[i+1] = '\0';
puts(entext);
}
int main()
{
char table[100] , text[100] , entext[100] , c;
int i , j , key;
printf("Enter the text : ");
gets(text);
printf("Enter the table : ");
gets(table);
printf("Enter the key : ");
scanf("%d",&key);
encrypt(table,entext,text,key);
system("pause");
return 0;
}
if ((j+key)>k)
should be
if ((j+key)>=k)
Besides, this check is completely unnecessary because of how mod works. I will take the liberty to rewrite your code so it looks nicer:
void encrypt (char table[],char entext[],char text[],int key)
{
int i,j;
int k = strlen(table);
//int result = (key + k);
for (i=0;i<strlen(table);++i)
{
if (text[i]!='\0')
{
for(j=0; text[i] != table[j] ;j++);
entext[i] = table[(j+key)%k];
}
}
entext[i+1] = '\0';
puts(entext);
}
I believe you could make this "table" lookup more efficient by indexing the value of the char itself, but unless you are dealing with pretty big input, this won't really make a difference.
void encrypt (char table[], char entext[], char text[], int key) {
int i,j;
int k = strlen(table);
for (i=0;text[i];++i){
for(j=0;table[j] && text[i]!=table[j];++j)
;
if(table[j]=='\0')//character not find at table
entext[i] = text[i];//Not slide. // or Error?
else {
j += key;
if(j>=k)
j -= k;//j = j % k
entext[i] = table[j];
}
}
entext[i] = '\0';
puts(entext);
}

Resources