question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
In C Linux , I can declare variable as static into function , and it init only once and each time the CPU will see that declaration again it will be skip , or declare globally
Witch one of those function will have better performance ?
```
void increase_x()
{
static int x =0;
x+=1;
}
static int x = 0 ;
void increase_x()
{
x+=1;
}
```
|
There's no difference. You can even see this in a diff of the disassembly of the compiled code:
```
< localstatic: file format elf64-x86-64
---
> globalstatic: file format elf64-x86-64
107c107
< 1131: 8b 05 dd 2e 00 00 mov 0x2edd(%rip),%eax # 4014 <x.0>
---
> 1131: 8b 05 dd 2e 00 00 mov 0x2edd(%rip),%eax # 4014 <x>
109c109
< 113a: 89 05 d4 2e 00 00 mov %eax,0x2ed4(%rip) # 4014 <x.0>
---
> 113a: 89 05 d4 2e 00 00 mov %eax,0x2ed4(%rip) # 4014 <x>
```
|
In C (not C++)
what is the difference between:
```
function(int &a)
{
a = a + 2;
}
```
and:
```
function(int *a)
{
*a = *a + 2;
}
```
For what I understand they are the same no?
If there are differences can you explain them with examples?
|
int &ais not code defined by the C standard and generally cannot be used in C. In C++, this declares areferenceto an object, which is like a pointer but does not require*when using the object that is pointed to, cannot be changed once created, and cannot use a null pointer.
For C++, differences between pointers and references are discussedhere. In C, you cannot normally useint &a. (It could be used in some hypothetical C implementation that supported it as extension, which is how C++ originated.)
|
I`m struggling with an error in C code.
```
#define MAX(i, limit) do \
{ \
if (i < limit) \
{ \
i++; \
} \
} while(1)
void main(void)
{
MAX(0,3);
}
```
This leads into the following error.
```
Error[Pe137]: expression must be a modifiable lvalue
```
Any ideas? Thank you in advance.
|
For starters according to the C Standard the function main without parameters shall be declared like
```
int main( void )
```
You passed to the macro MAX integer constant 0. You may not increase it.
In fact the macro expands to the following code
```
do
{
if ( 0 < 3 )
{
0++;
}
} while(1);
```
Macros are not functions. So in your macro there is performed a direct substitution i and limit for 0 and 3.
You could declare a variable and initialize it with the value 0 and pass it to the macro. In this case you will get an infinite loop.
|
I use WSAConnect to connect to a server whose site has the prefix http: \ That is, it seems like the remote server should connect only on port 80. But, in fact, I see that for some pages of this http site - WSAConnect completes successfully on port 443.
Is it okay? Is this allowed?
|
WSAConnectis for low-level socket communication, for example low-level TCP/IP sockets.
Web servers use HTTP for communication with clients, such as browsers. HTTP is an application protocol on top of TCP/IP.
By default web servers use port 80 for plain HTTP communication. Webservers can also support HTTP over a secure connection (HTTPS). The default port for this is 443.
So it is perfectly fine for a web server to be reachable on port 80 and 443.
In general, a single server can be reachable on any number of ports. Different ports are used for different protocols.
|
For debugging purposes, when there are many make file inclusions, it's useful to print the full path of the makefile where a particular variable in the current makefile was first defined. Is there a way to do that?
|
Just runmake -p. Make will print its internal database including all targets and variables that were seen along with the filename and linenumber where they were set.
|
I'm printing out and array of three bytes like this:
cmd_bufis passed as aconst char *
```
for (ii = 0; ii<=2; ii++) {
printf("byte[%0d] = %02x\n", ii, cmd_buf[ii]);
}
```
But I'm seeing this:
```
# BUFFER IS b4a602
# byte[0] = ffffffb4
# byte[1] = ffffffa6
# byte[2] = 02
```
It works properly if I do this:
```
printf("byte[%0d] = %02x\n", ii, (unsigned char) cmd_buf[ii]);
```
Shouldn't%02xbe printing only two characters? Why is it acting like this is an signed value?
|
%x is int - it implicitly turned your signed char into a 4-byte to match. use %hx for short and %hhx for char. In your case, you likely meant to use %02hhx
|
Everything I look up just tells me how to do complement operations/calculations in C.
I want to know what representation does C use internally and how does it handle with overflow.
|
C allows 3 representation for signed integers
(https://port70.net/~nsz/c/c11/n1570.html#6.2.6.2p2):
the corresponding value with sign bit 0 is negated (sign and
magnitude);the sign bit has the value -(2M) (two's complement);the sign bit has the value -(2M- 1) (ones' complement).
Two's complement is most common.
Unsigned overflow wraps around the maximum value for the unsigned.
Signed overflow causes undefined behavior. I.e., it is assumed not to happen, and if you do make it happen, no guarantees can be made about your program's behavior.
Overflow in signed atomics is an exception: it is well defined and two's complement is mandated there:https://port70.net/~nsz/c/c11/n1570.html#7.17.7.5p3.
|
I want to initialise all three arrays of mainstr , can anyone help me to initialise this anonymous union inside the struture? 0th index should initialise with interger array and 1st and 2nd indexes with char pointer.
```
typedef struct
{
int testy;
union
{
int a[3];
char* b[3];
}
bool testz;
} testStr;
typedef struct
{
testStr x[3];
} mainStr;
```
something like this,
```
mainStr test = {
{20, {{10, 20, 30}}, FALSE},
{10, {{"test1", "test2", NULL}}, TRUE},
{30, {{"test3", "test4", NULL}}, FALSE},
}
```
|
Usedesignators:
```
mainStr test = {{
{20, {{10, 20, 30}}, false},
{10, {.b={"test1", "test2", NULL}}, true},
{30, {.b={"test3", "test4", NULL}}, false},
}};
```
Demo
|
Hello guys im writing a program c that have to read a list of files in a directory, but when I print the names of files there are 2 file: "." and "..".
Is there any way to prevent it from reading these two files, without doing an explicit check?
My code is:
```
d = opendir("myfolder");
if (d) {
while((dir = readdir(d)) != NULL){
strcpy(path,"myfolder");
strcat(path,"/");
strcat(path,dir->d_name);
printf("File name: %s ",dir->d_name);
}
//... other things like closing dir and file.
```
|
Because files with those names exist in the directory.
```
$ ls -1a
.
..
.bash_history
.bash_logout
.bashrc
⋮
bin
projects
tmp
usr
```
.is a hardlink to the directory that contains it...is a hardlink to the parent of the directory that contains it.
Most of the time, you want to ignore files that have a name starting with ".".
Similar idea in Windows.
|
I have just set up VS code for C++ today and I tried to check if everything works perfectly. First I tried to print "Hello World" and it worked. Then I wrote this:
```
#include <stdio.h>
int main()
{
int x = 10, y = 20, z;
z = x + y;
printf("%d + %d = %d", &x, &y, &z);
return 0;
}
```
After running that simple code, I got an output:6422220 + 6422216 = 6422212
What did go wrong?
|
You are printing the addresses ofx,yandzhere
```
printf("%d + %d = %d", &x, &y, &z);
```
This will print the values
```
printf("%d + %d = %d", x, y, z);
```
|
I was looking into the following C snippet:
```
char x = 'a';
int y = 5;
```
After running gdb I encounter the following assembly:
```
mov BYTE PTR [ebp-1], 0x61
mov DWORD PTR [ebp-8], 0x5
```
Why isebpdecreased by 7 instead of 4? If I replacechar x = 'a'withint x = 2, I don't see this behavior.
|
In your C implementation,intobjects must be stored at addresses that are multiples of four, usually due to hardware alignment requirements or features. The address in the EBP register is known to be a multiple of four (and likely a multiple of 16, depending on your C implementation). So[ebp-5]would not be at a multiple four bytes, nor would[ebp-6]or[ebp-7]. The compiler has to go to[ebp-8]to get to the next multiple of four.
([ebp-2],[ebp-3], and[ebp-4]are not considered because starting a four-byteintat any of those addresses would overlap the byte in[ebp-1]used for thechar.)
|
Is it possible to use dynamic memory allocation, or some other method, to make a 1000-bit (or 1024-bit) integer variable?
Obviously, this is an insane amount, but I'm just using this amount as an example. Basically, can I make an integer any size I want? I'm thinking maybe dynamic memory allocation would work, or perhaps something to do with char arrays?
|
Depends on what exactly you mean.If you mean "a fully functionalintthat the compiler knows how to handle and can be used with the built-in arithmetic operators", the answer would be no.If you mean "allocate an arbitrary size of memory that I'll treat as a continuous integer and write my own custom mathematical functions for", the answer is most definitely yes, and there are in factseveral librariesthat do exactly that.
|
This question already has answers here:Why is adding a leading space in a scanf format string recommended?(2 answers)scanf getchar function is skipped(3 answers)scanf Getting Skipped [duplicate](1 answer)scanf() leaves the newline character in the buffer(7 answers)Closed2 years ago.
After first successful iteration, the second print statement is automatically getting printed. It is taking a whitespace its input.
Why does this happen?
```
#include<stdio.h>
int main() {
char c;
while (1)
{
printf("\nEnter any character to get its ASCII value - ");
scanf("%c",&c);
printf("Ascii value of %c : %d",c,c);
}
}
```
Sample output:
|
It's because the linefeed still remains in the input buffer, changescanf("%c",&c);toscanf(" %c",&c);and it'll work as expected.
|
Could you please give a thorough explanation of this ?
|
You can try, but if the assignment succeeds it will not store the entirety of your original number, because representing it with accuracy requires more than 16 bits.
The highest order bit in a 16 bit integer is the 215place. Two to the fifteenth power is 32768. Setting your 16 bits to all ones will yield 65535 (32768 * 2 - 1), if the integer is unsigned, so that's the highest number you can assign reliably.
In any case, this is easy enough to test:
```
#include <stdio.h>
int main(void) {
unsigned short i = 72368;
printf("%d\n", i); // 6832
return 0;
}
```
Note that 72368 is interpreted as anint, and an implicit conversion occurs tounsigned short, although the compiler will warn you.Try it online.
|
AreHAS_SUBNORMand__STDC_IEC_559__dependent? For example:
If__STDC_IEC_559__is 1, thenHAS_SUBNORMis 1.IfHAS_SUBNORMis 0, then__STDC_IEC_559__is not 1.
|
AreHAS_SUBNORMand__STDC_IEC_559__dependent?
I'd suggest no.__STDC_IEC_559__ == 1andxxx_HAS_SUBNORM != 1possible.
C17 Appendix F specifies what is needed to conform to__STDC_IEC_559__: "An implementation that defines__STDC_IEC_559__shall conform to the specifications in this annex."
Appendix F does not specify support of subnormal's and even has in 2 places describing functions:
... When subnormal results are supported, the returned value is exact and is independent of the current rounding direction mode. C17dr § F.10.7.2&3 2.
This at least implies subnormal support is not required for those functions. Also see@Ian Abbott
Nit:
"__STDC_IEC_559__is not 1." is more like "__STDC_IEC_559__not defined", not "if defined and not 1".
|
I am working on C implementations of calculus operations (such as derivatives, integrals, etc...). As an example, here's the template definition of myderivativefunction:
```
double derivative(double (*f)(double), double x);
```
Let's say I want to compute the derivative ofexpat 1, the call would then be:derivative(exp, 1);
Pretty basic stuff. Now my question is, how would I go about (if it is even possible) to pass a composition to myderivativefunction? I tried passingexp(cos)which got me
error: passing 'double (double)' to parameter of incompatible type 'double'.
How would I do it? Is it even possible?
|
I think you're asking for this:
```
double composition(double x) {
return exp(cos(x));
}
derivative(composition, 1);
```
Many languages allow you to do something like the following, but C doesn't have anon functions:
```
derivative(x => exp(cos(x)), 1);
```
|
given that
```
int w = 1;
int x = 6;
int y = 5;
int z = 0;
z = !z || !x && !y;
printf("%d\n", z);
z = x-- == y + 1;
printf("%d\n", z);
```
Could someone explain how the line below would evaluate to 1 if x-- is 5 and y+1 is 6?
```
z = x-- == y + 1;
```
|
The expressionx--evaluated to the value ofxbeforebeing decremented.
Sox-- == y + 1is the same as6 == 5 + 1which is true, then the value 1 is assigned toz.
|
AreHAS_SUBNORMand__STDC_IEC_559__dependent? For example:
If__STDC_IEC_559__is 1, thenHAS_SUBNORMis 1.IfHAS_SUBNORMis 0, then__STDC_IEC_559__is not 1.
|
AreHAS_SUBNORMand__STDC_IEC_559__dependent?
I'd suggest no.__STDC_IEC_559__ == 1andxxx_HAS_SUBNORM != 1possible.
C17 Appendix F specifies what is needed to conform to__STDC_IEC_559__: "An implementation that defines__STDC_IEC_559__shall conform to the specifications in this annex."
Appendix F does not specify support of subnormal's and even has in 2 places describing functions:
... When subnormal results are supported, the returned value is exact and is independent of the current rounding direction mode. C17dr § F.10.7.2&3 2.
This at least implies subnormal support is not required for those functions. Also see@Ian Abbott
Nit:
"__STDC_IEC_559__is not 1." is more like "__STDC_IEC_559__not defined", not "if defined and not 1".
|
I am working on C implementations of calculus operations (such as derivatives, integrals, etc...). As an example, here's the template definition of myderivativefunction:
```
double derivative(double (*f)(double), double x);
```
Let's say I want to compute the derivative ofexpat 1, the call would then be:derivative(exp, 1);
Pretty basic stuff. Now my question is, how would I go about (if it is even possible) to pass a composition to myderivativefunction? I tried passingexp(cos)which got me
error: passing 'double (double)' to parameter of incompatible type 'double'.
How would I do it? Is it even possible?
|
I think you're asking for this:
```
double composition(double x) {
return exp(cos(x));
}
derivative(composition, 1);
```
Many languages allow you to do something like the following, but C doesn't have anon functions:
```
derivative(x => exp(cos(x)), 1);
```
|
given that
```
int w = 1;
int x = 6;
int y = 5;
int z = 0;
z = !z || !x && !y;
printf("%d\n", z);
z = x-- == y + 1;
printf("%d\n", z);
```
Could someone explain how the line below would evaluate to 1 if x-- is 5 and y+1 is 6?
```
z = x-- == y + 1;
```
|
The expressionx--evaluated to the value ofxbeforebeing decremented.
Sox-- == y + 1is the same as6 == 5 + 1which is true, then the value 1 is assigned toz.
|
I am a bit rusty in programming, so I came here to ask what's the meaning of this line?
```
int (*f)(int, int)
```
|
Usehttps://cdecl.org/to translate thigs like that.
int (*f)(int, int)=> declare f as pointer to function (int, int) returning int.
|
I retrieve rows via C API.
```
MYSQL_ROW row;
int i=0;
char* A[100];
while ((row = mysql_fetch_row(result))){
A[i]=row; // My Question
i++;
}
mysql_free_result(result);
mysql_close(con);
for(int i=0;i<sizeof(A);i++){
printf("%s\n",A[1]);
}
```
How can I save the entire rows in an array, independent of MySQL connection?
|
You have to duplicate the field value.
For example, duplicating only the first field:
```
#define MAX_REC 100
MYSQL_ROW row;
unsigned int i;
char* A[MAX_REC];
i = 0;
while ((i < MAX_REC) && (row = mysql_fetch_row(result))) {
// Copy first field only (Create a duplicate that must be freed later)
A[i] = row[0] ? strdup(row[0]) : "NULL";
i++;
}
```
If you need all fields, an inner loop and a 2D array is necessary.
Don't forget to free all duplicated values when no more needed!
|
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.Closed2 years ago.Improve this question
basically, I want to create a Position/location ruler which shows each numeric position starting at 1. let's say, if the characters in the above statement are 20 then in the next line 12345678901234567890 should be printed. similarly, if the characters are 30 then 123456789012345678901234567890 should be printed.
how can I do that?
|
Let's saynis the length you need to match
```
int n = 20; // or 30, or whatever
for (int i = 0; i < n; i++) printf("%d", (i + 1) % 10);
puts(""); // add newline
```
|
I can't understand why the following program outputs 5,6 instead of 6,6
```
#include<stdio.h>
int main(){
int a=5,b=6,*ptr1,*ptr2;
ptr1=&b;
ptr2=ptr1;
*++ptr2=6;
printf("%d,%d",a,b);
}
```
At firstptr2has the address ofb, then we're going to increment its value in the line*++ptr2=6;which will make it take the address ofa,so then*ptr2=6is equivalent toa=6.
|
You got the result by chance.
The address ofbis assigned toptr2viaptr1.
Scalar variables likebhere can be treated as one-element array in pointer arithmetics.
Adding one (incrementing) toptr2moves the pointer one element after the last (the only) element. Making that pointer is legal, but dereferencing that is illegal.
You invokedundefined behaviorby performing out-of-range access.
|
Sum of numbers occurring in the multiplication table of 8. What's wrong with my code? Desirable output is 440, and I'm getting 33204.
```
#include <stdio.h>
int
main ()
{
int sum, n, p;
printf ("Sum of numbers occurring in the multiplication table of 8: ");
do
{
p = 8 * n;
sum += p;
n++;
}
while (n <= 10);
printf ("%d", sum);
return 0;
}
```
|
You are using uninitialized variables
```
int sum, n, p;
```
that have indeterminate values.
As a result your program has undefined behavior.
You need to initialize them like
```
int sum = 0, n = 1, p;
```
|
Where can I get the source code for Linux and not one of its distros? And what languages do I have to learn to understand the system other than C?
|
Linux5.13(latest as of July 2021) source code is located athttps://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.13.tar.xz. You can download it and extract it with those commands:
```
wget "https://cdn.kernel.org/pub/linux/kernel/v5.x/linux-5.13.tar.xz"
tar xvf linux-5.13.tar.xz
```
Also, Linux has official Github repository attorvalds/linuxand official git server is located athttps://git.kernel.org/, can be downloaded withgit:
```
git clone "https://github.com/torvalds/linux"
```
Besides C, you should learn GNU Makefile, a bit of Assembly language, and shell scripting. Github has aLanguagessection with technologies used in project visualized:
As you can see, it's mostly C.
|
I read about int vs size_t vs ssize_t , and I understand that int and ssize_t is signed while size_t is unsigned.
Whymemcmpreturn int and no return ssize_t likerecvreturn ssize_t?
|
Anintis sufficient to hold the return value ofmemcmp.
Thememcmpfunction returns 0 if the two given memory regions are equal, a value less than 0 if the first region compares less, and a value greater than 0 if the first region compares more.
Assize_tmay be larger than anint(and on most implementations it will be), and anintis typically the "natural" word size, so there is no benefit to using the larger size.
|
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.Closed2 years ago.Improve this question
I am having trouble evaluating 8-bit unsigned binary values with the & operator.
For example: would 0b11110101 & 0b11111100 = 0b01001010.
If not, then what would be the correct binary value?
|
```
(a) 0b11110101 &
(b) 0b11111100 =
----------------
0b11110100
----------------
```
This is anANDoperation, and both inputs (a)and(b) must be logical 1
Boolean algebra basics
|
I read about int vs size_t vs ssize_t , and I understand that int and ssize_t is signed while size_t is unsigned.
Whymemcmpreturn int and no return ssize_t likerecvreturn ssize_t?
|
Anintis sufficient to hold the return value ofmemcmp.
Thememcmpfunction returns 0 if the two given memory regions are equal, a value less than 0 if the first region compares less, and a value greater than 0 if the first region compares more.
Assize_tmay be larger than anint(and on most implementations it will be), and anintis typically the "natural" word size, so there is no benefit to using the larger size.
|
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.Closed2 years ago.Improve this question
I am having trouble evaluating 8-bit unsigned binary values with the & operator.
For example: would 0b11110101 & 0b11111100 = 0b01001010.
If not, then what would be the correct binary value?
|
```
(a) 0b11110101 &
(b) 0b11111100 =
----------------
0b11110100
----------------
```
This is anANDoperation, and both inputs (a)and(b) must be logical 1
Boolean algebra basics
|
If the next representable value after-0.0is+0.0, then whynextafter(-0.0, INFINITY)does not return+0.0?
|
If the next representable value after -0.0 is +0.0 ....
False premise.-0.0and+0.0have the samevalue.if (-0.0 == +0.0)istrue.
nextafter()"functions determine the next representablevalue" (C17dr § 7.12.11.3 2)
nextafter(-0.0, INFINITY)andnextafter(+0.0, INFINITY)both returnDBL_TRUE_MIN.
+0.0and-0.0often make no functional difference. Sometimes they do make adifference.
Advanced: Be prepared for C2X with expected decimal floating point support as there are many encoding sets ofdecimal64that have the samevalue. Repeated use ofnextafter()and friends does not form a sequence through all FP encodings.
|
Would someone please explain me how having the same valueVAL1andVAL2behave differently?
For the firstifstatementVAL1is equal to zero?
Thanks!
```
#include <stdio.h>
#define VAL1 (1U << 1) | (1U << 5)
#define VAL2 0x22
int main()
{
printf("VAL1: %d\r\n", VAL1);
printf("VAL2: %d\r\n", VAL2);
if (VAL1 == 0)
{
printf("TRUE 1\r\n");
}
if (VAL2 == 0)
{
printf("TRUE 2\r\n");
}
if (VAL1 == VAL2)
{
printf("TRUE 3\r\n");
}
}
```
Output:
```
VAL1: 34
VAL2: 34
TRUE 1
TRUE 3
```
|
The numbers are both the same, but when your macro expands in you conditions, it does not behave as you expect due tooperator precedence.
In other words, here's what you get when expanded:
```
(1U << 1) | (1U << 5) == 0
// is equivalent to
(1U << 1) | ((1U << 5) == 0)
```
|
I saw this in an example Apple project calledRendering Terrain Dynamically with Argument Buffers
```
if (buffers.size() > 1)
{
assert (false);
return;
}
```
How would this behave any differently than the simplerassert(buffers.size() <= 1)?
|
In Cassertis a macro that does nothing ifNDEBUGis defined. In this case I'd guessassert(false)is inside the conditional to ensure that even ifabort()is not called (becauseassert()was a no-op due toNDEBUGor redefinition) the function returns.
|
If I put an inline function in a .h file, then include that in the bridging header, can I invoke it in Swift? (Answer: Yes) But will it still be inline when invoked in Swift?
|
The compiler will do what it wants but generally the answer isyes. This is part of why the atomics libraries and math shims that go down to C use header only inlined modules. So at least in release builds it can be fully optimized.
Seethisfor example.
|
After entering any value of p,r,n. I am getting SI=0 only. Please help
```
int main()
{
int p, n;
float r, s;
printf ("enter p,n,r \n");
scanf("%d,%d,%f", &p,&n,&r);
printf("value of s=%f",s=p*n*r/100);
return 0;
}
```
|
The commas in thescanfformat string will be used to compare the input string.
Therefore, in your program, you have to enterNumber,Number,Numbersuch as20,30,10.
Remove the commas and replace them with spaces, which represent any kinds of whitespaces including spaces and newlines.
```
scanf("%d %d %f", &p,&n,&r);
```
Refer towhitespace in the format string (scanf)
|
This question already has answers here:How do I properly compare strings in C?(11 answers)Closed2 years ago.
I am just starting to learn C coding ,I am trying to write a program that keeps scanning names and once it scans a specific name lets say for example "John" it stops Please correct me
```
#include <stdio.h>
int main()
{
char name[20];
printf("enter a name:");
for(;;)
{
scanf("%s",name);
if (name='John')
{
break;
}
}
```
|
You can't compare two string pointers with!=or==.
you need to use strcmp, for example:
```
while (strcmp(check,input) != 0)
```
strcmp compares the string pointed to, by str1 to the string pointed to by str2.
|
Using clang or clang++ the command ofclang -S -emit-llvm ./source.cwill create a llvm ir document. However debugging information is missing. So when you test and compile things you lose debugging information.
How does one can make clang emit human readable llvm ir document with debug information ?
|
The standard option to add debug info is-g. So, runningclang -g -S -emit-llvm source.cwill emit necessary information
|
I read this 16-bit value from a temperature sensor (type MCP9808)
Ignoring the first three MSBs, what's an easy way to convert the other bits to a float?
I managed to convert the values 2^7 through 2^0 to an integer with some bit-shifting:
```
uint16_t rawBits = readSensor();
int16_t value = (rawBits << 3) / 128;
```
However I can't think of an easy way to also include the bits with an exponent smaller than 0, except for manually checking if they're set and then adding 1/2, 1/4, 1/8 and 1/16 to the result respectively.
|
Something like this seems pretty reasonable. Take the number portion, divide by 16, and fix the sign.
```
float tempSensor(uint16_t value) {
bool negative = (value & 0x1000);
return (negative ? -1 : 1) * (value & 0x0FFF) / 16.0f;
}
```
|
After entering any value of p,r,n. I am getting SI=0 only. Please help
```
int main()
{
int p, n;
float r, s;
printf ("enter p,n,r \n");
scanf("%d,%d,%f", &p,&n,&r);
printf("value of s=%f",s=p*n*r/100);
return 0;
}
```
|
The commas in thescanfformat string will be used to compare the input string.
Therefore, in your program, you have to enterNumber,Number,Numbersuch as20,30,10.
Remove the commas and replace them with spaces, which represent any kinds of whitespaces including spaces and newlines.
```
scanf("%d %d %f", &p,&n,&r);
```
Refer towhitespace in the format string (scanf)
|
This question already has answers here:How do I properly compare strings in C?(11 answers)Closed2 years ago.
I am just starting to learn C coding ,I am trying to write a program that keeps scanning names and once it scans a specific name lets say for example "John" it stops Please correct me
```
#include <stdio.h>
int main()
{
char name[20];
printf("enter a name:");
for(;;)
{
scanf("%s",name);
if (name='John')
{
break;
}
}
```
|
You can't compare two string pointers with!=or==.
you need to use strcmp, for example:
```
while (strcmp(check,input) != 0)
```
strcmp compares the string pointed to, by str1 to the string pointed to by str2.
|
Using clang or clang++ the command ofclang -S -emit-llvm ./source.cwill create a llvm ir document. However debugging information is missing. So when you test and compile things you lose debugging information.
How does one can make clang emit human readable llvm ir document with debug information ?
|
The standard option to add debug info is-g. So, runningclang -g -S -emit-llvm source.cwill emit necessary information
|
I read this 16-bit value from a temperature sensor (type MCP9808)
Ignoring the first three MSBs, what's an easy way to convert the other bits to a float?
I managed to convert the values 2^7 through 2^0 to an integer with some bit-shifting:
```
uint16_t rawBits = readSensor();
int16_t value = (rawBits << 3) / 128;
```
However I can't think of an easy way to also include the bits with an exponent smaller than 0, except for manually checking if they're set and then adding 1/2, 1/4, 1/8 and 1/16 to the result respectively.
|
Something like this seems pretty reasonable. Take the number portion, divide by 16, and fix the sign.
```
float tempSensor(uint16_t value) {
bool negative = (value & 0x1000);
return (negative ? -1 : 1) * (value & 0x0FFF) / 16.0f;
}
```
|
Imagine I havefile1.c,file2.c. First I compile one file withgcc -c file1.c -o file1.o. Is it OK to compile them together withgcc file1.o file2.c -o prog? I tried it and no errors are shown, but should I compilefile2.ofirst? Is it correct to mix.cand.ofiles?
|
Yes, you can dogcc file1.o file2.c -o prog. You can also dogcc file1.c file2.c -o prog.
GCC will handle compiling file2.c behind the scenes.
|
How can I send back the value inside a void function to the main function if the condition restricts me from using the non-void function to return those values?
here's my example code:
```
void calcTotalPaid(float total){
float totalPaid=0;
totalPaid += total;
}
```
|
You should pass a pointer to a variable that will receive the result and use that.
```
#include <stdio.h>
void calcTotalPaid(float* res, float total){
float totalPaid=0;
totalPaid = totalPaid + total;
*res = totalPaid;
}
int main(void) {
float value = 0;
calcTotalPaid(&value, 3.14);
printf("%f\n", value);
return 0;
}
```
|
I'm trying to work out how to define my own window properties in xcb/x11, in order to be able to associate additional data with a window.
I can set and retrieve the pre-defined properties, such as XCB_ATOM_WM_NAME, using xcb_change_property() and xcb_get_property(), just fine, but can't figure out how to define new properties of my own.
A number of tutorials allude to this being possible, and indeed integral to the design, but nowhere can I find any guidance on how to go about it.
|
I don't know about xcb but in X you can create an Atom (Property) with
XInternAtom
The XInternAtom function returns the atom identifier associated with the specified atom_name string. If only_if_exists is False, the atom is created if it does not exist.
and modify/retrieve it by
XChangePropertyXGetWindowProperty
xcb should provide something similar.
|
If I declare a function parameter as myfunc(char (*p) [10]) what is the
correct syntax for returning said pointer p ?
```
char *myfunc(char (*p) [10]) {
/* do something */
return (*p);
}
```
compiles and appears to work but it doesn't look correct (i.e., it doesn't
seem to suggest that the pointer returned necessarily is a pointer to an
array of size 10).
|
char xdeclares a character.
char x[10]declares an array of ten characters.
char (*x)[10]declares a pointer to an array of ten characters.
char (*x())[10]declares a function that returns a pointer to an array of ten characters.
char (*x(char (*p)[10]))[10]declares a function that takes a pointer to an array of ten characters and returns a pointer to an array of ten characters.
|
I'm getting the following error message from Clang 10:
```
error: expected value in expression
#if FOOBAR
^
1 error generated.
```
No further info. What could be the cause for this?
|
What could be the cause for this?
When the macro is defined to nothing
```
#define FOOBAR
```
then
```
#if FOOBAR
```
expands to just:
```
#if
```
And compiler prints an error -ifneeds an expression#if something-here.
|
What does the following declaration mean?
```
char *(*g(char a, int b))
```
So far, I know that,
```
char *(*g)(char, int)
```
declares a pointer to a function that returns achar *, and I can successfully assign a value to it, however I can't do the same with the first. Any hints?
|
It looks like a functiongthat takes two arguments (char aandint b) and returnschar**.
The outer parenthesis looks working like ones inchar** x = /* some value */; char y = *(*x);
As a proof, this code compiles:
```
char *(*g(char a, int b));
char** test(void) {
return g(0, 0);
}
```
|
```
#include <stdio.h>
#include <string.h>
int main()
{
char string[100];
printf("Input string: ");
fgets(string, sizeof(string), stdin);
printf("%ld\n", strlen(string));
return 0;
}
```
To my knowledge strlen() returns the length of a string excluding the \0 but when i input "hello" it returns a value of 6
|
Print the string as hexadecimal and you will see that the new line character\nor0x0Ais included:
```
size_t i = 0;
for (; string[i] != 0; i++) {
printf("string[%zu] = %02X\n", i, (unsigned char)string[i]);
}
```
Output:
```
Input string: hello
6
string[0] = 68
string[1] = 65
string[2] = 6C
string[3] = 6C
string[4] = 6F
string[5] = 0A
```
EDIT: Fixed code for not handling correctlysigned chartointpromotion and removed unnecessarystrlenfrom loop as very well recommended by @phuclv.
|
How do Ig_printaGValue, if I don't know it's type at compile time?
Is there some kind of special format character for theg_printformat string?
|
Depends what format you want to print it in. If you don’t really care about the format, you can useg_value_transform()to convert the value into a secondGValuewhich has been initialised with typeG_TYPE_STRING.
If you do care about the format, you will need to have a multi-branchifstatement which compares the value ofG_VALUE_TYPE()for yourGValueagainst many differentGTypes. In the body of eachifblock you’d have type-specific printing code.
|
This question already has answers here:With arrays, why is it the case that a[5] == 5[a]?(20 answers)Closed2 years ago.
Why is the following program print -7 instead of throwing syntax error?Code:
```
#include <stdio.h>
int main (int argc , char **argv)
{
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int *b = arr + 6;
printf("%d\n", -1[b]);
return 0;
}
```
|
Because the index operatora[b]is just syntactic sugar, that literally translates into*(a+b)thus invoking pointer arithmetic which is commutative on its arguments. Hence it's perfectly allowed to swap the "inside" and the "outside" of…[…].
|
```
for (int i = 0; i < num - 1 - ct; i++) {
int tmp = k;
fread(&k, sizeof(int), 1, fp);
fflush(stdin);
fseek(fp, -(sizeof(int)), SEEK_CUR);
fwrite(&tmp, sizeof(int), 1, fp);
}
```
The question part is above.
I wantfseekto roll back 4 bytes every time. But it rolls back 8 bytes or maybe roll back to the beginning of the file. I can't make it work right. A freshman. Thanks in advance.
|
The problem is you do not usefseek()to sync the stream's internal data when switching from writing to reading from the same stream.
Try this:
```
fseek(fp, 0, SEEK_CUR);
for (int i = 0; i < num - 1 - ct; i++) {
int tmp = k;
fread(&k, sizeof(int), 1, fp);
//fflush(stdin); // this has undefined behavior
fseek(fp, -(sizeof(int)), SEEK_CUR);
fwrite(&tmp, sizeof(int), 1, fp);
fseek(fp, 0, SEEK_CUR);
}
```
|
Please help me fix my confusion:
In Elf64 File at first we the elf header, then immediately all program header and then all section headers?
Then why for example in elf header we have a index to where the first program header starts if it's always 64 bytes after the start of the file, that seems to be extra garbage information?
|
If nothing else, it allows the header's size to be made larger in future versions of the format without losing backwards compatibility.
In Elf64 File at first we the elf header, then immediately all program header and then all section headers?
No, the program header, the section headers and the sections are wherever the headers say they are. There's no requirement for them to be immediately after one another or in any particular order.
|
The following compiles:
```
main()
{
int(asdf);
}
```
It seems this is some strange kind of declaration. I have tried to find code like this, but was unable to. Could someone explain?
|
It turns out the line
```
int(asdf);
```
is equivalent to
```
int asdf;
```
which obviously declares an ordinary local variable namedasdf.
But you can put parentheses around various parts of the declarator, whether you need to or not. So it's just the same if you write
```
int asdf;
```
or
```
int (asdf);
```
or
```
int ((asdf));
```
Parentheses are allowed in declarators because, sometimes, they're necessary in order to make a significant distinction. For example,
```
int *ap[10];
```
declares an array of 10 pointers, while
```
int (*pa)[10];
```
declares a pointer to an array.
|
I need to read data like "01", but skip data like just "1".
I triedfscanf(f, "%2lu ", &ulong), but seems that 2 is max length, not fixed.
Yes, i know that i can do it with symbols like %c%c, but it's will be harder for reading code.
What should i do?
|
Use"%n"conversion specifier
```
#include <stdio.h>
int main(void) {
long n;
int m1, m2;
if (sscanf(" 123\n", " %n%ld%n", &m1, &n, &m2) != 1) puts("scanf error");
if (m2 - m1 != 2) puts("error with 123");
if (sscanf(" 12\n", " %n%ld%n", &m1, &n, &m2) != 1) puts("scanf error");
if (m2 - m1 != 2) puts("error with 12");
if (sscanf(" 1\n", " %n%ld%n", &m1, &n, &m2) != 1) puts("scanf error");
if (m2 - m1 != 2) puts("error with 1");
return 0;
}
```
Better yet: never usescanf()for user input.
|
I would like to see line number in the console when it asks for input.
Something like:
```
1 foo
2 bar
3 baz
```
Here 1 was shown in the prompt and I enter any input and hit enter
Then the next number shows up and I do the same.
Any simple help for this in C for a beginner?
|
This will might help you.
```
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int main() {
int lineNo = 0;
char name[256];
do {
printf("%d ", ++lineNo);
scanf("%s", name);
} while (strlen(name) > 0);
return 0;
}
```
|
I know this code returns an error but is there anyway to input a string with %c format specifierwithout the use of any loops?
```
char string[100];
scanf("%c",&string);
```
|
Yes. You can specify the number of characters to read with%cformat specifier, so you can use that in a special case in which the length of the string to read is already known.
Also note that%cformat specifyer doesn't put a terminating null-character, so you have to be careful not to forget to add that.
```
#include <stdio.h>
int main(void) {
char string[100] = ""; /* initialize to put a terminating null-character */
if (scanf("%10c", string) == 1) { /* read a 10-character string */
puts(string);
} else {
fputs("read error\n", stderr);
}
return 0;
}
```
|
if I write data to the middle of the allocated address space, will the file size increase. just likefseekdoes ?
or it will write to the beginning of the file ?
|
The answer is no. writeto mmap will not grow the file or create sparse file.
I have to allocate the file manually.
|
Is it ok if we ignore part of input string tosscanffunction.
In the below code , I am interested only indayandyear, so I don't collect theweekdayandmonthinto variables.
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
int day, year;
char weekday[20], month[20], dtm[100];
strcpy( dtm, "Saturday March 25 1989" );
if(sscanf( dtm, "Saturday March %d %d", &day, &year ) == 2)
printf("%d, %d \n", day, year );
else
printf("error");
return 0;
}
```
|
Yes, it is fine.
Also you can ignore general strings by adding*to the format specifier like
```
if(sscanf( dtm, "%*s%*s%d%d", &day, &year ) == 2)
```
|
Why in this code the integer array is able to hold floating point numbers and characters, I mean what is the real working of sprintf, what is it(sprintf) actually doing?
```
#include <stdio.h>
//Compiler version gcc 6.3.0
int main()
{
int arr[20];
int y=10;
char c='A';
float k=13.4;
sprintf(arr,"%d %c %.1f",y,c,k);
printf("%s",arr);
return 0;
}
```
|
Whatsprintfsee ofarris simply a memory address, and it starts writing byte after byte there. Thenprintftakes the same address, assumes the bytes there are intended as a zero-terminated string and start printing it with that assumption.
It's NOT a good idea to do like this.
If you really want to study this, have a look at this source:
https://code.woboq.org/userspace/glibc/stdio-common/sprintf.c.html
https://code.woboq.org/userspace/glibc/libio/iovsprintf.c.html#__vsprintf_internal
|
Let's say we have this code:
```
main
some code...
fork()
fork()
some code
```
The question is:
How many threads are running?
Thank you !
|
Thanks to the help of Jeremy I figured out the answer and want to share it with you.
In general if we have a fork() a child is created. Unless we have a different code for the child the child runs the code of the parent (aka the code under fork() ).
So in this example the 1st fork will create a new process as it will run the second fork.
So we have 1 thread for the parent. 1 second thread for the child1 from fork1. 1 third thread from the child1 due to fork2. And finally a thread from the child2.
So in total there are 4 threads.
|
```
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(void)
{
int i;
double interval;
for(i=0;i<30;i++)
{
interval = i/10.0;
printf("sin(%lf) = %lf \t", interval, abs(sin(interval)));
};
printf("\n+++++++++\n");
return 0;
}
```
the sin value of each interval term is coming out to be 0.000000. example sin(0.60000) = 0.000000
|
Theabsfunction is anintegerfunction. Which means you haveundefined behaviorsince you use the mismatching format specifier%lf.
For floating point you need to usefabs.
|
This will print alternately "0" and "1":
```
while(1){
printf("%d", 0);
sleep(1);
printf("%d", 1);
sleep(1);
}
```
To reduce the calls toprintf()down to only 1 time for each loop, I use XOR:
```
int toggle = 0;
while(1){
printf("%d", toggle^=1);
sleep(1);
}
```
I would like to know if there are any other ways to print alternately between 0 and 1 (means toggling the output) with only 1 call toprintf()(or any other C standard functions) for each loop. And can this achievable without using any variable?
(user-defined function may not be used)
|
2 easy options at least:
```
toggle= !toggle;
toggle = 1 - toggle;
```
and for fun and games that you might not know
```
toggle = !!!toggle;
toggle = !!!!!!!!!!!!!!!!!!!!!toggle;
```
|
I am learning how to use pointers in C and I am having trouble with this little program. In main, I want to get the value in the parameter.
```
int testing(int *number) {
int num = 12;
number = #
return 0;
}
int main() {
int num;
testing(&num);
printf("The number is: %d", num);
return 0;
}
```
Essentially, I want to print the num pointer after it goes through the testing function. Therefore, I want num to be 12. Currently, when I print num, it is a random number. Any ideas? Thanks.
|
number = #is changing the local parameter (copy of what is passed). This means nothing becausenumberis not used after that.
Instead of that, you should dereference the passed pointer to write the integer there:*number = num;
|
I am looking for help with writing a C macro that expands into char* macro in one place and wchar_t* macro in another place.
Eg:
```
#define MACRO_STRING "Macro String"
```
to atomic section with function calls:
```
{
function1(L"Macro String");
function2("Macro String");
}
```
function1always accepts wide characterswchar_t *, whilefunction2always acceptschar *.
In most places in my code I am callingfunction1immediately followed byfunction2. Throughout my code, the string "Macro String" is a constant. But one function takes input aswchar*while the other takes input aschar*.
Need help in expanding the macro differently in the two functions
|
A quick and easy solution, with no extra macros:
UseMACRO_STRINGdirectly when you needchar *.UseL"" MACRO_STRINGwhen you needwchar_t *.
|
I need to separate the decimal part of afloatfrom the integer part. In C, I can usemodfto achieve this. When I try to use the same function in Metal Shading Language, it returns the following error:
No matching function for call to 'modf'Fix in metal_math
Pressing "Fix in metal_math" only causes more issues in the metal_math file. Is there some way that I can usemodfor an alternate method to get just the decimal part in Metal Shading Language. Here is my code so far in Metal Shading Language.
```
float f = <some float of undetermined precision>;
float decimal;
modf(f, &decimal);
```
|
You should pass your value by reference, not by address.
Replace your code with this:
```
modf(f, decimal);
```
|
May I have a question about my error during valgrind check?
I don't know how to fix this error below:
at 0x4C2E2B1: __strcmp_sse42 (vg_replace_strmem.c:852)
|
This occurs when the string doesn't aNULLterminated string. In this case, the value"-all"orargv[1]maybe doesn't aNULLterminated string, therefore thestrlenwill return an indeterminate value, becausestrcmpgoes past the end of the strings and past the memory you allocated for them.
Try add\0in the end of the string before thestrcmp.
|
If I start with xmlSchemaNewParserCtxt() the parser is fine and finds all referenced schemas, but I wonder if I can somehow tell it where the schemas are if I use xmlSchemaNewMemParserCtxt().
The thing is, If I already have downloaded XSD in memory can I pass the document URL to the parser so it finds related stuff?
a)
```
char *urlPath = "http://docs.oasis-open.org/ubl/os-UBL-2.1/xsd/maindoc/UBL-Invoice-2.1.xsd";
xmlSchemaNewParserCtxt (urlPath);
```
b)
```
xmlSchemaNewMemParserCtxt (schemaBuffer, buffSize);
```
Variant a) works fine, variant b) produces errorI/O warning : failed to load external entity "../common/UBL-CommonAggregateComponents-2.1.xsd"
Schemas are located here:http://docs.oasis-open.org/ubl/os-UBL-2.1/xsd
|
The best solution is probably to use XML catalogs, but you can also control loading of sub-resources withxmlRegisterInputCallbacksorxmlSetExternalEntityLoader.
|
I'm struggling with the demo code like below:
```
typedef volatile union
{
unsigned U;
int I;
struct
{
unsigned some_array:32;
} B;
} bar;
#define foo (*( bar*) 0xABCDU)
```
I know that0xABCDUis some address in memory.
How can I read thefooin English?
|
( bar*) 0xABCDUis0xABCDUreinterpreted as a pointer tobar.*( bar*) 0xABCDUis dereferenced pointer (a reference if it was C++).
(Outer braces are to prevent it from possible misinterpretation due to operators precedence)
|
I have been developing a library in C that usesfopento open and read files. In some cases, a file path beginning withfile://is passed in (such asfile:///Users/<username>/Desktop/doc.txt), and even though it is a valid file on the machine,fopenfails to open the file.
Is there another function I should be using other thanfopen? And if not, how should I edit the file path so it opens correctly?
(To be clear, the same path passed in withoutfile://opens fine)
|
You just need to check if the path starts with "file://", and if so pass in the string starting from the next character.
```
const char *prefix = "file://";
if (!strncmp(filename, prefix, strlen(prefix))) {
fp = fopen(filename + strlen(prefix), "r");
} else {
fp = fopen(filename, "r");
}
```
|
I'm trying to figure out the behavior offor(i = 0; i < rand(); ++i)where I'm not sure if the second expression is supposed to generate a new random number each time the loop iterate or just when it executes for the first time.
Tried to find out by comparing the program execution times but no luck as there were no big differences between them.
Does the random number generates once or each time the loop iterate?
|
i < rand()is evaluated each time round the loop, sorand()will be called each time round the loop.
The way to prove this to yourself would be to replace the call torandwith a call to a function that printed out some 'I have been called' information each time it is invoked.
|
If we allocate memory on the stack like so:
```
void foobar()
{
int arr[10];
}
```
Afterfoobar()exits, the reference to this memory block (arr) is lost. But is it zeroed out?
|
But is it set to zero?
No / maybe. There are no guarantees about the "value" of unallocated memory. Nor is there any way guaranteed by the standard to observe that hypothetical "value".
From an information security perspective: If you store private information in an object, then you should assume that the information may persist even after the storage duration of the object. And that an attacker may be able to access that information if your program is vulnerable to an exploit (typically, through undefined behaviour).
|
I've opened aFILE *fwithfdopen(fd, "w+")and I would like to keep thefdopen after closing withfclose(f).
Is there an elegant way to do that?
Can I simply callfflush(f); free(f);or is that dangerous?
Or is there a way to change the internalfdto an invalid value-1so thatfdcannot be closed byfclose()?
|
If you want to get the file descriptor and disassociate it from the theFILE*, there is one supported way:
Get the file descriptor withfileno(). (POSIX)Duplicate it usingdup(). (POSIX)Close theFILEthe normal way withfclose(). (c)
Now you only have a file descriptor.
|
I've opened aFILE *fwithfdopen(fd, "w+")and I would like to keep thefdopen after closing withfclose(f).
Is there an elegant way to do that?
Can I simply callfflush(f); free(f);or is that dangerous?
Or is there a way to change the internalfdto an invalid value-1so thatfdcannot be closed byfclose()?
|
If you want to get the file descriptor and disassociate it from the theFILE*, there is one supported way:
Get the file descriptor withfileno(). (POSIX)Duplicate it usingdup(). (POSIX)Close theFILEthe normal way withfclose(). (c)
Now you only have a file descriptor.
|
```
int main() {
char a[5];
a[0] = 0;
return a[0];
}
```
In this snippet, doeschar a[5];, which is an array declaration without any initialization, guarantee allocation of 5 bytes of consecutive memory?
Or since only 1 element gets initialized later, compiler is free to use a register for that 1 element?
I'm assuming that reading any other index of this array beside0is undefined behaviour.
|
It guarantees that the observable behaviour of the program will be the same as if it has allocated this memory.
The compiler is free to optimize out any objects as in your trivial example:
```
main:
xor eax, eax
ret
```
https://godbolt.org/z/KE5PzvTKq
|
I encountered something weird while trying C read function. I know file descriptor 0 means standard input. So I decided to take input with read function like below
```
#include<unistd.h>
int main(){
char buf[1];
read(0,buf,1);
return 0;
}
```
I compiled that main.c file with gcc
```
$ gcc -o main main.c
```
then I executedmainbinary and then entered input 'tls'. Characters after 't' are interpreted by the shell and output was like the following
```
$ ./main
tls
$ ls
main main.c
```
Why the shell directly interprets overflown input characters?
|
Nothing is overflowed. Your program reads one character from stdin and then exits. Any characters after that are read by the shell.
|
I was trying to code and ran into a problem.
FILE *tickets = fopen("tickets.h", "w");- so here I open a file source where in the future I want to append some text to the end of the file. So the problem is that I don't want the file content to be removed and want to append text to the end of the file. I've chosen write permissions because in the future the program will be writing doing stuff with the write and not the append perms.
Help will be appreciated!
|
You should useFILE *tickets = fopen("tickets.h", "a");
Because when you open a file in the write mode, the file is overwritten, resulting in deletion of any data already present in the file. But in append mode this will not happen. Append mode is used to append or add data to the existing data of file(if any).
|
newbie here,
hi,basically im trying to input 10 integers in file, entering less than 9 numbers are correcly written but if im trying to input more than 9 numbers, the contents of the file are random sometimes with negative in the beginning.
what am i missing?
this is the code;
```
int main()
{
int num;
int value;
FILE *test_file;
test_file = fopen(".\\testfile.txt", "w+");
if (test_file == NULL)
{
printf("ERROR!\n");
return 1;
}
printf("Enter a number to be written on the text file: ");
scanf("%d", &num);
fprintf(test_file, "% d", num);
fclose(test_file);
}
```
|
The limit of intINT_MAXis defined as2147483647. If you go above that, the numberwillbecome negative. To avoid this problem, uselong longorunsigned long long.unsigned long longcan go up to18446744073709551615(extremely large).
|
I am starting out C programming and I could not find the answer to this anywhere.
When I run a ".c" file from my C project's folder, it only runs the "main.c" file, ignoring any other ".c" source files within the project's folder. So, am I correct in understanding that I can only have one source file per project, that's being run while all the others are files that are only called (i.e. #included) by that primary source file, "main.c"? (Similar to libraries/modules in Python)
FYI, I am usingCLion, if this makes any difference.
Thanks for the help.
|
CLion uses CMake, you'll find a CMakeLists.txt file in your project. Any additional source files should be added (manually) to the commandadd_executable(main main.c other_source.c yet_another_source.c). Notice these are space separated. You can have as many source files as you want!
|
i have tried to make a program to check the pallindrome manually on paper it should work
but it doesnt.
i have attached the output with the code
```
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdlib.h>
void main()
{
char str[100];
int i,l,k;
printf("type the desired to string to check pallindrome\n");
gets(str);
l=strlen(str);
printf("%d\n", l);
k=l-1;
char temp[100];
for(i=0;i<l;i++)
{
temp[k]=str[i];
--k;
}
if(strcmp(temp, str)==0)
{
printf("pallindrome\n");
}
else
{
printf("not a pallindrome\n");
}
}
```
here is the output
[1]: https://i.stack.imgur.com/dERFQ.png
|
You need to append the NUL terminator at the end oftempright after theforloop:
```
for(i=0;i<l;i++)
{
temp[k]=str[i];
--k;
}
temp[i] = '\0';
```
Otherwise, thestrcmpfunction will causeUB.
|
I am using code blocks with gcc compiler when I encountered this problem ...
error: conflicting types for func32();
I tried changing name of the function. but still don't work
```
static void func32(int, int);
void main()
{
int a = 4, b = 5, c = 6;
func31(a, b);
func32(&b, &c);
printf("The Result Will Be: %d\n", c - a - b);
}
static void func32(int *a, int *b)
{
int c;
c = *a;
*a = *b;
*b = c;
}
```
|
Your declaration offunc32says that it takes two integers (int).
```
static void func32(int, int);
```
On the other hands, your definition offunc32says that it takes two pointers (int*).
```
static void func32(int *a, int *b)
```
Here is the confrict. The declaration and definition should use the same signature. In this case the arguments should be pointers.
|
I knowkbhit"Determines if a keyboard key was pressed" but I see that people use both_kbhitandkbhitinterchangeably.
|
According tothis page on MSDN-kbhitis deprecated
The Microsoft-specific function name kbhit is a deprecated alias for the _kbhit function. By default, it generates Compiler warning (level 3) C4996. The name is deprecated because it doesn't follow the Standard C rules for implementation-specific names. However, the function is still supported.
We recommend you use _kbhit instead. Or, you can continue to use this function name, and disable the warning. For more information, see Turn off the warning and POSIX function names.
|
i have tried to make a program to check the pallindrome manually on paper it should work
but it doesnt.
i have attached the output with the code
```
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdlib.h>
void main()
{
char str[100];
int i,l,k;
printf("type the desired to string to check pallindrome\n");
gets(str);
l=strlen(str);
printf("%d\n", l);
k=l-1;
char temp[100];
for(i=0;i<l;i++)
{
temp[k]=str[i];
--k;
}
if(strcmp(temp, str)==0)
{
printf("pallindrome\n");
}
else
{
printf("not a pallindrome\n");
}
}
```
here is the output
[1]: https://i.stack.imgur.com/dERFQ.png
|
You need to append the NUL terminator at the end oftempright after theforloop:
```
for(i=0;i<l;i++)
{
temp[k]=str[i];
--k;
}
temp[i] = '\0';
```
Otherwise, thestrcmpfunction will causeUB.
|
I am using code blocks with gcc compiler when I encountered this problem ...
error: conflicting types for func32();
I tried changing name of the function. but still don't work
```
static void func32(int, int);
void main()
{
int a = 4, b = 5, c = 6;
func31(a, b);
func32(&b, &c);
printf("The Result Will Be: %d\n", c - a - b);
}
static void func32(int *a, int *b)
{
int c;
c = *a;
*a = *b;
*b = c;
}
```
|
Your declaration offunc32says that it takes two integers (int).
```
static void func32(int, int);
```
On the other hands, your definition offunc32says that it takes two pointers (int*).
```
static void func32(int *a, int *b)
```
Here is the confrict. The declaration and definition should use the same signature. In this case the arguments should be pointers.
|
I knowkbhit"Determines if a keyboard key was pressed" but I see that people use both_kbhitandkbhitinterchangeably.
|
According tothis page on MSDN-kbhitis deprecated
The Microsoft-specific function name kbhit is a deprecated alias for the _kbhit function. By default, it generates Compiler warning (level 3) C4996. The name is deprecated because it doesn't follow the Standard C rules for implementation-specific names. However, the function is still supported.
We recommend you use _kbhit instead. Or, you can continue to use this function name, and disable the warning. For more information, see Turn off the warning and POSIX function names.
|
I want to make this division in C
```
#include <stdio.h>
void main() {
float result;
int val;
val = 7;
result = 1/(1 >> val);
}
```
but i get -2147483648 as result instead of 128.
How to obtain the right result from this division?
|
(1 >> val)shifts1"down" (towards the least significant bit)val(7) steps.
To get128, you want to shift it "up" (towards the most significant bit)valsteps.
```
result = 1 / (1 << val);
```
Now you've got1 / 128... which is0. Why? Because they are both integers. It doesn't matter thatresultis afloat. To promote the division to a division of twofloats, you need to make either operand afloat. The other operand will then implicitly be converted to afloattoo.
```
result = 1.f / (1 << val);
```
resultnow becomes approximately0.007812.
|
I am trying to use the <Python.h> header file but I cannot get it to be found. I am using ubuntu 20.04. I have seen many similar questions on stack overflow but none solve my problem. I have tried doing:
```
sudo apt-get install python3.9-dev
```
but this does not resolve my problem. I can also do Windows but #include <Python.h> produced the same error on Windows and I couldn't resolve it there so I moved to ubuntu. I am using Python3.9. Please can I have some suggestions as to what could be the problem?
|
It's not clear exactly what the context is, but you may just need to do:
```
sudo apt-get install libpython3.9-dev
```
If that doesn't work, do something like:
```
CPPFLAGS="${CPPFLAGS} -I $(dirname $(dpkg -L libpython3.9-dev | grep Python.h))"
```
And make sure you compile with the appropriate flags. That is, if you are building withgcc, use:
gcc $CPPFLAGS ...
|
I was trying to understand the iphdr struct and I don't understand what src and dest represent. For instance I have a packet sniffer that takes the packet and passes it into an iphdr struct. Running netcat withnc 127.0.0.1 7999andnc -l 127.0.0.1 7999I get the result 16777343 for the src and dest. Am I forgetting a conversion or something?
|
1 * 256 * 256 * 256 + 127is 16777343.I think that demonstrates the needed conversion nicely.It is close to the hexadecimal representation, just that each bytes value is then shown in decimal.
|
In my rooted Android device,
```
jint fd = open("/dev/ashmem",O_RDWR);
```
gives -1 and fopen results in error 13. I've tried changing the permissions as well with chmod 777, but to no avail.
Any ideas? Thank you for your help.
|
Apps targeting Android 10 cannot directly use ashmem (/dev/ashmem) and must instead access shared memory via the NDK’s ASharedMemory class
|
I am trying to use the <Python.h> header file but I cannot get it to be found. I am using ubuntu 20.04. I have seen many similar questions on stack overflow but none solve my problem. I have tried doing:
```
sudo apt-get install python3.9-dev
```
but this does not resolve my problem. I can also do Windows but #include <Python.h> produced the same error on Windows and I couldn't resolve it there so I moved to ubuntu. I am using Python3.9. Please can I have some suggestions as to what could be the problem?
|
It's not clear exactly what the context is, but you may just need to do:
```
sudo apt-get install libpython3.9-dev
```
If that doesn't work, do something like:
```
CPPFLAGS="${CPPFLAGS} -I $(dirname $(dpkg -L libpython3.9-dev | grep Python.h))"
```
And make sure you compile with the appropriate flags. That is, if you are building withgcc, use:
gcc $CPPFLAGS ...
|
I was trying to understand the iphdr struct and I don't understand what src and dest represent. For instance I have a packet sniffer that takes the packet and passes it into an iphdr struct. Running netcat withnc 127.0.0.1 7999andnc -l 127.0.0.1 7999I get the result 16777343 for the src and dest. Am I forgetting a conversion or something?
|
1 * 256 * 256 * 256 + 127is 16777343.I think that demonstrates the needed conversion nicely.It is close to the hexadecimal representation, just that each bytes value is then shown in decimal.
|
In my rooted Android device,
```
jint fd = open("/dev/ashmem",O_RDWR);
```
gives -1 and fopen results in error 13. I've tried changing the permissions as well with chmod 777, but to no avail.
Any ideas? Thank you for your help.
|
Apps targeting Android 10 cannot directly use ashmem (/dev/ashmem) and must instead access shared memory via the NDK’s ASharedMemory class
|
How can we use the functionstrchrto find absolute path in linux, for example:
```
Input: /home/test/sample
Output: /home/test
```
I try to write something like this:
```
int main() {
char* string = "/home/test/sample";
char* pos;
pos = strchr(string, '/');
printf("%s\n", pos);
return 0;
}
```
But that's not working, I got the same output as the input:
```
Input: /home/test/sample
Output: /home/test/sample
```
|
Use thedirnamefunction instead:
```
#include <libgen.h>
#include <stdio.h>
#include <string.h>
int main()
{
char* string = strdup ("/home/test/sample");
char* pos;
pos = dirname (string);
printf ("%s\n", pos);
return 0;
}
```
In order to search for the right most occurrence use thestrrchrfunction.
|
Here is an example from a ST CMSIS header:
```
#define USART_ISR_TC_Pos (6U)
#define USART_ISR_TC_Msk (0x1UL << USART_ISR_TC_Pos)
```
Everywhere in CMSIS headers, the bitfield positions (_Pos) are given as decimal integer constants of typeunsigned intand the unshifted masks areunsigned long int.
Why is it that they both are not specified asunsigned long int?
|
Bit position: Position in the register cannot be more than 31 andanyinteger type in C can hold it. There is no reason even to make the position unsigned.Themask. As the minimumunsigned intsize required by the C standard is not big enough to hold 32 bit value, It has to be declared as unsigned long. CMSIS authors do not know the compiler you are going to use so they use theminimalsufficient type.
|
I am trying to read a gz file into a char buffer which should resize depending on how big the file is.
```
gzFile infile = gzopen(infile_name, "rb");
char *buf = malloc(256);
int total_read = 0;
int incr_read = 0;
do {
incr_read = gzread(infile + total_read, buf, 256);
total_read += incr_read;
buf = realloc(buf, total_read + 256);
} while (incr_read > 0);
```
This stops immediately for some reason, only reading the first 256 bytes. There is no way it reached the end of the file, because it is 1.3 kB in size (compressed). How could I continue reading the rest of the file?
I am relatively new to C so there is likely something obvious I overlooked, but I have not been able to find a solution elsewhere.
|
The first parameter togzread()should be agzFilehandle but you passinfile + total_readfor some reason instead of justinfile.
|
This question already has answers here:When an int is cast to a short and truncated, how is the new value determined?(6 answers)Closed2 years ago.
Here's the scenrio -
```
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main()
{
uint8_t backoff;
char* value = "300000";
backoff=atoi(value);
printf("value = %s\n", value);
printf("backoff value = %d\n", backoff);
return (0);
}
```
Output is as -
```
value = 300000
backoff value = 224
```
Can someone please help me understand how this conversion happened ?
|
Pretty simple. Values of uint8_t are 0 to 255. You need at least uint32_t (uint16_t max 65535). 224 is the bits of the real answer that fit in the 8 bit int.
|
I have a problem when comparing wchar_t with hex value.
```
wchar_t c;
FILE *f = fopen("input1.txt", "r");
fwscanf(f, L"%lc", &c); // c is 'ệ'
printf("%d", c == L'\0x1ec7');
```
'ệ' is 0x1ec7 hex. But the result is 0. And how to compare wchar_t with hex value?
|
The correct notation isL'\x1ec7', notL'\0x1ec7':
```
#include <stdio.h>
int main() {
wchar_t const c = L'ệ';
printf("%d", c == L'\x1ec7'); // prints 1
}
```
|
my code is belowhow to avoid the blank line printed before the required output?
the question is to print the batsman with maximum runs.
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,runs,maxRuns=0;
char bat[100],maxBat[100];
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%[^,],%d",&bat,&runs);
if(runs>maxRuns){
maxRuns=runs;
strcpy(maxBat,bat);
}
}
printf("%s",maxBat);
}
```
the output i'm getting is
|
Try the following
```
scanf( " %[^,],%d", bat, &runs );
```
See the blank before the first conversion specifier,
Also instead of&batusebatbecause the type of the expression&bat(char( * )[100]) is notchar *as it is required by the conversion specifier%[.
|
I'm faced with the problem of printing (in console) a value without using any library. I tried to do so by means of the returning value of main function but it seems that there is not a way to show in console the return value of a function without the use of printf(). I'm looking a piece of advice so feel free to 'brainstorm'. Any idea is welcomed, hope you can help me and thank you before hand.
|
Technically,write(notewriteand notfwrite) isn't a library function, it's a system call.stdout(which is what's going to appear on the screen), can be written to if you're able to find it's file descriptor number (hint hint,STDOUT_FILENO) usingwrite.
Hope that's somewhat helpful! If you need some more direction feel free to drop a comment!
|
I have a string in C that i want to split in str_tok
String is =04_1,03_0,05_1It works fine if split once.
```
char* token = strtok(argv[2], ",");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ","); }
```
It will get04_1 03_0 05_1I want to split it again with the_underscore as the delimiter
SOLUTION FOUND
```
char* token = strtok(argv[2], "_,");
token = strtok(NULL, "_,");
```
|
You can givestrtokmultiple deliminators:
```
token = strtok(NULL, ",_");
```
I guess that will give you:
```
04 1 03 0 05 1
```
If that helps?
Otherwise,https://linux.die.net/man/3/strtok_rsaysstrtok_ris the reentrant version.
Personally, I'd probably just do it in two separate steps and avoid nesting it.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.