While loop doesn't initialize [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 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.

Related

Why is my %d specifier putting the "-" after the number? [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 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...

remove duplicates in a string with a buffer [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 1 year ago.
Improve this question
I’m trying to remove duplicates in a string using a map. Running it through GDB I'm not able to figure out where the code is failing, though the logic to me seems right.
Could anyone please point out the mistake?
int main() {
char *str="I had my morning tea";
int len = strlen(str);
int dupArr[256] = {0};
//Build the map
int i=0;
for(i;i<256;i++)
dupArr[str[i]]++;
//If the count is 1 then print that value.
i=0;
for(i;i<256;i++) {
if(dupArr[str[i]] == 1) {
printf("%c\n",str[i]);
}
}
}
output
I h y o r i g t % c 4 # } ` 8 � F J
I get up to 't' ,which is correct but then i see magic chars.
Your string has length of len but you are traversing till 256 which is out of bound.
Use len when inserting into the hash.
int i=0;
for(i;i<LEN;i++)
dupArr[str[i]]++;
Also if your are checking the duplicates then it should be bigger than 1 since your are ++ the first encountered char
if(dupArr[str[i]] > 1)
In addition to Mark Ezberg's good answer, note that dupArr[str[i]]++; poses a problem when str[i] < 0.
Better to treat the characters as unsigned char:
int dupArr[UCHAR_MAX + 1] = {0};
....
dupArr[(unsigned char) str[i]]++;
Rolling this and other ideas together:
int main(void) {
char *str="I had my morning tea";
size_t dupArr[UCHAR_MAX + 1] = {0};
unsigned char *s = (unsigned char *) str;
while (*s) {
dupArr[*s]++;
s++;
}
for(unsigned i = 0; i <= UCHAR_MAX; i++) {
// A duplicate is when dupArr[i] is _more_ than 1.
if(dupArr[i] > 1) {
printf("%c\n",str[i]);
}
}
}

what is the best way to convert an integer into a bitstring in C [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I need to convert an integer into a bit string in C. I have written a function to achieve this (example) & need to know a better solution for it.
eg:
char* int_to_bin(int n)
{
char arr[] = "00000000000000000000000000000000"; // 32 zeros , coz int => 32 bit
int pos = 0;
while(n!=0)
{
char element = (n%2==0)?'0':'1';
arr[pos] = element;
n /= 2;
pos++;
}
char *str = malloc(sizeof(char)*(pos+1)); // need to malloc for future use
for(int i = 0; i<pos; i++) // get the reverse
{
*(str+i) = arr[pos-1-i];
}
*(str+pos) = '\0';
return str;
}
You can avoid the memory copy and let the compiler unroll the loop by using a fixed number of iterations:
char* int_to_bin(unsigned n) {
unsigned size = sizeof(n) * CHAR_BIT;
char* str = malloc(size + 1);
str[size] = 0;
while(size--) {
str[size] = '0' + (n & 1);
n >>= 1;
}
return str;
}

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