question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
As the title said I was interested in the best way to convert a binary string to a hexadecimal string in C. The binary string is 4 bits at most so converting into a single hexadecimal char would be best.
Thanks for any help, I'm not sure if there's something built in to make this easier so don't have my own attempt to post yet.
|
You can usestrtolto convert the binary string to an integer, and thensprintfto convert the integer to a hex string:
```
char* binaryString = "1101";
// convert binary string to integer
int value = (int)strtol(binaryString, NULL, 2);
// convert integer to hex string
char hexString[12]; // long enough for any 32-bit value, 4-byte aligned
sprintf(hexString, "%x", value);
// output hex string
printf(hexString);
```
Output:
```
d
```
If it's guaranteed to be a single hexadecimal character just takehexString[0].
|
I've to check one byte in 200 tables.
I don't want to write 200 line to check it.
Do you have any tips to do it with a for loop?
My example of code :
```
#include <stdio.h>
#include "CUnit/Basic.h"
#include "CUnit/Console.h"
#include "CUnit/Automated.h"
#include "CUnit/CUCurses.h"
#include "CUnit/TestDB.h"
void _testu(){
CU_ASSERT_EQUAL(55, my_tab_0[5]);
CU_ASSERT_EQUAL(55, my_tab_1[5]);
CU_ASSERT_EQUAL(55, my_tab_2[5]);
CU_ASSERT_EQUAL(55, my_tab_3[5]);
.
.
.
CU_ASSERT_EQUAL(55, my_tab_n[5]);
}
```
|
If you have n independant arrays, you could try to build an array of pointers:
```
char *my_tab[] = { my_tab_0, my_tab_1, m__tab_2, ... my_tab_n };
```
you can they simply do:
```
void _testu(){
int i;
for(i=0; i<=n; i++) {
CU_ASSERT_EQUAL(55, my_tab[i][5]);
}
}
```
It mainly make sense if you have more than one loop using it.
|
I want to know how a node* variable NODE can be assigned to the data inside the structure?
```
struct node
{
int info;
struct node *link;
};
typedef struct node* NODE;
//IN SOME OTHER FUNCTION
NODE temp,first;
temp = first;
first = first->link; // I WANT HELP WITH THIS LINE.
```
|
In a linked list you have a node with some information. In every node you have the address of the next node.
```
struct node
{
int info; //Information or data which is stored at every node
struct node *link; // Address of next node
};
```
first = first->link; // I WANT HELP WITH THIS LINE.
If you're done with current node then you may require to access the next node.
In this line you have accessed the next node (first->link) of the linked list
and you are making your next node asfirst(top node).
|
Is it possible to display progress on one line instead of having the for-loop printing out a bunch of lines for every action?
Like, for example. Instead of this:
```
Progress: 0%
Progress: 15%
Progress: 50%
Progress: 100%
```
It does all that in one line (while showing progress, of course):
```
Progress: 100%
```
Basically, I'm making a sockets program to transfer files from one socket to another socket. And it's taking the amount transferred divided by the file size multiplied by 100 to get its percentage.
|
Use
```
printf ("\r progress =%d", progress)
```
|
I encountered this in a C program:
```
char str[100];
scanf(" %[^\n]", str);
```
Please explain how it works and why?
|
Thisscanfformat string consists of two parts:
a space character, which skips space characters (' ','\t','\n', etcetera) in the input, andthe%[^\n]conversion specification, which matches a string of all characters not equal to thenew linecharacter ('\n') and stores it (plus a terminating'\0'character) instr.
Note however that if the input (after the leading spaces, and before the first newline character) is longer than 99 characters, this function exhibits undefined behaviour, becausestrcan only hold 100chars including the terminating'\0'character. A safer alternative is:
```
scanf(" %99[^\n]", str);
```
|
I want to know how a node* variable NODE can be assigned to the data inside the structure?
```
struct node
{
int info;
struct node *link;
};
typedef struct node* NODE;
//IN SOME OTHER FUNCTION
NODE temp,first;
temp = first;
first = first->link; // I WANT HELP WITH THIS LINE.
```
|
In a linked list you have a node with some information. In every node you have the address of the next node.
```
struct node
{
int info; //Information or data which is stored at every node
struct node *link; // Address of next node
};
```
first = first->link; // I WANT HELP WITH THIS LINE.
If you're done with current node then you may require to access the next node.
In this line you have accessed the next node (first->link) of the linked list
and you are making your next node asfirst(top node).
|
Is it possible to display progress on one line instead of having the for-loop printing out a bunch of lines for every action?
Like, for example. Instead of this:
```
Progress: 0%
Progress: 15%
Progress: 50%
Progress: 100%
```
It does all that in one line (while showing progress, of course):
```
Progress: 100%
```
Basically, I'm making a sockets program to transfer files from one socket to another socket. And it's taking the amount transferred divided by the file size multiplied by 100 to get its percentage.
|
Use
```
printf ("\r progress =%d", progress)
```
|
I encountered this in a C program:
```
char str[100];
scanf(" %[^\n]", str);
```
Please explain how it works and why?
|
Thisscanfformat string consists of two parts:
a space character, which skips space characters (' ','\t','\n', etcetera) in the input, andthe%[^\n]conversion specification, which matches a string of all characters not equal to thenew linecharacter ('\n') and stores it (plus a terminating'\0'character) instr.
Note however that if the input (after the leading spaces, and before the first newline character) is longer than 99 characters, this function exhibits undefined behaviour, becausestrcan only hold 100chars including the terminating'\0'character. A safer alternative is:
```
scanf(" %99[^\n]", str);
```
|
My program asks the user to input an integer and adds the sum of the digits.
```
#include <stdio.h>
int main (void)
{
int inputNum, sum;
// Gets the inputNum
printf("Type in a positive integer, and this program\nwill calculate the sums of the digits: ");
scanf("%i", &inputNum);
do
{
sum += (inputNum % 10);
inputNum /= 10;
} while (inputNum != 0);
printf("Your sum is: %i\n", sum);
}
```
But every time it put an integer in, I get a number around 36000. I saw another example online that used %d, so I tried it but it made no difference. Am I just going in the wrong direction from the start? Thanks in advance.
|
You never initializedsum; it may well be starting with value 1,000,000
Just do:
```
int inputNum, sum = 0;
```
|
I've got a program to catch any terminating signals. Currently all it does is catchCtrl + C. I want to be able to catchCtrl + ZandCtrl + \in addition toCtrl + C. Here's part of my code.
```
if (signal(SIGINT, SIG_IGN) == SIG_ERR)
fprintf(stderr,"Error: Can't catch SIGINT\n");
if (signal(SIGTERM, SIG_IGN) == SIG_ERR)
fprintf(stderr,"Error: Can't catch SIGTERM\n");
// do stuff
```
What other signals to I need to implement to catchCtrl + ZandCtrl + \? And what raisesSIGTERM? Thanks in advance.
|
Ctrl+Zraises SIGTSTP.Ctrl+\raises SIGQUIT.
I don't know of any key combination that raises SIGTERM, but of course you can send it usingkill -TERM <pid>replacing<pid>with the process ID. (Or justkill <pid>; SIGTERM is the default signal forkill)
Note that you can't catch SIGSTOP nor SIGKILL.
|
I want to use interrupt handlers
```
void EXTI3_IRQHandler(void)
{
//body
}
```
but when I build the project, I get the following error:
SymbolEXTI3_IRQHandlermultiply defined (by stm32f10x_it.o and
main.o)
I have included library stm32f10x_exti.h
|
Handlervoid EXTI3_IRQHandler(void)already defined in filestm32f10x_it.c.
You can replace code of your handler frommain.cto this special file or comment blank handler instm32f10x_it.c.
|
```
#include<stdio.h>
#include<conio.h>
void main()
{
int *p=NULL;
*p=30;
printf("%d %p", *p,p); //output:- 30 0000
}
```
p should be pointing to address 0 and I think there should be null assignment error. But how *p is giving output as 30? Is 30 stored in location 0000? According to me 0th address should not be assigned to any variable.
|
[..] I think there should be null assignment error.
C staandard doesn't provide any such guarantees.
Dereferencing a null pointer isundefined behaviour. So, there's no point in reasoning about why it prints 30.
Btw, you should cast the pointer argument tovoid*to print it:
```
printf("%d %p", *p, (void*)p);
```
|
I have a C program and a bash script that need exclusive access to a file. I've seen thatyou can use mkdir with bash, but does this mix well with C? Is it safe to just test the presence of a directory, create and then delete it?
What I'm actually doing: a C program keeps rewriting a file with new data that is then read from a bash script.
|
The whole point of semaphores is atomicity, and if you check for directory presence using your own code, you will lose that property. What you should do it usemkdirfunction and check forEEXISTerror code once it returns:
```
char * lockdir="/tmp/myscript.lock";
int retval=mkdir(lockdir, S_IRWXU);
if(retval == 0) printf("successfully acquired lock: %s", lockdir);
else if(errno == EEXIST) printf("cannot acquire lock %s", lockdir);
else printf("Something bad happened (permissions/no free space/read-only filesystem)")
```
|
I have this piece of C code
```
#include <stdio.h>
int main(){
int i , j , m , A[5]={0,1,15,25,20};
i = ++A[1];
printf("%d:\n",i);
j = A[1]++;
printf("%d:\n",j);
m = A[i++];
printf("%d:\n",m);
printf("%d %d %d",i,j,m);
return 0;
}
```
and It's output is
```
2:
2:
15:
3 2 15
```
Shouldn't the printf print the values as 2 , 2, 15 but why is it printing 3 , 2, 15
P.S : I really didn't abuse this code , someone else did (my professor perhaps) and I'm just learning C .
|
The line
```
m = A[i++];
```
will increment the variable i in-place after it gets the cooresponding value from the array A.
|
I have the following code:
```
#include <stdio.h>
float a; //Initialize variables
char b;
int c;
char d;
int main(void)
{
printf("Enter float: ");
scanf("%4.2f", &a);
printf("%4.2f", a);
//printf("Enter character:\n");
//printf("Enter 4-digit integer: \n");
//printf("Enter character:\n");
return 0;
}
```
However I get the following errors when compiling:
1.)scanf:unknown field type character '.' in format specifier2.)scanf: too many arguments passed for format string
Can anyone explain what the issue in my code is?
Thank you!
|
scanf("%f",&a)does not take format specifier.
As mentioned in comments Visual Studio treat this warning as error.
So either use
```
scanf_s("%f",&a);
```
or go into settings and disable this warning as mentioned in this postWhy does Visual Studio 2013 error on C4996?
|
What would this translate to (in a more verbose way)?
```
local.sin_addr.s_addr = (!ip_address) ? INADDR_ANY:inet_addr(ip_address);
```
Trying to understand Ternary operators and I can't quite get it.
|
A ternary is similar to anifstatement, but it can be used where an expression is required. So it's equivalent to:
```
if (!ip_address) {
local.sin_addr.s_addr = INADDR_ANY;
} else {
local.sin_addr.s_addr = inet_addr(ip_address);
}
```
|
I want to get char array size but I cant do that
let see
```
#define MAX 64
char value[MAX]
value = "hi" //or something initialization
sizeof("hi") //result = 3
sizeof(value) // result = 64
```
I want to getsizeof("hi") == sizeof(value)How cant I do?
|
In the snippet that you've included, you're actually setting the size ofvalueto 64. As a resultsizeof(value)will return 64 *sizeof(char).
This is correct, regardless of what you're putting into the arrayvalue.
Perhaps what you're trying to do is to get the array to be automatically sized at compile time? e.g.
```
char value[] = "hi";
int value_size = sizeof(value); // value_size will now equal 3, as the array contains { 'h', 'i', '\0' }
```
|
I looked at thisSO postwith no help.
```
int main()
{
int a[][] = {{1,2},{3,4}};
}
```
Error
```
$ gcc a.c
a.c:6:8: error: array has incomplete element type 'int []'
int a[][] = {{1,2},{3,4}};
^
1 error generated.
```
Why isa[][]incomplete type?
Why isint a[][2]fine?
I would've assumed that since compiler can initialize this 2-D array it can also figure out bounds automatically? I know that I'm required to provide size but why? Is it language requirement?
|
Only one index can autosize. Otherwise you could have any pair of factors in the size. Soa[][2]works, buta[][]does not, because it can't guess the size of the array of arrays.
|
I have 2 structs of the same size, layout and alignment, but of different types. I would like to copy one onto the other.
```
struct one s1;
struct two s2;
...
s1 = (struct one)s2; // error: conversion to non-scalar type requested
s1 = *((struct one*)&s2); // fine?
```
Is the 2nd method safe & portable?
Bonus: What was the thinking of the language designers here, are they making sure I take off the safety before I shoot myself in the foot?
|
The second method is undefined behaviour due to violating the strict aliasing rule. Even thoughstruct oneandstruct twohave the same layout, it is not permitted to use an lvalue of typestruct oneto access an object of typestruct twoor vice versa.
In general, accessing an object via an expression of a different type is only allowed for using a character type to access another object; or via a union.
An alternative would be:
```
memcpy(&s1, &s2, sizeof s1);
```
|
I am working with multi processes and signals and I just found out yesterday that printf is not a re-entrant function so there is a risk by using it with signal handlers. Is there anything I can do about it? Is there any re-entrant variation of printf or any re-entrant syscall that could replace printf?
Thanks!
|
Signal handlers are highly tricky in general. So highly tricky, that usually the only safe operation to do within them is to set a flag "signal was received" and then let the main loop (or in a multi threaded application a special signal handling thread) of the program do the actual signal handling.
|
I want to assign a value to mychar *like that:
```
char *text;
struct node *ptr = head;
//start from the beginning
while(ptr != NULL)
{
text = ptr->key + ";" + ptr->data + ";\n";
ptr = ptr->next;
fprinft(f, text);
}
```
The key value is achar[]and the data value anint.
I get the following error:
Error: invalid operands to binary + (have ‘int’ and ‘char *’) text = ptr->key + ";" + ptr->data + ";\n";
Does anyone know how to fix that problem?
|
As the concatenation ofptr->key,";",ptr->data,";\n"does not need to exist after the loop, just print it to the file.@user3386109
```
// Not needed
// char *text;
struct node *ptr = head;
while(ptr != NULL) {
// v--v----- printf specifiers for a pointer to a string and int
fprinft(f, "%s;%d;\n", ptr->key, ptr->data);
ptr = ptr->next;
}
```
|
I'm trying to count the syscalls in my Go program on OS X Yosemite. I've tried usingdtrussanddtrace, but both cause my program to crash with the following error, followed by a stack trace:
```
fatal error: runtime: bsdthread_register error
```
The two commands I've used are:
sudo dtruss "./my_program my_arg"sudo dtrace -c "powerset 2" -n 'syscall:::entry { @num[probefunc] = count(); }'
Things I've Tried
The main takeaway from my Google-foo has been to unsetDYLD_INSERT_LIBRARIES, which I have done numerous times to no avail.
./my_programis a binary that I created withgo install. I've written an equivalent C program and both of the above commands work fine with that.
|
If you want to use dtrace on macOS, you will need to use the external linker to build your program
```
-ldflags -linkmode=external
```
|
I want to do an evented read on Serial port which will run only when the data is available.
I have triedsigactionbut it causes problem when making a highly threaded application, alsosleepfunction seem to work incorrectly according to many forums.
So I am looking for a similar way as in windowsWaitCommEventthat is used in MSDN.
|
The canonical equivalents for linux systems is to usepoll()orselect().
Workings are different of course.
|
What does the 'Rebuild all' button or the 'Build' in IDE's like DEV C++ do actually?I never needed it but I've seen people using it.This is different from 'compile'(compiling is building in code blocks but not in DEV c++).
|
The first time you compile, you need to compile every C file. On subsequent compiles, you only need to compile the C files that have changed.
The project can keep track of what had been modified and what needs to be recompiled and what doesn't.
So Build can be faster, as it won't recompile everything, only the source files that have changed since last build.
Re-build all forces everything to be recompiled, which might be necessary if some sort of change is made that the project can't identify for some reason, like a change to a file made externally to the IDE.
|
Is it possible to define a macroINPUT_ARR, so thatint a[4]; void (INPUT_ARR(int, a, 4)){}equals tovoid (int a0, int a1, int a2, int a3){}
|
Here's one way:
```
#define INPUT_ARR(type, name, count) IARR ## count (type, name)
#define IARR0(type, name)
#define IARR1(type, name) type name##0
#define IARR2(type, name) IARR1(type, name), type name##1
#define IARR3(type, name) IARR2(type, name), type name##2
#define IARR4(type, name) IARR3(type, name), type name##3
void func (INPUT_ARR(int, a, 4)){}
int main()
{
func(1,2,3,4);
}
```
Results ofgcc -E(excludingmain):
```
void func (int a0, int a1, int a2, int a3){}
```
You'll need to add IARR lines up until the max count that you want to support. It's not possible to have recursive macro definitions that go on automatically.
|
I have 2 structs of the same size, layout and alignment, but of different types. I would like to copy one onto the other.
```
struct one s1;
struct two s2;
...
s1 = (struct one)s2; // error: conversion to non-scalar type requested
s1 = *((struct one*)&s2); // fine?
```
Is the 2nd method safe & portable?
Bonus: What was the thinking of the language designers here, are they making sure I take off the safety before I shoot myself in the foot?
|
The second method is undefined behaviour due to violating the strict aliasing rule. Even thoughstruct oneandstruct twohave the same layout, it is not permitted to use an lvalue of typestruct oneto access an object of typestruct twoor vice versa.
In general, accessing an object via an expression of a different type is only allowed for using a character type to access another object; or via a union.
An alternative would be:
```
memcpy(&s1, &s2, sizeof s1);
```
|
I am working with multi processes and signals and I just found out yesterday that printf is not a re-entrant function so there is a risk by using it with signal handlers. Is there anything I can do about it? Is there any re-entrant variation of printf or any re-entrant syscall that could replace printf?
Thanks!
|
Signal handlers are highly tricky in general. So highly tricky, that usually the only safe operation to do within them is to set a flag "signal was received" and then let the main loop (or in a multi threaded application a special signal handling thread) of the program do the actual signal handling.
|
I want to assign a value to mychar *like that:
```
char *text;
struct node *ptr = head;
//start from the beginning
while(ptr != NULL)
{
text = ptr->key + ";" + ptr->data + ";\n";
ptr = ptr->next;
fprinft(f, text);
}
```
The key value is achar[]and the data value anint.
I get the following error:
Error: invalid operands to binary + (have ‘int’ and ‘char *’) text = ptr->key + ";" + ptr->data + ";\n";
Does anyone know how to fix that problem?
|
As the concatenation ofptr->key,";",ptr->data,";\n"does not need to exist after the loop, just print it to the file.@user3386109
```
// Not needed
// char *text;
struct node *ptr = head;
while(ptr != NULL) {
// v--v----- printf specifiers for a pointer to a string and int
fprinft(f, "%s;%d;\n", ptr->key, ptr->data);
ptr = ptr->next;
}
```
|
I'm trying to count the syscalls in my Go program on OS X Yosemite. I've tried usingdtrussanddtrace, but both cause my program to crash with the following error, followed by a stack trace:
```
fatal error: runtime: bsdthread_register error
```
The two commands I've used are:
sudo dtruss "./my_program my_arg"sudo dtrace -c "powerset 2" -n 'syscall:::entry { @num[probefunc] = count(); }'
Things I've Tried
The main takeaway from my Google-foo has been to unsetDYLD_INSERT_LIBRARIES, which I have done numerous times to no avail.
./my_programis a binary that I created withgo install. I've written an equivalent C program and both of the above commands work fine with that.
|
If you want to use dtrace on macOS, you will need to use the external linker to build your program
```
-ldflags -linkmode=external
```
|
I want to do an evented read on Serial port which will run only when the data is available.
I have triedsigactionbut it causes problem when making a highly threaded application, alsosleepfunction seem to work incorrectly according to many forums.
So I am looking for a similar way as in windowsWaitCommEventthat is used in MSDN.
|
The canonical equivalents for linux systems is to usepoll()orselect().
Workings are different of course.
|
There are a ton of posts explaining why explicitly doingfoo(void)is better thanfoo()because it specifies that there are no function arguments instead of an unknown amount.
However, I cannot seem to find if it's best practice to put void in both the header file declarationandthe source file definition such as:
foo.h
```
void foo(void);
```
foo.c
```
void foo(void)
{
return;
}
```
OR
foo.h
```
void foo(void);
```
foo.c
```
void foo()
{
return;
}
```
Which one is better practice, and is there a specific reason to do one over the other?
|
Old-style function declarations and definitions with empty parentheses are an obsolescent feature (N15706.11.6, 6.11.7). There are hardly any good reasons to use them.
Use(void)consistently, not().
|
Strings(character arrays) can be modified in C but string literals can't be modified. But why do string functions like strlen(const char *str) have a pointer to a constant characters?
|
Because they do not modify (and do not need to modify) their argument strings. That's what thatconstmeans.
Ifstrlen's argument were declared aschar *(noconst), you wouldn't be able to usestrlento determine the length of a constant string. For example
```
size_t my_own_strlen(char *str) { /* whatever */ }
const char hello[] = "Hello";
size_t l1 = my_own_strlen(hello); // Error: cannot convert `const char *` to `char *`
size_t l2 = strlen(hello); // OK
```
Declaring that argument asconst char *makesstrlenapplicable to both constant and non-constant strings.
|
```
hashset *newset= new_hashset;
char *info="1234";
put_hashset (newset,info);
```
I took the help fromhere. I have inserted values in the hashset but I am not being able to print the values.
|
it's a standard hashtable structure. A size, plus an array of linked lists. So you ned to iterate over the array, then over the lists (mosts of the lists will be short and some will be empty). The data is in no particular order.
```
void getdata(hashset *hash)
{
int i;
hashnode *ptr;
for(i=0;i<hash->size;i++)
{
if(hash->chains[i])
{
for(ptr = hash->chains[i]; ptr; ptr = ptr->link)
{
printf("key : %s\n", ptr->word);
}
}
}
}
```
|
That's my code -
```
main()
{
double x;
double y = pow(((1/3 + sin(x/2))(pow(x, 3) + 3)), 1/3);
printf("%f", y);
return 0;
}
```
I get an error indouble y = pow((1/3 + sin(x/2))(pow(x, 3) + 3), 1/3);, it says that called object is not a function or function pointer. I don't get it though -(1/3 + sin(x/2))(pow(x, 3) + 3)is the first element ofpow(x, y);that is the x I want to raise to y (1/3) power. Where lies the problem? I'm pretty new to c basic but I can't find the answer anywhere.
|
If you want to multiply, you need to use the*operator. You can't put parenthesized expressions adjacent to each other to denote multiplication.
```
(1/3 + sin(x/2))*(pow(x, 3) + 3)
```
|
In the below code,
```
#include<stdio.h>
int main(){
char string[] = {1, 2, 3};
char* my_pointer = string;
printf("%c", *my_pointer);
}
```
Am expecting the ASCII character'1'to be displayed on screen.
ASCII character'1'is49with binary representation as00110001
|
You need to give it characters when initializing:
```
char string[] = {'1', '2', '3', '\0'};
```
or you can initialize using a string
```
char string[] = "123";
```
When you use numbers like
```
char string[] = {1, 2, 3};
```
it will print the ASCII character corresponding to the number 1 (which is most likely not generating any output).
If you want to initialize using numbers, you must do:
```
char string[] = {49, 50, 51};
```
|
I wrote the following c program:
```
int main()
{
char a[1];
char b[6]="hello\0";
int c, i;
for(i = 0; (c = getchar()) != EOF; i++)
a[i] = c;
for(i = 0; i < 5; i++)
printf("%c", b[i]);
}
```
Why when I give "bye" in input the program print "helby"?
I thought 'b' should be saved in a[0], 'y' in b[0] and 'e' in b[1].
Thank you in advice!
|
You assume thatais immediately followed bybin memory. That is not necessarily the case.
Reading/writing past the end of an array isundefined behavior, so compilers are free to arrange local variables in any order they choose.
On my particular machine, ifbis declared beforea, thenaappears just beforebin memory and I get the output you expect. However, as you can see from the other answers and comments that behavior is not reliable because of undefined behavior.
|
i try this code to get duration of a media file:
```
AVFormatContext* pFormatCtx = NULL;
avformat_open_input(&pFormatCtx, filename.c_str(), NULL, NULL);
if (pFormatCtx != 0) {
avformat_find_stream_info(pFormatCtx, NULL);
int64_t media_duration = pFormatCtx->duration;
duration = media_duration/AV_TIME_BASE;
avformat_close_input(&pFormatCtx);
avformat_free_context(pFormatCtx);
}
```
The problem is if i call avformat_free_context() the app die, if i comment out the line the program works, but i prefer to avoid memory leak.
PS: i call av_register_all() when the program start.
|
Becauseavformat_close_inputwill free theAVFormatContextafter it close it. That is why you should sendpFormatCtxby pointer.
So you don't need to callavformat_free_contextas it is already called byavformat_close_inputand no need to worry about memory leaks.
See the documentation foravformat_close_inputfor reference.
|
If "Allow windows manager to decorate window" is on.
What is the function name in the wine source that knows a user click this X button and send the WM_CLOSE to the app?
Thank you
|
The window manager sends ClientMessage with type WM_PROTOCOLS and the protocol value WM_DELETE_WINDOW. This is handled in dlls/winex11.drv/event.c: X11DRV_ClientMessage() -> handle_wm_protocols().
|
What's the difference between the following two character arrays: one with a null character and one without a null character?
```
char name1[] = {'j','o','h','n'};
char name2[] = {'j','o','h','n','\0'};
```
If there is a difference betweenname1andname2how doesstrlenwork onname1since it has no null character?
What would the result be for
```
printf("%d", name1[5] == '\0');
```
I expected it to be 0 but got 1
|
how does strlen work on name1 since it has no null character.
It doesn't. This would invoke undefined behaviour.
I expected it to be 0 but got 1
Your code snippet tries to accessname1[5]. Given thatnameis achararray of size 4, you are accessing memory that has nothing to do with that array. Possibly at the time of execution that memory happened to contain a null character, leading to this result. This cannot be predicted however, and so the behaviour isundefined.
|
What's the difference between the following two character arrays: one with a null character and one without a null character?
```
char name1[] = {'j','o','h','n'};
char name2[] = {'j','o','h','n','\0'};
```
If there is a difference betweenname1andname2how doesstrlenwork onname1since it has no null character?
What would the result be for
```
printf("%d", name1[5] == '\0');
```
I expected it to be 0 but got 1
|
how does strlen work on name1 since it has no null character.
It doesn't. This would invoke undefined behaviour.
I expected it to be 0 but got 1
Your code snippet tries to accessname1[5]. Given thatnameis achararray of size 4, you are accessing memory that has nothing to do with that array. Possibly at the time of execution that memory happened to contain a null character, leading to this result. This cannot be predicted however, and so the behaviour isundefined.
|
While running a sample code from the internet, I am stuck at 'glutTimerfunc'. I cannot figure out what is this error.
|
glutTimerFunctakes a pointer to a function that must have a signature of
```
void (*func)(int value)
```
YourframeTimerCallbackfunction doesn't take an integer parameter. Hence the error.
Refer tohttps://www.opengl.org/resources/libraries/glut/spec3/node64.html
|
I have:
```
char M[20] = "abcdabcdabcdabcd";
```
I can either print it as a string or as characters:
```
printf("%s\n", M); //print as string
for(i = 0;str[i] != '\0';i++) //print as characters
{
printf("%c",str[i]);
}
```
I want to read a string of 7 characters and store it in M such that afterwards when I print it as a string and as characters I get (assuming the 7 characters entered are: ABCDEFG):
```
ABCDEFG //output of printf("%s\n", M); when printed as string
ABCDEFG abcdabcd //output of the for loop above
```
My answer is:
```
for(K = 0;K<7;K++)
{
scanf(" %1c", &M[K]);
}
```
but the above doesn't work as it should.
EDIT:
it outputs
```
ABCDEFGdabcdabcd
```
for both cases.
|
You should add a statement:M[7] = '\0'. The last character for the string should be '\0'.
|
need to make a c program that will get the current time of pc and display if its traffic or not.
Traffic every : 7:00am - 10:00am && 17pm - 19pm
need help in time comparisons. im using if else.
if ((mytime > 7 && mytime < 10) && (mytime > 17 && mytime < 19))
|
Use||(OR) instead of&&(AND). Or it will never work.
And to get the hour, do something like that:
```
#include <stdio.h>
#include <time.h>
int main() {
time_t now = time(NULL);
struct tm *now_tm = localtime(&now);
int hour = now_tm->tm_hour;
if ((hour > 7 && hour < 10) || (hour > 17 && hour < 19))
printf("traffic\n");
else
printf("smooth\n");
return 0;
}
```
|
I have the following lines:
```
char *name = malloc(strsize + 1);
```
and
```
uint8_t *data;
data = (uint8_t *)name;
```
It is correct? It doesn't exist a chance that the pointer *name will be interpreted bad when that conversion is done?
|
That shouldn't be much of a problem, except that thesignednessof the memory would be interpreted differently between access alongdataandname. In most of the practical platforms, the size ofcharanduint8_tin bits is the same.
|
I can't seem to find any good documentation for the DWARF DI format to answer my question. I'm writing a language that compiles to C, is there any way that I can produce DWARF Debug Information into the C code or is it assembly only?
Is itimpossibleto add debug information to some (generated) C code other than using primitive stuff that isn't as good like#lineand the#filedirectives?
|
It can be done for some things, if you assume your compiler can emit assembly. For an example of this, seemy favorite gdb test case.
Normally this isn't done, though. It can be quite hard to get right. Nowadays it's better to either write your compiler to be a direct front-end to GCC or LLVM; or to write gdb or lldb helper scripts to make debugging the generated C code simpler.
|
I want to write a C program that takes as input an integer, and outputs its square. Here is what I have tried.
However,
./a.out < 3outputs 32768, and./a.out < 4also outputs 32768.
Where am I wrong? Thanks.
```
#include <stdio.h>
int main(){
int myInt;
scanf("%d", &myInt);
printf("%d\n",myInt*myInt);
}
```
|
It looks like what you're trying to do is
```
echo 4 | ./a.out
```
the syntax for < is
```
program < input_file
```
whereas | is
```
command_with_output | program
```
|
I am working on my first C program for school. For some reason I am getting the following error when I try to compile it
```
#include <stdio.h>
int multiplication()
{
int i, j, k;
for ( i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
for (k = 0; k < 10; k++) {
if (x[k] == 0)
return 0;
a[i] = a[i] + b[j] / x[k];
}
}
}
return 1;
}
```
|
you have to declarea,bandxor receive them as arguments to your function before you can use them
|
I want to receive a file through a TCP socket on Linux. But I just get a empty file. However when I delete line 1 (while), anything will go okay. My code on server looks like this:
```
while(1)
{
FILE *fp = fopen(file_name, "w");
if(NULL == fp)
{
printf("File:\t%s Can Not Open To Write\n", file_name);
exit(1);
}
bzero(buffer, BUFFER_SIZE);
int length = 0;
while((length = recv(new_server_socket_fd, buffer, BUFFER_SIZE, 0)) > 0)
{
if(fwrite(buffer, sizeof(char), length, fp) < length)
{
printf("File:\t%s Write Failed\n", file_name);
break;
}
bzero(buffer, BUFFER_SIZE);
}
```
One thing I can make sure is that "if(fwrite(...))" do execude cause I put a putchar('a') out of if() and I can get some "a" on my screen. All data will be transfered through socket new_server_socket_fd
|
fclosethe file before you return.
|
I have the following lines:
```
char *name = malloc(strsize + 1);
```
and
```
uint8_t *data;
data = (uint8_t *)name;
```
It is correct? It doesn't exist a chance that the pointer *name will be interpreted bad when that conversion is done?
|
That shouldn't be much of a problem, except that thesignednessof the memory would be interpreted differently between access alongdataandname. In most of the practical platforms, the size ofcharanduint8_tin bits is the same.
|
I can't seem to find any good documentation for the DWARF DI format to answer my question. I'm writing a language that compiles to C, is there any way that I can produce DWARF Debug Information into the C code or is it assembly only?
Is itimpossibleto add debug information to some (generated) C code other than using primitive stuff that isn't as good like#lineand the#filedirectives?
|
It can be done for some things, if you assume your compiler can emit assembly. For an example of this, seemy favorite gdb test case.
Normally this isn't done, though. It can be quite hard to get right. Nowadays it's better to either write your compiler to be a direct front-end to GCC or LLVM; or to write gdb or lldb helper scripts to make debugging the generated C code simpler.
|
I have a function like
```
int myfun(int *a, int *b)
{
while(some condition)
{
if(condition) return *a + *b;
else
{
some manipulation;
}
}
return -1;
}
```
When first return statement in while->if part is encountered,does the control go to the function calling myfun or while loop still continues?Why is the return -1 statement needed?
|
After thereturn *a+*bthe function returns that and ends. You need thereturn -1because if that condition is never met, what will it return? It is aintfunction so it has to return something.
|
I'm trying to print the following pattern:
```
@@@@@@@@
@@@@@@@
@@@@@@
@@@@@
```
However, I am getting this instead:
```
@ABCDEFG
ABCDEFG
BCDEFG
CDEFG
```
I'm not sure what I am doing wrong. I would appreciate any feedback or direction.
```
#include <stdio.h>
#define ROWS 4
#define CHARS 8
int main(void)
{
for(int row = 0; row < ROWS; row++)
{
for(char ch = ('@' + row); ch < ('@' + CHARS); ch++)
printf("%c", ch);
printf("\n");
}
return 0;
}
```
|
The+operator doesn't work the way you think it does.@is converted to it's ASCII value (64) then you addrow. Whenrowis2, you are saying: print the character that coresponds the number (64 + 2) which isA.
Here's an ASCII Table
I would change the inside loop to something like this:
```
for(int ch = row; ch < CHARS; ch++) {
printf("%c", '@');
}
printf("\n");
```
|
I'm looking at string manipulation in C and I don't understand why the statements1[i] = s1[++i];won't replace the firstHby the next charactere. Take a look at the code :
```
#include <stdio.h>
main()
{
char s1[] = "Hello world !";
for(int i = 0; s1[i] != '\0'; ++i)
s1[i] = s1[++i];
printf("%s", s1);
}
```
It printsHello world !instead ofel r
|
Your program hasundefined behaviourbecause in this statement
```
s1[i] = s1[++i];
```
iis modified twice between sequence points (The assignment operator=doesn't introduce a sequence point).
gcc (gcc -Wall -Wextra) warns with:
```
warning: operation on ‘i’ may be undefined [-Wsequence-point]
```
similarly clang warns:
```
warning: unsequenced modification and access to 'i' [-Wunsequenced]
```
|
I would like to assign hex values into char type. Due to null (\x00) character, I cannot assign all hex values. Just 4 character can be assigned. How to assign all hex values in(char*)data??
```
unsigned char data[100];
sprintf((char*)data,"\x30\x29\x02\x01\x00\x04\x06\x70\x75\x62\x6c\x69\x63\xa0");
```
|
Since you have all your hex numbers available at compile time, you can assign them using curly brace initializer instead of a string literal:
```
unsigned char data[] = {
0x30, 0x29 ,0x02, 0x01, 0x00, 0x04, 0x06,
0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0xa0
};
```
|
So I wish to make it so you cannot enter a number such as 0 or 11. I am usingnetbeans 8.1 (GNU cygwin). I have found that the while loop is not being used, and that the terminal runs a successful build regardless of the loop made to ensure out of bound numbers are not existent.
```
int main(int argc, char** argv) {
int x;
int guess = 0;
srand(time(NULL));
x = rand() % (10) + 1;
printf("random number is %d. \n", x);
printf("whats your guess? 3 tries. between 1 and 10 \n");
scanf("%d", guess);
while (guess >10 || guess < 0){
printf(" your guess is out of the bounds (1 to 10) re enter: \n");
scanf("%d", guess);
}
return (EXIT_SUCCESS);
```
}
Any ideas?
I intend to make several comparisons to 'x' later.
|
Simply needs a & (ampersand) in the scan f statement.
```
scanf("%d", &guess);
```
|
This question already has answers here:Segmentation fault when trying to modify a string [duplicate](4 answers)Closed6 years ago.
Why this code won't work, on online compiler return segment fault, on my linux VPS memory leak...
```
#include <ctype.h>
#include <stdio.h>
#include <string.h>
char *a_foo(char *str) {
unsigned char *p = (unsigned char *)str;
while (*p) {
*p = 'a';
p++;
}
return str;
}
int main() {
char * test = "TestTest";
a_foo(test);
printf("result: %s\n", test);
}
```
Online Compiler:LINK
|
The string literal"TestTest"is probably stored in read-only memory in your environment, so the code ina_foothat attempts to write to it would fail.
The type of a string literal has theconstqualifier and the compiler should warn you if you try to assign it to a non-const pointer variable.
|
Just a curiosity,
Consider that I have
./first./second
that they are executable c program
first.c:
```
char main(void){
return '5';
}
```
second.c:
```
#include<stdio.h>
int main(int argc, char** argv){
printf("%s", argv[2]);
return 0;
}
```
(I want to print 5 here)
Is it possible to compile second.c like:
```
gcc second.c -./first
```
Of course I know that wont work but is it possible to write something that will work like what I want?
|
The return value ofmain()becomes the program's exit status, which is put in the shell's$?variable. So it should be:
```
./first
./second $?
```
You should changefirst.cto return anint, notchar; otherwise it will print the ASCII code for the'5'character, not5.
```
int main(void){
return 5;
}
```
And insecond.c, it should beargc[1], notargv[2].
|
I would like to assign hex values into char type. Due to null (\x00) character, I cannot assign all hex values. Just 4 character can be assigned. How to assign all hex values in(char*)data??
```
unsigned char data[100];
sprintf((char*)data,"\x30\x29\x02\x01\x00\x04\x06\x70\x75\x62\x6c\x69\x63\xa0");
```
|
Since you have all your hex numbers available at compile time, you can assign them using curly brace initializer instead of a string literal:
```
unsigned char data[] = {
0x30, 0x29 ,0x02, 0x01, 0x00, 0x04, 0x06,
0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0xa0
};
```
|
So I wish to make it so you cannot enter a number such as 0 or 11. I am usingnetbeans 8.1 (GNU cygwin). I have found that the while loop is not being used, and that the terminal runs a successful build regardless of the loop made to ensure out of bound numbers are not existent.
```
int main(int argc, char** argv) {
int x;
int guess = 0;
srand(time(NULL));
x = rand() % (10) + 1;
printf("random number is %d. \n", x);
printf("whats your guess? 3 tries. between 1 and 10 \n");
scanf("%d", guess);
while (guess >10 || guess < 0){
printf(" your guess is out of the bounds (1 to 10) re enter: \n");
scanf("%d", guess);
}
return (EXIT_SUCCESS);
```
}
Any ideas?
I intend to make several comparisons to 'x' later.
|
Simply needs a & (ampersand) in the scan f statement.
```
scanf("%d", &guess);
```
|
(There was a similar question but the answer given doesn't work)
There is no warning. But after entering values, segmentation fault appears.
```
#include <stdio.h>
typedef struct
{
int a;
char b;
}PO;
PO *P[1000];
int main()
{
scanf("%d%c",&(P[0]->a),&(P[0]->b));
}
```
|
PO *P[1000];
defines an array of 1000pointerstoPOstructures.
Written like that it would probably be clearer:
```
PO* P[1000]; // <-- P is an array of 1,000 pointers to PO
```
What you probably want is a preallocated array of structures, not pointers to those, e.g.:
```
PO Data[1000];
```
In this case, you can read data into it with code like this:
```
scanf("%d%c", &(Data[0].a), &(Data[0].b));
```
Or, if you still want an array of pointers, you should allocate each structure usingmalloc()and thenfree()it after use.
|
I have a stringrangethat represents a range, for example:
```
"7-35"
```
I am looking for a simple way to split it into two integersint beginandint end.I already sawthisandthis, but I am actually searching for some kind of a "one line" command if there exist any.It is actually the opposite of doing:
```
sprintf(range,%d-%d,start,end);
```
|
The opposite of printing is scanning, and you'd usesscanf():
```
unsigned int start, end;
if(sscanf(range, "%u-%u", &start, &end) == 2)
printf("start=%u, end=%u\n", start, end);
```
Some notes:
We useunsigned intand%uto make the embedded dash non-ambigousAlways check the return value to make sure the scanning succeeded
|
I want to change a value in the stack inside another function.
```
int Function(int *var){
int i=125;
var = i;
}
int Function2(){
int apple;
Function(&apple);
printf("%d", apple);
}
```
This shows meerror: assignment makes pointer from integer without a castat this linevar = 125;.
I want to copy the value ofiintovarin order to getapple = 125. (But when I will leave theFunction,iinside the stack will be freed.)
I don't see where I made a mistake.
|
You need to dereference the pointer.
```
*var = 125;
```
As written you are trying to change the address stored in the pointer (i.e., the thing the pointer is pointing to).
|
According to thecplusplus.com,tm_secfield from thetmstructure accept values from 0 to 61 in C90 and values from 0 to 60 in C99 and later.
I know that 60 can be used to express leap second but what about the other one (I mean 61)? And why did they choose to remove it?
Yeah, I tagged it both C and C++ because it is related to both languages in this case.
|
A range of0to61allows for up to 2 consecutive leap seconds on December 31st of a given year, probably mistakenly because in years that require 2 leap seconds, these are not added on the same day.
Newer versions of the C Standard correctly assume that at most one leap second will be inserted at a time on any given day.
As explained in detail inhttps://en.wikipedia.org/wiki/Leap_secondleap seconds are inserted in December and/or June in order to avoid a drift longer than 0.9 second, hence the maximum value fortm_secshould be60instead of61.
|
This question already has answers here:Yosemite and Valgrind(12 answers)Closed6 years ago.
I am not sure if I can installvalgrinddebugger in my Macbook Pro. I searched online but most posts are related to Ubuntu. Can someone tell if this is possible? If so, can it be by brew for example?
|
you can use "brew install valgrind" to install valgrind.
|
I'm trying to explain this satisfactorily, but when I call a function I want it to virtually insert itself into the main function's code in the place where I call it, so I can save typing it out multiple times, however it directly affects variables defined in the scope of the main function. What's the best way to achieve this?
EDIT: I should probably make it clear I also want it to take a single argument.
|
Sounds like you need a preprocessor macro. These aren't real functions, but blocks of code the the preprocessor replaces before compiling the code. E.g., consider a simple macro to increment a number:
```
#include <stdio.h>
#define INC(x) (x)++
int main() {
int a = 1;
INC(a);
INC(a);
printf("%d\n", a);
return 0;
}
```
The textINC(a)will be replaced witha++, so running this program will print out 3 (1 after two increments).
|
I am trying to invoke python script from C application usingsystem()call
The python script has#!/usr/bin/python3on the first line.
If I dosystem(python_script), the script does not seem to run.
It seems I need to dosystem(/usr/bin/python3 python_script).
I thought I do not need to specify the interpreter externally if I have#!/usr/bin/python3in the first line of the script.
Am I doing something wrong?
|
Make sure you have executable permission forpython_script.
You can makepython_scriptexecutable by
chmod +x python_script
Also check if you are giving correct path forpython_script
|
I am trying to invoke python script from C application usingsystem()call
The python script has#!/usr/bin/python3on the first line.
If I dosystem(python_script), the script does not seem to run.
It seems I need to dosystem(/usr/bin/python3 python_script).
I thought I do not need to specify the interpreter externally if I have#!/usr/bin/python3in the first line of the script.
Am I doing something wrong?
|
Make sure you have executable permission forpython_script.
You can makepython_scriptexecutable by
chmod +x python_script
Also check if you are giving correct path forpython_script
|
I want to add a string to a string array but it doesn't work.Currently, I have that code:
```
void splitArray(char *strings, char *delimiter) {
int i = 0;
char newArray[MAXCHARS];
char* pch = NULL;
pch = strtok(strings, delimiter);
while (pch != NULL)
{
// doesn't work; Exception: warning: assignment makes integer from pointer without a cast [enabled by default]
newArray = pch;
printf("%s\n", pch);
pch = strtok(NULL, delimiter);
}
}
```
How can I solve that problem?
|
Use strcpy to copy string to char array.
|
I am trying to invoke python script from C application usingsystem()call
The python script has#!/usr/bin/python3on the first line.
If I dosystem(python_script), the script does not seem to run.
It seems I need to dosystem(/usr/bin/python3 python_script).
I thought I do not need to specify the interpreter externally if I have#!/usr/bin/python3in the first line of the script.
Am I doing something wrong?
|
Make sure you have executable permission forpython_script.
You can makepython_scriptexecutable by
chmod +x python_script
Also check if you are giving correct path forpython_script
|
I want to add a string to a string array but it doesn't work.Currently, I have that code:
```
void splitArray(char *strings, char *delimiter) {
int i = 0;
char newArray[MAXCHARS];
char* pch = NULL;
pch = strtok(strings, delimiter);
while (pch != NULL)
{
// doesn't work; Exception: warning: assignment makes integer from pointer without a cast [enabled by default]
newArray = pch;
printf("%s\n", pch);
pch = strtok(NULL, delimiter);
}
}
```
How can I solve that problem?
|
Use strcpy to copy string to char array.
|
I don't understand why the last two lines cause warning using strlen(). Shouldn't the compiler ignore these?
```
size_t len;
char cstr[] = "char string";
signed char scstr[] = "signed char string";
unsigned char ucstr[] = "unsigned char string";
len = strlen(cstr);
len = strlen(scstr); /* warns when char is unsigned */
len = strlen(ucstr); /* warns when char is signed */
```
|
Because the prototype is:
size_t strlen ( const char * str );
as stated on theref.
An implicit conversion is happening in these lines, thus the warnings. Read more here:How can I avoid gcc warning for plain "char" to : "unsigned char" OR "signed char" conversion?
As Pete Becker stated:
"chartounsigned charinvolves an implicit conversion.unsigned char*tochar*, as in the code in the question, is not valid, and requires a diagnostic. "
|
Is there any way to roundsystemGuessup. In this case the outcome ofsystemGuessis 5.5 I want it to be 6 how do I do this?
See code below:
```
int main(void){
int systemGuess = 0;
stystemGuess = (10 - 1)/2 + 1;
printf(" %d ", stystemmGuess);
}
```
|
Use floating point division andceil:
```
stystemGuess = ceil((10 - 1)/2.0) + 1;
```
If you want to round 0.4 down, useroundinstead.
|
This is part of my code:
```
float score_from_judge(number_judges, n)
{
float judge_score;
printf("Score from judge %d? ", n);
scanf("%f", &judge_score);
return(judge_score);
}
int main(void)
{
int n;
float judge_score;
n=1;
for(n; n<=number_judges; n++ ) {
judge_score = score_from_judge(number_judges, n)
}
}
```
I am looking for a way to save judge_score in a variable every time score_from_judge returns the value.
I am trying to find a way to make a new variable for each loop.
For example, first time I recieve judge_score it is saved in variable_1 and next time in variable_2 etc.
|
declare a float array and set its value inside the 'for' loop, as shown:
```
int main(){
float judge_score[10];
for(int n=1; n<=number_judges; n++ ) {
judge_score[n] = score_from_judge(number_judges, n);
}
}
```
|
My code:
```
#include <stdio.h>
int main() {
int M, N, O, P;
printf("Enter the value of M\n");
scanf("%d", &M);
N = 3*M^2;
O = M + N;
P = M + M;
printf("The value of %d \n", M + %d \n", M equals %d \n", P %d \n", N %d \n", O);
return 0;
}
```
The error:
test.c: In function 'main':test.c:9: error: expected expression before '%' tokentest.c:9: error: stray '' in programtest.c:9: error: stray '' in program
I can't figure out how to properly print the values ofM,N,O,Pand test alongside with it.
|
You seem to have mixed up your formatting string, with some %d and \n outside of your quotes.
Try writing your entire formatting string first, then each of the arguments; like so:
```
printf("The value of %d \nM equals %d \nN %d \n", M, P, 0);
```
Each %d should correspond to the number you want to print from the arguments, given in order.
|
I wanted to know the meaning of space after the format specifier in scanf. There are many posts related to space in scanf and most of them talk of the space before %c. In the below code, I have to enter second character for first scanf to return. Just entering enter key will not break the scanf. Because of this second character, second scanf for reading the string is also getting affected.
Can I say that space after %c is for ignoring all white spaces entered after the character and wait until next character? But why "enter" key is not considered as a character itself?
```
char str[50];
char c;
printf("Enter the Character:");
scanf("%c ",&c);
printf("Char read is: %c",c);
printf("Enter the string:");
scanf("%s",str);
printf("%s", str);
```
|
If you use trailing space after"%c"thenscanfwill need to find the next non-white-space to be able to return. If there is none thenscanfwill block for ever.
|
I am using this :
```
if(strstr(inData, respond) != NULL)
```
to search for the stringCMDinsideinData.
problem is that when new data looks like this :
```
Reboot
CMD
```
strstrwill not find it, because it stops searching where is a new line.
Is there an elegant way (notusing fancy functions since I can't) to get over it ?
|
As pointed out in the comments, strstr does not stop at newline boundaries, but only at string terminators (\0)
Here is the relevant section from the man page:
DESCRIPTION
The strstr() function finds the first occurrence of the substring needle in the string haystack. The terminating null
bytes
('\0') are not compared.
So the assumption is, that there are null bytes within one of CMD or inData.
You should investigate the string inData and CMD inthis wayorhexdump it(as suggested by @BLUEPIXY)
|
I have been working on a college project. I want user to enter Y/N if he wants to continue or not, so I wrote following code
```
repeat:
pr=0;
q=0;
res=0;
printf("\nEnter the serial number of product you wish to purchase: ");
scanf("%d",&pr);
printf("Quantity: ");
scanf("%d",&q);
billing(pr,q);
printf("Continue Shopping? (y/n) ");
scanf("%d",&res);
if(res=='y')
goto repeat;
else
return 0;
}
```
The problem is entering y executes else statement. I tried replacing y with 1,2,3.... and it works but I want it to work with Y or y or yes.
|
There is a bug in this line
```
scanf("%d",&res);
```
It should be
```
scanf(" %c",&res);
```
The formatting placeholders for char is%cnot%d
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed6 years ago.Improve this question
```
#include <stdio.h>
int main(){
char c;
while((c = getchar()) != EOF){
if(c >= 'A' && c <= 'Z')
c = c - 'A' + 'a';
putchar(c);
}
return 0;
}
```
Came across this C code in MIT's Practical Programming in C. Can anyone explain how this program works?
|
The program converts any input into lower case output.
You would have recognized this yourself, if youran it,debugged it, or justmade a paper testfor this.
|
Is there a possibility to load a system font usingsdl2-ttf. I read the documentation but there seems only the way of loading a font with the full file path. On windows this would be a bit easier than in linux, as you can find the font folder relativly easy, but on Linux this is more of an issue as fonts can be stored in different places (e.g./usr/shareand in the home folder in the font folder). I did not find a reliable way yet to do this under linux, under Windows I find the installation dir of windows and append\font\<name>to it.
|
To display text on Linux you need to go through harfbuzz-ng (for correct text shaping) and fontconfig (for font discovery and substitution), either directly or via a third-party lib such as pango or cairo.
Direct use of ttf files bypasses the font location stack, font substitution stack, correct opentype metadata parsing, it's a partial solution and won't ever work too well.
For exampleorvia pango
|
In TensorFlow, you can create custom allocators for various reasons (I am doing it for new hardware). Due to the structure of the device, I need to use a struct of a few elements as my data pointer which the allocator returns as avoid*.
In the kernels that I am writing, I am given access to Tensors but I need t get the pointer struct that I wrote. Examining the classes, it seemed that I could get this struct by doingtensor_t.buf_->data()
Tensor::buf_
TensorBuffer::data()
The problem is that I can't find code that does this and I am worried that it is unsafe (highly likely!) or there is a more standard way to do this.
Can someone confirm if this is a good/bad idea? And provide an alternative if such exists?
|
You may also be able to useTensor::tensor_data().data() to get access to the raw pointer, without using the weird indirection through DMAHelper.
|
I have a file pointercurrent_fileof typeFILE *current_file;. When I run this code
```
current_file = fopen ("file.text", "r");
struct buffer *buf;
buf->file = current_file;
```
I keep ending with aSegmentation fault (core dumped). Herebufferis a struct like so:
```
struct buffer {
FILE *file;
int size;
};
```
I am completely stuck wit what's making this die. Thanks for taking time to read this!
|
You only declare buf to be a pointer of the type buffer, but there is no memory allocated for the struct.
Therefore you have an uninitialized pointer.
|
I came across this syntax today and couldn't work out what it meant:
```
// Uses the GNU C statement expression extension
#define envSet(name) ({ \
static int initialised; \
static bool set; \
(void) "" name; \
if (!initialised || !g_cacheEnv) { \
const char *value = getenv(name); \
set = value != NULL; \
initialised = true; \
} \
set; \
})
```
The specific line I cannot understand is:
```
(void) "" name; \
```
Could somebody please shed some light on this?
|
It looks like a way to statically ensure thatnameis a string literal and not some other type.
If you do(void)"" "hello";then it is a valid C expression.
But if you do something like(void)"" 1;then you get a syntax error.
|
When you define a structure like below
```
typedef struct num {
int a;
int b;
} A;
```
Thensizeof(A)is valid, butsizeof(num)isn't. Could anyone please explain the reason why the sizeof operator doesn't acceptnum?
|
Becausenumon its own doesn't constitute atypein C (onlystruct numor its typedefAconstitutes thetype). So,sizeoffails as its operand is not in either form of that it's defined for:
```
sizeof unary-expression
sizeof ( type-name )
```
i.e.numis neither atypenor aunary-expression.
So,sizeof(struct num)orsizeof(A)is fine butsizeof(num)isn't.
|
I am trying to compile sqlite from sources (amalgamation) to use it from C#. The reason to compile it myself rather than use precompiled version is that I need JSON support which is not included by default. This is how I compiled it:
```
cl sqlite3.c -DSQLITE_ENABLE_JSON1 -link -dll -out:sqlite3.dll
```
Then I tried to replace precompiled version of sqlite3.dll in my application with the version I compiled myself, and my C# application started to crash with EntryPointNotFoundException.
How to fix this, and what is the right way to compile SQLite?
|
The solution is to export the API functions:
```
cl sqlite3.c -DSQLITE_API=__declspec(dllexport) -link -dll -out:sqlite3.dll
```
|
I am trying to memcpy from one ptr to another. I know the size that I want to copy. Both the destination and source pointers are void pointers. Is this valid? Does it actually copy the ELEMENT_SIZE (integer like 128) from source to the destination? I know this is not the most ideal thing to do. But I want to know if this works.
```
memcpy(to_add, element_ptr, ELEMENT_SIZE);
```
|
Does it actually copy the ELEMENT_SIZE (integer like 128) from source
to the destination?
Yes, If you know the size information,then its working fine.
See the reference link :http://www.cplusplus.com/reference/cstring/memcpy/
|
I want to evaluate the following boolean expression in C:
```
f = (b+c')(a'+c')(a+b'+c)
```
This is my current program:
```
#include <stdio.h>
int main()
{
int a,b,c,f;
a=0;b=1;c=1;
f=((b|(~c))&((~a)|(~c))&(a|(~b)|c));
printf("%d\n",f);
}
```
The function should return 1 since a=0,b=1 and c=1 but it returns -1.
Also, when a=1,b=1 and c=1 it returns -2 instead of 0.
Why does this happen? How can I fix it?
|
In C you use!for negation:
```
#include <stdio.h>
int main()
{
int a,b,c,f;
a=0;b=1;c=1;
f=((b||(!c))&&((!a)||(!c))&&(a||(!b)||c));
printf("%d\n",f);
}
```
The~operator flips all the bits in a number, which is not what you wanted, and why you were getting -1.
Also you need||instead of|and&&instead of&. The&and|operators work on individual bits, where as the||and&&are logical operators and do what you want.
|
I want to have a regex that contains one and only one "-", followed by "s" or "h".
So, "-shshshshs" would match, "-ssssss" would too, but "-so" would not match, neither would "sh".
So far, I only succeeded to match "if strings contains "-" and "s" or "h", but typing "-sho" is accepted.
```
/* Compile regular expression */
reti = regcomp(®ex, "-[sh]", 0);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
exit(1);
}
/* Execute regular expression */
reti = regexec(®ex, "--sh", 0, NULL, 0);
if (!reti) {
puts("Match");
} else {
puts("No match");
}
```
Thanks in advance.
|
If your regex engine supports it:
```
"-[sh]+$"
```
Otherwise:
```
"-[sh][sh]*$"
```
|
Give the c code for a loop that computes and displays a sum of numbers that the user enters. The loop should prompt the user for input until the user enters -335 and then exit and display the final sum.
This is what I have. Why does it not print (exit the loop) when I enter -335? It just keeps asking me to input a number.
```
#include <stdio.h>
int main(void)
{
int userNum;
printf("Please enter an integer:\n");
scanf("%d", &userNum);
while (userNum != -335){
printf("Please enter an integer:\n");
scanf("%d", &userNum);
userNum += userNum;
}
printf("%d", userNum);
return 0;
}
```
|
userNum changes after you have input it, in the statementuserNum += userNum;. -335 plus -335 is -670, not 335.
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed6 years ago.Improve this question
How show 00156,00
```
float number = 156;
printf("%5.2f",number);
```
The output of the example above:
Output: 156.00
|
You need to pass the0flag for leading zeros, and the field width must be wide enough to have any leading characters printed. So you might try this:
```
printf("%08.2f", number);
```
The.verses,(aka, the "radix character") is determined from the LC_NUMERIC portion of the locale. Seeman setlocalefor information on setting this programatically.
|
Functions likememchrseem quite simple but Rust projects usebindings to the C codewith only a Rust fallback, rather than implementing them in Rust. Can'tmemchrbe efficiently implemented in Rust?
|
They can. If you look at glibc's implementation, it will look somewhat likefallback:memchr. However, that's only part of the story. Thegeneric implementationis used only when there isn't a more appropriate one available.
For example,x68-64 has a variant written in assembly. And so domanyotherarchitectures, that provide sophisticated instructions.
So to reach the same speed, Rust would have to provide something similar on instruction level, which essentially boils down to the same (or better) assembly. At that point you're just duplicating work. It's already there, no need to create everything anew.
|
I have a huge project consisting of:
main.cwhich contains main function and calls function fromabc.S- nothing more!abc.Swhich does some initialization steps and then calls other assembly routinesa1.S,a2.S, ... which contain functions called byabc.S
abc.Shas all the files included like this:
```
.include "a1.S"
.include "a2.S"
.include "a3.S"
```
Now I want to include a file calleddefinitions.hwhich contains somedefine MEOW 123and I want to useMEOWin e.g.a1.S- how does my makefile have to look like to achieve this behaviour? Where do I have to includedefinitions.h?
I tried a few things but ended up having nothing but errors.
|
Figured it out for myself - makefile could look like this:
```
all:
gcc -o abc a1.S a2.S a3.S abc.S main.c
clean:
rm -rf abc
```
Includedefinitions.hina1.Sand includea1.Sinabc.S.
|
I am new to kernel module programming and got some problem while compiling some old kernel code. I am getting following error messages,
```
error: ‘struct tty_driver’ has no member named ‘write’
((my_tty->driver)->write) (my_tty,0,str,strlen(str));
```
I checked thetty_driver.hfile, therewriteis defined. So, Whats going on? How can I access in version3.13.0-24?
My code is here:
```
void print_string(char *str)
{
struct tty_struct *my_tty;
my_tty = get_current_tty();
if (my_tty != NULL)
{
(*(my_tty->driver)->write)(my_tty, 0, str, strlen(str));
}
}
```
Thanks in advance..
|
writeis indeed defined, but not as members oftty_driver. It is defined as members oftty_operations, andtty_driverhas a memberops, a pointer to aconst tty_operations.
So, I usedmy_driver->ops->writeinstead ofmy_driver->driver->write.
|
I want to get a number of days from a certain date to current date.
Here is my current code that gets the days from 1/1/1970.
```
int days_since_my_birth(int day, int month, int year) {
time_t sec;
sec = time(NULL);
printf("Number of days since birth is %ld \n", sec / 86400);
return d;
}
```
Can I use thetime()function to get the number of seconds from a date I entered?
|
Subtract the julian day integer of the earlier date from the julian integer of the later date. The following tells you exactly how to do that.
http://www.cs.utsa.edu/~cs1063/projects/Spring2011/Project1/jdn-explanation.html
Otherwise,http://pdc.ro.nu/jd-code.htmlalready has a C version
```
long gregorian_calendar_to_jd(int y, int m, int d)
{
y+=8000;
if(m<3) { y--; m+=12; }
return (y*365) +(y/4) -(y/100) +(y/400) -1200820
+(m*153+3)/5-92
+d-1;
}
```
|
This question already has answers here:What is the difference between macro constants and constant variables in C? [duplicate](4 answers)Closed6 years ago.
I am rewriting a function and I noticed one particular variable is never reassigned after initialization. Is there any reason NOT to simply convert this variable to a macro? Is a macro ALWAYS preferable in this case?
Thanks!
|
A macro is basically never preferable compared to a variable, since a variable which doesn't change its value can be declared asconstand it will likely be optimized away in any case.
```
const int CONST_VALUE = 1234;
```
is safer and clearly expresses the meaning more than a macro.
|
I've found an interesting way to allocate matrices in C which allows the use of[i][j]without initializing asdouble matrix_a[nrows][ncols]. The allocation is
```
double (*matrix_a)[ncols] = (double (*)[ncols])malloc(sizeof(double) * (nrows) * (ncols));
```
But I can't find how to properly free this type of allocation. Would it be as simple asfree(matrix_a)?
|
That is correct. You may only pass tofreewhat was returned frommallocand family. So since you did onemalloc, you do onefree.
Also,there is no need to cast the return value of malloc:
```
double (*matrix_a)[ncols] = malloc(sizeof(double) * (nrows) * (ncols));
```
|
```
void main()
{
char a;
float f = 10;
for(a=1; a<=5; a++)
{
f-=.2;
printf("\nf = %g", f);
}
}
```
Here the for loop is executive five times and each time the value of f is decremented by .2.But according to me the final value of f should be 9.0 but output is 9.
Why the value of f is not coming in decimal point ?
|
The decimal point is not shown for%gconversions if there is no non-zero digit following the decimal point. You can use%finstead, or explicitly specify the number of digits you want to see behind the decimal point, for example%.1gto always show 1 digit.
|
Why we don't use extern when using function from one .c file in another .c file , but we must do extern for variables case? Is it related to linker?
|
Functions are extern qualified by default (unless you change it to internal withstatic). For example,
```
int func(void) {
}
extern int func2(void) {
}
```
Bothfuncandfunc2are external. Theexternkeyword is optional for external functions.
|
Functions likememchrseem quite simple but Rust projects usebindings to the C codewith only a Rust fallback, rather than implementing them in Rust. Can'tmemchrbe efficiently implemented in Rust?
|
They can. If you look at glibc's implementation, it will look somewhat likefallback:memchr. However, that's only part of the story. Thegeneric implementationis used only when there isn't a more appropriate one available.
For example,x68-64 has a variant written in assembly. And so domanyotherarchitectures, that provide sophisticated instructions.
So to reach the same speed, Rust would have to provide something similar on instruction level, which essentially boils down to the same (or better) assembly. At that point you're just duplicating work. It's already there, no need to create everything anew.
|
I have a huge project consisting of:
main.cwhich contains main function and calls function fromabc.S- nothing more!abc.Swhich does some initialization steps and then calls other assembly routinesa1.S,a2.S, ... which contain functions called byabc.S
abc.Shas all the files included like this:
```
.include "a1.S"
.include "a2.S"
.include "a3.S"
```
Now I want to include a file calleddefinitions.hwhich contains somedefine MEOW 123and I want to useMEOWin e.g.a1.S- how does my makefile have to look like to achieve this behaviour? Where do I have to includedefinitions.h?
I tried a few things but ended up having nothing but errors.
|
Figured it out for myself - makefile could look like this:
```
all:
gcc -o abc a1.S a2.S a3.S abc.S main.c
clean:
rm -rf abc
```
Includedefinitions.hina1.Sand includea1.Sinabc.S.
|
I am new to kernel module programming and got some problem while compiling some old kernel code. I am getting following error messages,
```
error: ‘struct tty_driver’ has no member named ‘write’
((my_tty->driver)->write) (my_tty,0,str,strlen(str));
```
I checked thetty_driver.hfile, therewriteis defined. So, Whats going on? How can I access in version3.13.0-24?
My code is here:
```
void print_string(char *str)
{
struct tty_struct *my_tty;
my_tty = get_current_tty();
if (my_tty != NULL)
{
(*(my_tty->driver)->write)(my_tty, 0, str, strlen(str));
}
}
```
Thanks in advance..
|
writeis indeed defined, but not as members oftty_driver. It is defined as members oftty_operations, andtty_driverhas a memberops, a pointer to aconst tty_operations.
So, I usedmy_driver->ops->writeinstead ofmy_driver->driver->write.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.