question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I need to print variables usingHEXformat.
The problem is when my variables are little the MSBs equal 0 so they are not printed.
```
ex: uint16_t var = 10; // (0x000A)h
```
-> I need to print"000A"but no matter what I do it always prints just'A'
How could I get it to work?
|
You can add a leading0to the width specifier in order to forceprintfto add leading zeros (at least, you can in C and C++ - notentirelysure about other languages that use the function).
For example, in C, the following:
```
#include <stdio.h>
#include <stdint.h>
int main()
{
uint16_t a = 10; // 0xA
printf("%04X\n", a);
// ^ width specifier: display as 4 digits
// ^ this signals to add leading zeros to pad to at least "n" digits
return 0;
}
```
will display:
```
000A
```
|
This is the algorithm to retrieve values from a2D array, what will be thetime complexityof this algorithm?
```
for(i=0;i<n;i++){
for(j=0;j<2;j++){
x = arr[i][j]
}
}
```
So thetime complexityof this algorithm would beO(2n)orO(n^2)? What is thereason?
|
Outer loop is iterating n times, but inner loop is iterating only two times, So time complexity will be O(2n) and not O(n^2). And
```
O(2n) = O(n)
```
|
Trying to do a rank based voting algorithm. Rank tells order of voter preference. For example if rank is 0, this is the first choice of the voter. I'm trying to save the order of names to the array but it doesn't work.
Error is at the ranks[rank] = name;
```
bool vote(int rank, string name, int ranks[])
{
for (int i = 0; i < candidate_count; i++)
{
if (strcmp(name, candidates[i]) == 0)
{
ranks[rank] = name;
printf("rank was successfuly recorded");
return true
}
}
// TODO
return false;
}
```
|
Your are trying to store a String value in int array.
Either change the type of ranks array to String or change type of name to int.
|
I need to print variables usingHEXformat.
The problem is when my variables are little the MSBs equal 0 so they are not printed.
```
ex: uint16_t var = 10; // (0x000A)h
```
-> I need to print"000A"but no matter what I do it always prints just'A'
How could I get it to work?
|
You can add a leading0to the width specifier in order to forceprintfto add leading zeros (at least, you can in C and C++ - notentirelysure about other languages that use the function).
For example, in C, the following:
```
#include <stdio.h>
#include <stdint.h>
int main()
{
uint16_t a = 10; // 0xA
printf("%04X\n", a);
// ^ width specifier: display as 4 digits
// ^ this signals to add leading zeros to pad to at least "n" digits
return 0;
}
```
will display:
```
000A
```
|
This is the algorithm to retrieve values from a2D array, what will be thetime complexityof this algorithm?
```
for(i=0;i<n;i++){
for(j=0;j<2;j++){
x = arr[i][j]
}
}
```
So thetime complexityof this algorithm would beO(2n)orO(n^2)? What is thereason?
|
Outer loop is iterating n times, but inner loop is iterating only two times, So time complexity will be O(2n) and not O(n^2). And
```
O(2n) = O(n)
```
|
The value ofiis not conflicting with the value ofiinitialized inside the loop, why is it so?
```
#include <stdio.h>
int main()
{
for (int i = 0; i < 5 ; i++)
{
int i = 10;
printf("%d \t", i);
i--;
}
return 0;
}
```
|
The variableiwas initialized as zero in the loop. Now, when the loop iteration begins, the identically named variableiinside the braces shadows the original one (defined outside of the braces).
Since it was initialized to 10, the program displays10, then it is decremented by one later that doesn't affect the output because the shadowedint i = 10;is executed in each iteration. This will keep happening 5 times.
Here's ademo.
|
Can we add two numbers using pointers but without using any variable like a,b?
I mean, generally, we take two variables and store it in pointer... but is it possible to the numbers without taking variable or can we take pointer variable?
|
Simple answer :
```
int *a = (int *)malloc(sizeof(int));
*a = 10;
int *b = (int *)malloc(sizeof(int));
*b = 20;
printf("%ld + %ld = %ld\n", *a , *b , *a + *b);
```
|
I would like to make clang compile both C and C++ files in the directory (if any). To achieve this, I run clang as follows:clang *.c *.cpp. My issue is that it refuses to run if there's no files of one type:clang: error: no such file or directory: '/mnt/c/test/*.c'Is there a way to make clang ignore wildcards that don't match any files?
Thank you
|
The problem seems to be with the built in shell globbing inbash, not withclang. You can't makeclangignore what you feed it and a non-matching globbing will send the result unexpanded (since there's nothing to expand). To turn off the default globbing so that no matches results in an empty match:
```
shopt -s nullglob
```
To turn it on again
```
shopt -u nullglob
```
|
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 asked to write the C code that finds the number pi using the Leibniz formula.
However, the result should be 3.14 but result turns 3.23. What is the reason for this?
```
//Calculating the value of PI
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<conio.h>
//function main begins program execution
int main( void )
{
float pi = 0;
size_t k,n;
for ( n = 0 , k = 0; n <= 10 , k <= 10; n++ ,k++) {
pi += ( pow( -1, n ) * 4 )/ ( 2 * k + 1 );
}//end for
printf(" pi is %.2f\n",pi );
getch();
return 0;
}//end main
```
|
I played with it by increasing your iterations.At "200" I got 3.15.Basically "10" isn't even close to enough.
|
I'm trying to resize an array in C but i get a runtime assertion
this is the code snippet :
```
int *v = malloc(sizeof(v) * 5);
memcpy(v, (int[]){ 0, 1, 2, 3, 4,}, 5 * sizeof(int));
v = realloc(v, sizeof(int) * 6);
v[6] = 6;
for(int i = 0; i < 5; i++)
{
printf("%d", v[i]); //assertion at this line
}
```
I get this when i run the program:
```
a.out: malloc.c:2539: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
```
and I don't understand it
I 'm also not getting any warnings
|
You got two bugs that may cause memory corruption:
sizeof(v)->sizeof(*v)v[6] = 6;, this is out of bounds since you allocated space for 6 items not 7. And C got 0-indexed arrays as they taught us in array beginner class.
|
Can we add two numbers using pointers but without using any variable like a,b?
I mean, generally, we take two variables and store it in pointer... but is it possible to the numbers without taking variable or can we take pointer variable?
|
Simple answer :
```
int *a = (int *)malloc(sizeof(int));
*a = 10;
int *b = (int *)malloc(sizeof(int));
*b = 20;
printf("%ld + %ld = %ld\n", *a , *b , *a + *b);
```
|
I would like to make clang compile both C and C++ files in the directory (if any). To achieve this, I run clang as follows:clang *.c *.cpp. My issue is that it refuses to run if there's no files of one type:clang: error: no such file or directory: '/mnt/c/test/*.c'Is there a way to make clang ignore wildcards that don't match any files?
Thank you
|
The problem seems to be with the built in shell globbing inbash, not withclang. You can't makeclangignore what you feed it and a non-matching globbing will send the result unexpanded (since there's nothing to expand). To turn off the default globbing so that no matches results in an empty match:
```
shopt -s nullglob
```
To turn it on again
```
shopt -u nullglob
```
|
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 asked to write the C code that finds the number pi using the Leibniz formula.
However, the result should be 3.14 but result turns 3.23. What is the reason for this?
```
//Calculating the value of PI
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<conio.h>
//function main begins program execution
int main( void )
{
float pi = 0;
size_t k,n;
for ( n = 0 , k = 0; n <= 10 , k <= 10; n++ ,k++) {
pi += ( pow( -1, n ) * 4 )/ ( 2 * k + 1 );
}//end for
printf(" pi is %.2f\n",pi );
getch();
return 0;
}//end main
```
|
I played with it by increasing your iterations.At "200" I got 3.15.Basically "10" isn't even close to enough.
|
I'm trying to resize an array in C but i get a runtime assertion
this is the code snippet :
```
int *v = malloc(sizeof(v) * 5);
memcpy(v, (int[]){ 0, 1, 2, 3, 4,}, 5 * sizeof(int));
v = realloc(v, sizeof(int) * 6);
v[6] = 6;
for(int i = 0; i < 5; i++)
{
printf("%d", v[i]); //assertion at this line
}
```
I get this when i run the program:
```
a.out: malloc.c:2539: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
```
and I don't understand it
I 'm also not getting any warnings
|
You got two bugs that may cause memory corruption:
sizeof(v)->sizeof(*v)v[6] = 6;, this is out of bounds since you allocated space for 6 items not 7. And C got 0-indexed arrays as they taught us in array beginner class.
|
I have the following C code. I want to write a Java version of the C condition but I don't know what boolean operators the C numerical operators represent in the if statement.
The C code is:
```
if ( (n >= 1) * (n < 10) + (n == 0) )
{
printf("A\n");
}
else
{
printf("B\n");
}
return 0;
```
What boolean operators do * and + translate to?
|
You can figure this out by looking at their truth tables.
Keep in mind that in C,0isfalse, and any other value (including1) istrue.
```
* | 0 | 1 + | 0 | 1
| | | |
---+---+-- ---+---+--
0 | 0 | 0 0 | 0 | 1
---+---+-- ---+---+--
1 | 0 | 1 1 | 1 | 2
```
In case this is a homework question, I will leave the rest to you.
If you need more hints, Google for "boolean operation truth table".
|
I want to know if there is a way to make a parent process stop his child for a given time usingsignalfor example:
```
pid_t pid = fork();
if(pid==0){
while(1){
//some code here
}
}else{
// some code to make child process stop for x seconds
}
```
|
You may use SIGSTOP and SIGCONT to stop and continue the process. In combination with some time delay function (e.g. sleep() ) you may get the desired effect.
You may check the example here:https://ostechnix.com/suspend-process-resume-later-linux/
|
How to pass a pointer toconst intin a recursive call. I am using the following code format to calculate Fibonacci recursively, but am getting the error:
error: lvalue required as unary '&' operand**
```
#include <iostream>
void fun(const int *n)
{
fun( &(*n-1) ); // it is giving error.
}
int main()
{
const int n = 4;
fun(&n);
}
```
|
You would have to use another variable then, to which you assign the decremented const variable: you simply can't pass a decreased value of a const variable, since by definition, it is not modifiable neither by increment or decrement.
```
#include <iostream>
void fun2 (const int *n)
{
std::cout << *n << std::endl;
}
void fun1(const int *n)
{
int x = *n-1;
fun2( &x );
}
int main()
{
const int n = 4;
fun1(&n);
}
```
|
I would like to trap and handle CPU exceptions outside of KVM. How can I achieve this?
```
/* KVM_EXIT_EXCEPTION */
struct {
__u32 exception;
__u32 error_code;
} ex;
Unused.
```
From the documentation. This exit status is apparently not implemented.
Yet, to handle an exception afaik you would have to exit the guest first anyway.
I'm not going to write an IDT in the guest, don't worry about that.
|
So, I solved this by handling the exceptions unprivileged (in usermode), and simply trap into the hypervisor using any method of doing such, like writing to a trapping MMIO address. In my case the guest is always unprivileged and can't modify its own pagetables, so the host will be setting everything up before entering the guest.
This works completely fine, however backtraces will need to be handled remotely.
|
This question already has answers here:How to write a while loop with the C preprocessor?(7 answers)Closed2 years ago.
Is it possible to write a macro such as the following:
```
putcharX(repeat, char)
==>
putcharX(5, '*');
==>
putchar('*');
putchar('*');
putchar('*');
putchar('*');
putchar('*');
```
Note: I'm not looking to use afor/while/doloop, but literally copy the commandnnumber of times in the code. Is such a thing possible with the cpp?
|
you cannot write "real" recursive statements in macros. the closest you can get is
```
#define putcharOne putchar('*')
#define putcharTwo putcharOne; putcharOne
#define putcharThree putcharOne; putcharOne; putcharOne
#include <stdio.h>
int main()
{
putcharOne;
putcharTwo;
return 0;
}
```
|
Could we point and address specific place in memory using pointer in c language?
Then modify it from another file (ANOTHER PROGRAM) and view it from any where.
Like :
Modifying it :
```
#include<stdio.h>
void main(){
int *p;
p= 12345678;
scanf("%d",p);
}
```
Viewing it :
```
#include<stdio.h>
void main(){
int *p;
p= 12345678;
printf("%d", *p);
}
```
|
No. Each process in your operating system has its own address space.Processes can communicate, using the channels provided by the operating system.Look into IPC, aka inter process communication, if you're interested in knowing more about it.
|
If I have the following buffer:
```
char buffy[40]; // includes \0 at the end
```
Should thefgetsfunction haveSTLEN40 or 39? Why?
```
char buffy[40];
while (fgets(buffy, 40, fp) != EOF)
// ...
```
|
The number of characters thatfgetsreads in is at most one less than the value of its second parameter. So the proper value should be 40 in this context. It will read at most 39 characters and the last element of the array will be used to store the '\0'. This ensures that no buffer overrun will occur. As an idiom
```
fgets(buf, sizeof buf, fp)
```
may be used if (and only if) the declaration of thearraybufis visible.
Notice that there is nothing wrong with calling it asfgets(buf, 39, fp), but this will cause it to read in at most 38 characters, and the '\0' will be stored inbuf[38](if 38 characters have been read). The last element of the array (buf[39]) will not be used at all.
|
How can I replace theNumbersvalues with the with theinput. If theinputis 1 than theNumbersvalue is going to be{"K", "2", "3", "4", "5", "6", "7", "8", "9"}and then if the userinputis 4 theNumbersvalue is going to be re updated to be{"K", "2", "3", "K", "5", "6", "7", "8", "9"}and so on.
```
int main(void)
{
int input = 0
char Numbers[][9] = {"1", "2", "3", "4", "5", "6", "7", "8", "9"};
return 0;
for (int i = 1; i <= 18; i++){
scanf("%d", &input);
}
}
```
|
You need to use the standard C string function strcpy. For example
```
#include <string.h>
//...
strcpy( Numbers[input - 1], "K" );
```
Before using the function you should check that the value ofinputis greater than0and not greater thansizeof( Numbers ) / sizeof( *Numbers ).
|
Instead of writingif(exp[i] =='*' || exp[i] =='/' || exp[i] =='+')can i write something like thisif(exp[i] == {'*','/','+'}).But writing this throws me an error, So is there any simple way of doing this ?
|
You can use thestrchr()function together with acompound literal:
```
if( strchr( (char[]){'*','/','+','\0'}, exp[i] ) )
```
Or if you prefer, the far more readable string literal version:
```
if( strchr("*/+", exp[i]) )
```
|
When compiling withgccI usedtimeto get compile time.
```
time gcc main.c && ./a.out
```
when trying to do the similar thing inclangI can't get the result
```
clang -time main.c && ./a.out
```
gives me a waring:
clang: warning: argument unused during compilation: '-time'
probably my approach is false, so please help me find compile time using clang
|
Tryclang main.c -ftime-report
|
I was looking into scanf() - shifts the cursor to next line so got curious if fgets does the same but the output I am getting does not make sense to me . Please help me out in understanding it
Code -
```
main()
{
char name[30] , name2[20];
scanf("%s" , name) ;
printf("%s" , name) ;
fgets(name2 , 30 , stdin) ;
printf("%s" , name2) ;
return 0 ;
}
```
Output -enter image description here
In the first line I input premier it gives an output of premier in second line but its not asking me for input second time and please clarify if fgets() also moves cursor to second line
THANKS FOR HELPING OUT!!!
|
The firstscanfdoesn't consume the end of line, just a string; so the call tofgetsread an empty line.
Never mixscanfandfgetsyou will have problems.scanfis formatted input, whilefgetsis just raw input.
|
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
exit(0);
printf("%s\n", "Nice");
}
```
I was wondering if it is possible to disable whatever it is that doesn't generate the instruction for a call to printf if it is placed right after a call to exit.
I'm usinggcc version 4.8.4 (Ubuntu 4.8.4-2ubuntu1~14.04.4)and no flags when compiling. I have tried using -O0, but there is no change in the disassembly.
```
0x000000000040052d <+0>: push %rbp
0x000000000040052e <+1>: mov %rsp,%rbp
0x0000000000400531 <+4>: mov $0x0,%edi
0x0000000000400536 <+9>: callq 0x400430 <exit@plt>
```
|
exit()is defined in<stdlib.h>as never returning to its caller:
```
_Noreturn void exit(int status);
```
The compiler takes advantage of this and does not generate code for statements that are never reached. If you pass-Wallto get more diagnostics, you will get a warning about this.
|
This question already has answers here:Is the strrev() function not available in Linux?(7 answers)Closed2 years ago.
I am unable to use strrev() function even after including string.h in Ubuntu 20.04. Compiler says undefined reference to strrev(), but strlen() and other functions work. What should I do?
|
You need to implement it yourself.
```
char *strrev(char *str)
{
char *end, *wrk = str;
{
if(str && *str)
{
end = str + strlen(str) - 1;
while(end > wrk)
{
char temp;
temp = *wrk;
*wrk++ = *end;
*end-- = temp;
}
}
}
return str;
}
```
|
This question already has answers here:Is the strrev() function not available in Linux?(7 answers)Closed2 years ago.
I am unable to use strrev() function even after including string.h in Ubuntu 20.04. Compiler says undefined reference to strrev(), but strlen() and other functions work. What should I do?
|
You need to implement it yourself.
```
char *strrev(char *str)
{
char *end, *wrk = str;
{
if(str && *str)
{
end = str + strlen(str) - 1;
while(end > wrk)
{
char temp;
temp = *wrk;
*wrk++ = *end;
*end-- = temp;
}
}
}
return str;
}
```
|
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.Closed2 years ago.Improve this question
But it works for a long data type?
for example
```
printf("%i", strlen("test")) -- errors
printf("%li", strlen("test")) -- this works
```
|
strlendoesn't return anintor along, it returns asize_t. It appears that in your system, asize_tis the same size as along.
But if you're going to print out asize_twithprintf, you're supposed to use%zuto do it. That should work (on a new enough compiler to support it) regardless of the relative sizes ofint,longandsize_t. Before%zuwas added to the spec (e.g., C89/90) we typically cast thesize_tto anunsigned longbefore printing it out (and then used%lu, obviously).
|
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.Closed2 years ago.Improve this question
But it works for a long data type?
for example
```
printf("%i", strlen("test")) -- errors
printf("%li", strlen("test")) -- this works
```
|
strlendoesn't return anintor along, it returns asize_t. It appears that in your system, asize_tis the same size as along.
But if you're going to print out asize_twithprintf, you're supposed to use%zuto do it. That should work (on a new enough compiler to support it) regardless of the relative sizes ofint,longandsize_t. Before%zuwas added to the spec (e.g., C89/90) we typically cast thesize_tto anunsigned longbefore printing it out (and then used%lu, obviously).
|
I tested the following code on two different computers, using gcc:
```
int main(int argc, char** argv) {
char c1, c2;
c1 = 100;
c2 = 4*c1;
printf("%d", c2);
}
```
One of both tests threw a segmentation fault, the other outputted-112. Why did this happen ?
|
First of all, let me tell you, a plancharissignedorunsigned, depends on the implementation.
That said, I think you understand it by now, trying to store a value into a type which may not be fit to handle that, is implementation defined behavior.
In most practical case, the stored value will be treated as the 2's compliment value (of a negative number), and be used as such, but this is not guaranteed.
|
I am running gdb in the following way:
```
gdb $file "My Arg here" --ex "source .breakpoints_$file.c" --ex 'r' --ex 'set confirm off'
```
Yet I get the following in the program:
```
βββ Variables βββββββββββββββββββββββββββββββββββ
arg argc = 1, argv = 0x7fffffffe1d8: 47 '/'
```
Meaning it's not picking up theargv. How would I properly pass cmd line args to gdb?
|
You can do this by passing theargsargument togdb. For example:
```
gdb --ex "source .breakpoints_$file.c" --ex 'r' --ex 'set confirm off' \
--args $file "An argument" another
```
And now we get:
```
βββ Variables ββββββββββββββββββββββββββββββ
arg argc = 3, argv = 0x7fffffffe1b8: 47 '/'
>>> p argv[1]
$1 = 0x7fffffffe49c "An argument"
>>> p argv[2]
$2 = 0x7fffffffe4a8 "another"
```
|
I am writing a function
```
int are_non_negatives(int* start, int n) {
...
}
```
This function returns 1 if all the nextnintegers in the arraystartarenon-negative. It returns 0 otherwise.
My question is if there exist tricks that do this as fast as possible (other than looping and checking every single position)?
Dirty/non-portable tricks are fine. I want to know about those as well. Thanks!
|
One slightly "dirty/non-portable" trick you could leverage for the worst case where all elements need to be checked: In 2's complement int representation, the highest bit is set if and only if the value is negative. So, you could bitwise OR them all and check the highest bit. This could be done using vector instructions to do batches of them at a time, e.g. 8 elements at a time supposing 32-bit int and 256-bit AVX instructions.
|
I am running gdb in the following way:
```
gdb $file "My Arg here" --ex "source .breakpoints_$file.c" --ex 'r' --ex 'set confirm off'
```
Yet I get the following in the program:
```
βββ Variables βββββββββββββββββββββββββββββββββββ
arg argc = 1, argv = 0x7fffffffe1d8: 47 '/'
```
Meaning it's not picking up theargv. How would I properly pass cmd line args to gdb?
|
You can do this by passing theargsargument togdb. For example:
```
gdb --ex "source .breakpoints_$file.c" --ex 'r' --ex 'set confirm off' \
--args $file "An argument" another
```
And now we get:
```
βββ Variables ββββββββββββββββββββββββββββββ
arg argc = 3, argv = 0x7fffffffe1b8: 47 '/'
>>> p argv[1]
$1 = 0x7fffffffe49c "An argument"
>>> p argv[2]
$2 = 0x7fffffffe4a8 "another"
```
|
I am writing a function
```
int are_non_negatives(int* start, int n) {
...
}
```
This function returns 1 if all the nextnintegers in the arraystartarenon-negative. It returns 0 otherwise.
My question is if there exist tricks that do this as fast as possible (other than looping and checking every single position)?
Dirty/non-portable tricks are fine. I want to know about those as well. Thanks!
|
One slightly "dirty/non-portable" trick you could leverage for the worst case where all elements need to be checked: In 2's complement int representation, the highest bit is set if and only if the value is negative. So, you could bitwise OR them all and check the highest bit. This could be done using vector instructions to do batches of them at a time, e.g. 8 elements at a time supposing 32-bit int and 256-bit AVX instructions.
|
This question already has answers here:Algorithm to find nth root of a number(5 answers)Closed2 years ago.
C hassqrt()andcbrt(), but those are only the second and third roots. What if the root is an arbitrary number? What if I need the 57nth root?
|
Use thepowfunction, taking advantage of the fact that getting the 57 root is the same as raising to the power of 1 / 57.
More generically, to get theyroot ofx:
```
double result = pow(x, 1.0 / y);
```
|
```
*(&v69 + v15) = (double)(char)(*((_BYTE *)v14 + v15) ^ 0x80) * 0.0078125;
```
What does *(&v69 + v15) on the left side of the expression mean in this construction?
v69 is the variable declared above.
```
float v69;
```
|
This is (confirmed by OP) reverse-compiled code.
Take the address of variable v69 and add v15 to it and dereference the result as a pointer and assign to it. It makes sense.
But there's a problem waiting for you. If not passed back through the exact same compiler again, variable rearrangement will break the corresponding algorithm. The code needs to be rewritten making the array of floats in the appropriate place. That is, the declaration ofv69should look likefloat v69[some-number].
|
```
*(&v69 + v15) = (double)(char)(*((_BYTE *)v14 + v15) ^ 0x80) * 0.0078125;
```
What does *(&v69 + v15) on the left side of the expression mean in this construction?
v69 is the variable declared above.
```
float v69;
```
|
This is (confirmed by OP) reverse-compiled code.
Take the address of variable v69 and add v15 to it and dereference the result as a pointer and assign to it. It makes sense.
But there's a problem waiting for you. If not passed back through the exact same compiler again, variable rearrangement will break the corresponding algorithm. The code needs to be rewritten making the array of floats in the appropriate place. That is, the declaration ofv69should look likefloat v69[some-number].
|
How can i redeclared a variable in c. I know this can not be declared directly as follows;
```
int k = 5;
float k = 12.5;
```
Is there any possible way to do like this?
|
No, you cannot redefine a variable with different types within the same scope.
Although, there is one possible alternative. The same variable name can be used in a new scope or a subroutine. See the example below:
```
#include <stdio.h>
// Subroutine
void testing()
{
int k = 9;
printf("k = %i\n", k);
}
// Main Routine
int main() {
int k = 5;
// New scope
{
printf("k = %i\n", k);
float k = 12.5;
printf("k = %5.2f\n", k);
testing();
}
return 0;
}
```
The output is:
```
k = 5
k = 12.50
k = 9
```
|
Say I had a program in C where I asked the user to enter a number between 1 and 3. If the user selected a number outside of the range, whicherrnowould be most appropriate to return in my function?
|
I wouldn't use errno for a simple user-facing function like that. errno is mostly for system calls that are reporting low-level I/O, process, and other OS errors. It's not designed for things like bad keyboard input, incorrect file contents, or out of range values. When it's used by user libraries it's typically when they are forwarding internal system errors to the caller and don't want to bother creating an opaque error mechanism to wrap errno.
For example, a JSON library or a TLS encryption library might forward errno values from any failed I/O calls they perform. A multiprocessing library might forward errno values from failed fork/clone syscalls.
That said, if you still want to use errno,EINVAL Invalid Argumentis reasonable.
|
If open() returns a value of -1 to my program, which indicates a failure, do I still need to close the file? I read that if fopen() fails, then you do not need to call fclose() since you have not opened any files. I was wondering if this was the case for open() as well?
```
int fd = open(myfile, O_RDONLY);
if (fd == -1) {
close(fd);
}
```
|
No.
-1 isn't a file handle, so there's no need or reason to close it.
You could have answered your own question by checking the return value ofclose(-1). It returns -1, so that call was in error.
|
When I run isalpha in vscode with c17-standard (or any other) it always returns only 1 or 0. Yet when i run it on another system it returns also bigger numbers than 1. How does isalpha work? Where can I see which implementation do I have? What causes this difference in behaviour on my system?
I realise this question might be very weird or irrelevant but I tried to search for an answer yet couldn't find one.
|
From the C standard:
7.4.1 Character classification functionsThe functions in this subclause returnnonzero (true)if and only if the value of the argument conforms to that in
the description of the function.
When you implement the function from this class you do not have to return1or0. You are free to return any nonzero value not only1
|
I am trying to debug a Heap Corruption (using the QIRA Debugger); that only works with Doug Lea's Malloc.
I have tried doing the following:
```
LD_PRELOAD=./malloc.so qira ./program $(cat shfree5)
```
I get the following error:
ERROR: ld.so: object './malloc.so' from LD_PRELOAD cannot be preloaded (wrong ELF class: ELFCLASS32): ignored.
which happens because the loader tries linking an x86malloc.soto an x64qira.
I want to apply theLD_PRELOADonly to./program, not toqira; I have tried with theenvcommand, but can not make it to work.
Thanks in advance!
|
It looks like you can setQEMU_SET_ENV=LD_PRELOAD=./malloc.soin the environment to affect the process.
I'll note that you can similarly unset environment variables for the target by settingQEMU_UNSET_ENV=FOO,BAR.
|
Is there a way to pass a literal value to a function argument of a pointer .
eg
```
unsigned char returnBitShift(unsigned char* bit , unsignedChar* shiftBitsToRight){
return (*bit) >> (*shiftBitsToRight);
}
unsigned char someBit = 254 , bitval;
bitVal = returnBitShift(&someBit,(unsigned char)& 1);
```
|
You can use a compound literal to create an unnamed object, and its address can be taken and passed to a function:
```
bitval = returnBitShift(&someBit, & (unsigned char) {1});
```
A compound literal is form with a type in parentheses followed by an initializer list in braces.
|
I am having a c program which print letter by letter of the word. I referred this program from this linkhttps://www.tutorialgateway.org/c-program-to-print-characters-in-a-string/. If I run this program in online c compiler this gives the exact result, but not working in turbo c++
```
#include <stdio.h>
int main()
{
char str[100];
printf("\n Please Enter any String : ");
scanf("%s", str);
for(int i = 0; str[i] != '\0'; i++)
{
printf("The Character at %d Index Position = %c \n", i, str[i]);
}
return 0;
}
```
This program doesn't through any error, but I don't know why this program doesn't print the result.
|
Tryfgets(str, 100, stdin)instead ofscanf(). This is the normal way to read a line into a buffer. When I usedscanf()I only got part of the output because it will stop reading a string at a space.
|
Is there a function attribute in GCC which acts as __stackless in IAR?
I've been looking for it and didn't find anything...
Thanks in advance
Regards,
Victor.
|
I would use a combination ofnakedandnoreturn.
__attribute__((naked,noreturn,optimize("-O3")))
```
extern int *x;
void __attribute__((naked,noreturn,optimize("-O3"))) foo(int a, int b)
{
for(int c = a; c < b; c++)
{
x[c] = c * a;
}
}
```
https://godbolt.org/z/xf9YKa
|
Suppose my code is
```
void main()
{
for(i=1;i<5;i++)
{
printf("%d, ",i);
}
}
```
The output of this program will be
```
1, 2, 3, 4,
```
How can I get output like
```
1, 2, 3, 4
```
The last,should be omitted.
|
```
#include <stdio.h>
int main(void)
{
const char *pad = "";
for (int i = 1; i < 5; i++)
{
printf("%s%d", pad, i);
pad = ", ";
}
putchar('\n');
return 0;
}
```
You can't "delete" the character once you've printed it. You have to code so that you don't print what isn't actually wanted.
|
I am actually stuck with the idea as mentioned in the question, about calling nested functions dynamically.
Say I have 4 functions: fun1(), fun2(), fun3(), fun4()
And I want them to be called in this way
```
fun1()
{
fun2()
{
fun3()
{
fun4()
{
}
}
}
}
```
I am not sure how that can be done in C.
Is there a way to do that in C, like using function pointer?
|
Nested functions are not part of the C Standard. Some compilers support them but using them makes the code less portable. Avoid such extensions.
|
I recently learned something fromthis questionaboutcinin C++ and its speed was compared with the speed ofscanfin C. Callingcinobject is much slower than callingscanffunction as usual but when I was reading the accepted answer, I understood if we callstd::ios::sync_with_stdio(false);,cinsynchronization withscanfis turned off andcinspeed becomes so faster and even faster thanscanfin this case.
So, will we face some problems if we turn it off? If so, what problems, and is it good to turn offcinsynchronization withscanfin C? Thanks for helping.
|
If you use both sets of I/O functions (header<cstdio>or<stdio.h>and also<iostream>) on the same stream (e.g. thestdinstream is associated with bothscanfandcin), then you'd better leave them synchronized.
If any one stream only uses one I/O family you can turn off synchronization (you can still usefscanfwith a particular file andcinwithstdinfor example, as long as separate streams are involved).
|
Given the below C code:
```
static atomic_int a_i;
static void f()
{
for (int i = 0; i < 100; ++i)
atomic_fetch_add_explicit(&a_i, 1, memory_order_relaxed);
}
```
And two threads concurrently callingf().
Is it the case thata_imay end up having a non200result in hardware platforms with a relaxed cache coherency protocol (unlike x86)? In other words, the operation is atomic but no guarantees that the writes by one thread would be publicly visible immediately to the other?
|
The resulting value is guaranteed to be 200.
The memory order argument is only about whichothermodifications are made visible to other threads.memory_order_relaxedmeans that no guarantees are made. But the variable itself is still updated atomically.
|
This question already has answers here:Use of %d inside printf to print float value gives unexpected output(4 answers)Closed2 years ago.
This is my code:
```
#include <stdio.h>
#define PI 3.141592f
#define RADIUS 10.0f
int main(void)
{
float volume;
volume = (4.0f/3.0f) * PI * (RADIUS * RADIUS * RADIUS);
printf("Volume: %d\n", volume);
return 0;
}
```
It's wrongly printing the value536870912.
What am I doing wrong? As far as I know, the math is right.
|
%dis for printingint, so passingfloatto that invokesundefined behavior.
You should use%for%gto printfloat.
|
How can I format fscanf to format the input{'name surname', 'username', points}to strings which do not contain apostrophes
```
fscanf(fp,"{%s %s %d}",name,username,username1);
```
|
This should work:
```
fscanf(fp,"{'%[a-zA-Z ]', '%[a-zA-Z ]', %d}",name,username,username1);
```
|
This question already has answers here:Use of %d inside printf to print float value gives unexpected output(4 answers)Closed2 years ago.
This is my code:
```
#include <stdio.h>
#define PI 3.141592f
#define RADIUS 10.0f
int main(void)
{
float volume;
volume = (4.0f/3.0f) * PI * (RADIUS * RADIUS * RADIUS);
printf("Volume: %d\n", volume);
return 0;
}
```
It's wrongly printing the value536870912.
What am I doing wrong? As far as I know, the math is right.
|
%dis for printingint, so passingfloatto that invokesundefined behavior.
You should use%for%gto printfloat.
|
How can I format fscanf to format the input{'name surname', 'username', points}to strings which do not contain apostrophes
```
fscanf(fp,"{%s %s %d}",name,username,username1);
```
|
This should work:
```
fscanf(fp,"{'%[a-zA-Z ]', '%[a-zA-Z ]', %d}",name,username,username1);
```
|
In C'ssignal.hheader file there are a bunch of macros defined for (e.g.SIGCONT,SIGKILL).
Are these object-like macros or function-like macros? How can one tell?
Disclaimer: very new to C programming.
|
SIGCONTandSIGKILLare object-like macros.
Macros that are defined and used with parenthesized arguments after them, like:
```
#define max(a, b) ((a) < (b) ? (b) : (a))
```
are function-like macros, simply because they use arguments like a function. Macros that are defined and used without parenthesized arguments, like:
```
#define c 299792458. // Speed of light / (m/s).
```
are object-like macros, because they are more like ordinary variables (which designateobjectsin the terminology of the C standard).
|
While debugging a simple C program, I always get an error saying "Launch: program 'XXX' does not exist"
Note: I already have my compiler - GCC installed & I'm using Ubuntu operating system.
|
Replace the launch configuration from:
```
"program": "${workspaceRoot}/helloworld"
```
with:
```
"program": "${fileDirname}/helloworld"
```
This should fix your problem.
Important:Ensure the compiled filename intasks.jsonis equivalent to your"program"'s filename.
|
```
char str[] = "a";
char ch = 'a';
```
speaking of the difference between the two, we all knowstrpoint to a memory space which stored [a, \0], but I want to ask whether there is a difference betweenstr[0]andch?
|
but I want to ask whether there is a difference betweenstr[0]andch?
No.
str[0]andch, both are of typechar, and hold the value'a'. From this aspect (type and value), there is no difference.
|
I know that there is a similar topic, but those answers don't clarify what I want to find out. Thus, as long as from the excerpt below one can notice that a function and the reference to that function behave in the same way, what is the point in having both function variable and function pointers.
```
#include <stdio.h>
int f(){ return 0;}
int main() {
printf("%p\n",f);
printf("%p\n",&f);
printf("%p\n",f + 1);
printf("%p\n",&f + 1);
return 0;
}
```
Also, both f and &f could be passed as parameters for other functions.
|
fand&fmean the same thing, so there's no need to use&f.
But the language designers decided not to make it invalid for some reason, so you have this redundant syntax.
|
I cannot understand why are pointer type casts necessary, as long as pointers point to an address and their type is important only when it comes to pointer arithmetic.
That is to say, if I encounter the next code snippet:
int a = 5;then both
char*b = (char*)&a;andint*c = (int*)&a
point to the very same memory location.
Indeed, when executingchar*b = (char*)&apart of the memory contents may be lost, but this is due to the type ofbischar*which can store onlysizeof(char)bytes of memory, and this could be done implicitly.
|
The pointer type is important when you dereference it, since it indicates how many bytes should be read or stored.
It's also important when you perform pointer arithmetic, since this is done in units of the size that the pointer points to.
|
I can add include paths in Visual Studio easily but I couldn't find a way to do it in GCC? Any helps please?
|
Use the-Icommand-line argument:
```
gcc -Ipath
```
|
Take the following example where I want to get aconstdogandcatobject:
```
// place 1 (type declaration)
const typedef struct Animal {
int id;
char* name;
} Animal;
// place 2 (singleton creation/assignment)
const Animal Dog = {1, "Dog"};
const Animal Cat = {2, "Cat"};
// place 3 (reference of singleton)
void main(void) {
const Animal dog = Dog;
const Animal* dogPtr = &Dog;
}
```
Each time here I am using theconstprefix. Is theconstprefix required in all of the above three places, or is it only required on the first, or what's the proper way to go through this entire chain and why?
|
const in place 2 is not needed. If you remove the const, you still cannot change the values ofDogandCatafter the declaration because your const typedef. Likewise, the const in place 3 is not needed.
If you remove the const typedef, then you need the consts in place 2 and 3, depending on your purpose.
|
```
char fileName[20];
puts("Enter the date.\n");
scanf("-> %s", fileName);
//Read the file
FILE *ptr;
ptr = fopen(fileName, "r");
if(ptr == NULL)
{
printf("\nNo file was found with this name\n");
exit(0);
}
else
{
printf("\nI FOUND the file.\n");
}
fclose(ptr);
```
I just want the user to enter a file name and then display 'found the file' as of now however even when the this code file and the text file are in same directory I am always getting the message'No file was found with this name' and I assure you that I am inputting the right file name(along with .txt extension).
|
Thank you @kaylum I got the answer.
The problem is with thescanf()statement. Thescanf("-> %s", fileName)statement wants the user to input only->otherwise it will fail.
|
Title, basically. Isopen()cross platform? I personally like the flags combined with|better than a string, so can I just useopen()instead? Will it work anywherefopen()will?
|
open()is part of thePOSIXspecification, so it will work in any environment that implements this. This includes all modern flavors of Unix (POSIX is derived from Unix) as well as Windows. So you should be able to use it in any platform you're likely to encounter that also provides a hosted C implementation (so not a microcontroller, but it probably won't havefopen(), either).
If you want aFILE *that you can then use with all the otherstdiofunctions (e.g.fprintf()) you can usefdopen()to get this from the FD returned byopen().
|
So I was reviewing the Microchip's dsPIC MCU header file and stumbled upon this construct:
```
/* Generic structure of entire SFR area for each UART module */
typedef struct tagUART {
uint16_t uxmode;
uint16_t uxsta;
uint16_t uxtxreg;
uint16_t uxrxreg;
uint16_t uxbrg;
} UART, *PUART;
```
I cannot seem to figure out what is a type or instance here (and for what end was this designed like that):
What is tagUART?What is UART?What is *PUART?
|
It's a kind ofall-in-oneform of
```
struct tagUART { // the structure itself with all its details
uint16_t uxmode;
uint16_t uxsta;
uint16_t uxtxreg;
uint16_t uxrxreg;
uint16_t uxbrg;
};
typedef struct tagUART UART; // UART is a shorter name for struct tagUART
typedef struct tagUART *PUART; // PUART is a pointer-type to such a struct
```
|
This question already has answers here:What is short-circuit evaluation in C?(3 answers)Closed2 years ago.
I want to ask a question about the code below.
```
int a=1, b=3, c=1;
if((a||c--)&&(c&&b--)) printf("%d",b);
printf("%d %d %d",a,b,c);
```
Why does the code prints "21 2 1" rather than "1 2 0" ?
Thanks for your help.
|
Since the or is evaluated to true immediately in (a||c--), the c-- is never evaluated. The compiler does this. If a statement is true right off the bat, it won't bother evaluating the rest. So, c is never decremented as the right side of the or is never evaluated.
|
```
#include <stdio.h>
int main()
{
char text[20];
int quantity;
float number;
printf("Enter the data: ");
scanf("%s %*d %f", text, &quantity, &number);
printf("\nOutput: %s %d %f\n", text, quantity, number);
return 0;
}
```
Is there a way to properly use assignment suppression?
Data Output - Example
How can I make it delete the data from the variable "quantity" (%*d), and that it prints correctly.
|
When you use assignment suppression, don't supply an argument for that match:
```
scanf("%s %*d %f", text, &number);
```
As for "deleting" the value inquantity, C doesn't have such a concept. Because it was not initialized, its value isindeterminate, so it should be initialized before printing it.
|
How to assign value to char** in C.
```
char** departmentList;
departmentList[0] = "hahaha";
```
above code is running in a function but failed all other places. Im using gcc 10.2.0 as the compiler.
|
You must allocate some buffer todepartmentListbefore dereferencing that.
```
char** departmentList;
departmentList = malloc(sizeof(*departmentList)); // allocate
departmentList[0] = "hahaha";
```
Add#include <stdlib.h>(if it is not present) to usemalloc().
|
I'm using Visual Studio 2019 and I'm trying to compile an UEFI driver, that uses udis86(https://github.com/vmt/udis86) with the__UD_STANDALONE__preprocessor definition and the /NODEFAULTLIB linker option set.
This gives me this error
I have tried to set the_NO_CRT_STDIO_INLINEpreprocessor definition, like replied to some similar questions to mine, but it just changes the error to
Does anyone have an idea on how to fix this error ?
Thanks in advance
|
Maybe you could take a standalonevsnprintfimplementation from somewhere to satisfy the dependency.
e.g.https://github.com/MrBad/vsnprintf
or the Linux kernel one?https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/lib/vsprintf.c
|
This question already has answers here:random element from array in c(5 answers)Closed2 years ago.
Basically i made an array with number 1,2,3.
```
int array[3] = {1,2,3};
```
How can I select a random number from this list and assign it to a different variable?
|
Use therand()function and mod the result down to 3 values 0, 1, or 2 using mod. Then access the corresponding value in your array:
```
srand(time(NULL));// without this rand() function might continuously give the same value
int index = rand() % 3;
printf("random: %d\n", array[index]);
```
Considering that the array contains hardcoded values, you could simply:
```
int i = (rand() % 3) + 1;
printf("random: %d\m", i);
```
Include the header file<stdio.h>,<time.h>,<stdlib.h>
|
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've been working on this problem:
```
#include<stdio.h>
int main()
{
printf("%c", "abcdefgh"[4]);
return 0;
}
```
This gives e as the output, however I couldn't understand that how an array named "abcdefgh" with 4 elements is getting printed.
In nutshell, please tell me how this program works.
|
The string"abcdefgh"doesn't have 4 elements. It's an array with 9 elements (the characters plus the null terminator, and square brackets are the array subscript operator.
So"abcdefgh"[4]is getting the element at index 4 from"abcdefgh"which is'e'.
|
```
int a = 10;
while (a > 8 ? (a--, (a > 7 ? a-- : a)): a--,a--) {
printf("%d", a); // prints out 7
break;
}
```
premise: I know that the code is very badly written, this is not a real example, I will never write like that.
Can someone explain to me why it prints 7 instead of 8? it seems that the lasta--is computed, but why? the expression is true...
|
Comma operator,has lower precedence than ternary operator?:.
Breaking your expression up:
```
a > 8 // true because a = 10
? (
a-- // executed, making a 9
,
(
a > 7 // true because a = 9
? a-- // executed, making a 8
: a // not executed
)
)
: a-- // not executed
,
a-- // executed, making a 7
```
Threforeabecomes7after evaluating the expression.
|
I would like to convert an int to a byte in C.
In Java, I'd write:
```
int num = 167;
byte b = num.toByte(); // -89
```
In C:
```
int num = 167;
???
```
|
You can simply cast to a byte:
```
unsigned char b=(unsigned char)num;
```
Note that ifnumis more than 255 or less than 0 C won't crash and simply give the wrong result.
|
I'm new to C language and I'm very curious about the best way to declare string in c.
Example:
```
char *name;
//or char name[];
scanf("%s", &name);
printf("Hello %s !", name);
```
Which of these two will be better in this case?
```
char *name;
char name[];
```
|
If you have a string with constant length. You can declare an array ofcharlike this.
```
char name[64];
scanf("%s", name); // no more than 63 characters, remember the '\0'
printf("Hello %s\n", name);
```
If the string length is dynamic, please use the functionmallocto allocate a specific length of memory. What's more you should remember tofreethe memory allocated before.
|
This question already has answers here:how to initialize all elements of an array at one go when definition and declaration are separate?(5 answers)Closed2 years ago.
Is there a way to delay the array initialization. For example, instead of doing:
```
int array[2] = {1,2};
```
To do:
```
int array[2];
array = {1,2}; // possible to do with some sort of cast or other?
```
|
An array cannot be assigned to directly.
You would either need to assign each element individually, or usememcpyalong with a compound literal of the proper type.
```
memcpy(array, (int[2]){1,2}, sizeof(array));
```
|
I have a function where I am trying to reach the last index of the file contents. When i use descriptors and lseek combination as given below, things work normally:
```
offset = lseek(infd, 0, SEEK_END);
```
results in offset: 39 (which byte size of the file)
infd is 3
```
offset = fseek(file1, 0, SEEK_END);
```
results in offset 0
file1 is pointing to 0x00007fff8897e320
Why is the offset resulting in 0 when I try to use a file pointer to the same?
Note:offset is of type off_t
|
You are usingfseek, if you read thedocumentationyou can find:
Return valueβ0β upon success, nonzero value otherwise.
On the other hand,lseekdocumentationreads:
Return valueUpon successful completion, lseek() returns the resulting offset
location as measured in bytes from the beginning of the file.
Hope this clears thing up, and next time I really advise you to read the reference and check for return value section!
|
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 perfectly know that .exe files are not executable under Linux but I need some files to be converted in .exe. Is there a way?
|
You cancross-compileyour source files with special compilers : they are runnable on one platform, but produce executables for another.
|
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 perfectly know that .exe files are not executable under Linux but I need some files to be converted in .exe. Is there a way?
|
You cancross-compileyour source files with special compilers : they are runnable on one platform, but produce executables for another.
|
How can I work with the structure if i pass structure like parameter function ** ?
```
typedef struct TQueue
{
...
int m_Len;
}TQUEUE;
void nahraj(TQUEUE **tmp)
{
tmp[5]->m_Len = 7;
}
int main (void)
{
TQUEUE *tmp;
tmp = malloc(10*sizeof(*tmp));
nahraj (&tmp);
printf("%d\n",tmp[5].m_Len);
}
```
|
You need to dereferencetmpbefore indexing it, since it's a pointer to an array, not an array itself.
And the elements of the array are structures, not pointers to structures, so you use.rather than->.
```
void nahraj(TQUEUE **tmp)
{
(*tmp)[5].m_Len = 7;
}
```
|
I was trying to find out what would be best practice.
Suppose I have a C-function
void myfunc(double);
and I store this function prototype in myfunc.h
I write the function definitions in myfunc.c
```
void myfunc(double p){
/*
* Do work
*/
}
```
Should I #include "myfunc.h" in myfunc.c?
It isn't necessary but it would seem to me to be better practice.
|
Yes you should because it makes sure that the function signature is the same in the declaration and the definition. If they don't match the program won't compile. It is also a good idea to includemyfunc.hbefore any other include file inmyfunc.c. That way you will know that the header file is self-contained.
|
How can I use amax_sizevariable to get only the desired characters?.
```
int max_size=64;
sscanf(p,"%s %(MAX_SIZE-1)[^\n]",a,b);
```
|
Withsscanf, you would have to first prepare the formatting string. Something along:
```
char *fmt;
int r = asprintf(&fmt, "%%s %%%u[^\n]", (unsigned)MAX_SIZE - 1);
if (r < 0) abort();
sscanf(p, fmt, a, b);
free(fmt);
```
The sad part about such solution is that compiler stops warning you about invalid specifiers.
|
I'm doing an exercise for my college and I am somewhat lost on pointers.
The whole exercise is telling us to make a functionchar *mystrcpy(char *dest, char *src). So what we need is to make an already included in <string.h> by ourselves.
It's not that hard as for the logical steps of the function, but i don't get why we need to use the functionchar *mystrcpy()as a pointer. Also how do we use functions as pointers and why?
|
You don't need a pointer to function but a function that return a pointer.
like :
```
char* strcpy(char* destination, const char* source);
```
that return a pointer to destination.
|
Consider this short code:
```
#include <stdio.h>
int main(){
short s[] = {0xAB, 0xCD};
printf("%x\n", *(char*)s);
printf("%x\n", *((char*)s+1));
}
```
I thought casting s to char* would allow me to step bytewise through the array, producing the output
```
a
b
```
But instead I get this:
```
ffffffab
0
```
Can someone explain this to me? I'm running gcc 4.8.1 on x64.
|
Use the correct printf format if you want one byte.
```
short s[] = {0xAB, 0xCD};
printf("%hhx\n", *(unsigned char*)s);
printf("%hhx\n", *((unsigned char*)s+1));
printf("%hhx\n", *((unsigned char*)s+2));
printf("%hhx\n", *((unsigned char*)s+3));
```
Then you will see the correct outputab 0 cd 0. It will also indicate that your system is little endian.https://en.wikipedia.org/wiki/Endianness
|
I have this small function that read words from a file:
```
bool load(const char *dictionary)
{
FILE *fp = fopen(dictionary,"r");
//defined LENGTH = 45;
char *word = malloc(LENGTH + 1);
while(fscanf(fp,"%s[\n]",word) != EOF)
{
//do ... thing in here
}
free(word);
return true;
}
```
Willfscanfcause memory leak by continuously reassigningword?
|
No, this will not cause a memory leak in the way you suggest.fscanfdoes not reassignword, but rather modifies itscontents. You may wish to think of it in terms of:fscanfdoesn't changeword, but does changeword[0],word[1], etc.
After a call tofscanf,wordwill still point to the samelocationin memory (i.e. whatever you got frommalloc), but the data at that location will be different.
|
I'm doing an exercise for my college and I am somewhat lost on pointers.
The whole exercise is telling us to make a functionchar *mystrcpy(char *dest, char *src). So what we need is to make an already included in <string.h> by ourselves.
It's not that hard as for the logical steps of the function, but i don't get why we need to use the functionchar *mystrcpy()as a pointer. Also how do we use functions as pointers and why?
|
You don't need a pointer to function but a function that return a pointer.
like :
```
char* strcpy(char* destination, const char* source);
```
that return a pointer to destination.
|
Consider this short code:
```
#include <stdio.h>
int main(){
short s[] = {0xAB, 0xCD};
printf("%x\n", *(char*)s);
printf("%x\n", *((char*)s+1));
}
```
I thought casting s to char* would allow me to step bytewise through the array, producing the output
```
a
b
```
But instead I get this:
```
ffffffab
0
```
Can someone explain this to me? I'm running gcc 4.8.1 on x64.
|
Use the correct printf format if you want one byte.
```
short s[] = {0xAB, 0xCD};
printf("%hhx\n", *(unsigned char*)s);
printf("%hhx\n", *((unsigned char*)s+1));
printf("%hhx\n", *((unsigned char*)s+2));
printf("%hhx\n", *((unsigned char*)s+3));
```
Then you will see the correct outputab 0 cd 0. It will also indicate that your system is little endian.https://en.wikipedia.org/wiki/Endianness
|
I have been trying to write a file from memory in C, more specifically an executable file. Every time I try to usefputsit detects a '00' in memory after a bit and stops writing. But there is still the rest of the file that it has to write. In the file that I am trying to write there are '00's all over the place for padding. I have some code below for reference:
```
char *buffer;
buffer = malloc(size);
// ...
FILE *file;
file = fopen("somename","w");
fputs(buffer,file);
fclose(file);
```
Is there any way I would be able to have '00's in memory withoutfputstaking it as an EOF?Thanks!
|
you should use 'fwrite' take the place of fpus
|
I have a project where we are supposed to find a sha256 from another sha256.
For example we have
```
hash1 = "45f1bc22c29626c6db37d483273afbe0f6c434de02fe86229d50c9e71ed144fc"
```
and we would have to find
```
hash0 = "5495a885b7f445a198cc5b67a517a0e0536792ab3e7ead18a12c75f8310a9b89"
```
hash1is just thehash0used in a sha256 function.
Initially, I went on to redo every possibility of sha256 but it may do a lot and take a lot of time.
If you have any idea how I could do this, even see if it's possible?
|
It's impossible, hashes can't be inverted, regardless if they're hashes of hashes or of other content. You could try all the combinations, sure, knowing that the source is a 256-bit sequence, but this is practically prohibitive, although there's always a possibility of 1 out of 2^256 that you guess it at the first try :-)
|
```
#include <cs50.h>
#include <stdio.h>
int main(void)
{
// TODO: Prompt for start size
int n,m,y,b,a;
do{
n= get_int("Start Size");
}
while(n <9);
// TODO: Prompt for end size
do
{
m = get_int("End Size");
}
while(n > m);
// TODO: Calculate number of years until we reach threshold
for (y=0;n>m;y++)
{
a = n/3;
b = n/4;
y= n + a-b;
}
// TODO: Print number of years
{
printf("Years:%i\n",y);
}
}
```
Please can you tell me why I get this error (variables 'n' and 'm' used in loop condition not modified in loop body)?
|
The condition to end the loop doesn't depend on anything that changes inside the loop. So the loop will either never execute or will execute forever.
|
I am trying to undertand how this code works, specifically the linemsk = ~(uint64_t) 0 << (uint64_t)(high - low + 1);
I really only am curious whatuint64_tis calling/doing. Not so much the bit operations
Thanks for any insight!
```
uint64_t clearBits(unsigned low, unsigned high, uint64_t source){
uint64_t msk;
assert(high < 64 && (low <= high));
msk = ~(uint64_t) 0 << (uint64_t)(high - low + 1);
return source & msk;
}
```
|
uint64_tis an integer type.uint64_t msk;declares a variable of that type and(uint64_t) 0casts0to that type since the literal0is anint. Similarly,(uint64_t)(high - low + 1)casts the result of a calculation to the typeuint64_t. However, this second cast is unnecessary, as discussed in the comments since the type of the result of<<only depends on the type of the first operand and not the second.
|
This question already has answers here:Get a substring of a char* [duplicate](5 answers)Copying a part of a string (substring) in C(13 answers)Closed2 years ago.
I am trying to parse data from the user. I need to get a certain number from the user.
And I do not mean like with strstr(). I mean more like characters 9-12 in an array.
For example:
```
char array[15] = "asdfghjkbruhqw";
^--^
```
I cannot figure out a way to do this. Any help would be appreciated.
|
Use strcnpcy, in the second parameter you pass the starting position:
```
char array[15] = "asdfghjkbruhqw";
char dest[10] = "";
strncpy(dest, &arr[9], 3);
```
|
How do I convert this array with ASCII numbers to text, so every number get's a letter. So "72" gets H, 101 gets E and so on.
int a[] = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100};
|
You can iterate over the array, and use the%cformating parameter to print the ascii characters of the int value
```
for (int i = 0 ; i < 11; i ++){
printf("%c", a[i]);
}
```
|
I am trying to undertand how this code works, specifically the linemsk = ~(uint64_t) 0 << (uint64_t)(high - low + 1);
I really only am curious whatuint64_tis calling/doing. Not so much the bit operations
Thanks for any insight!
```
uint64_t clearBits(unsigned low, unsigned high, uint64_t source){
uint64_t msk;
assert(high < 64 && (low <= high));
msk = ~(uint64_t) 0 << (uint64_t)(high - low + 1);
return source & msk;
}
```
|
uint64_tis an integer type.uint64_t msk;declares a variable of that type and(uint64_t) 0casts0to that type since the literal0is anint. Similarly,(uint64_t)(high - low + 1)casts the result of a calculation to the typeuint64_t. However, this second cast is unnecessary, as discussed in the comments since the type of the result of<<only depends on the type of the first operand and not the second.
|
This question already has answers here:Get a substring of a char* [duplicate](5 answers)Copying a part of a string (substring) in C(13 answers)Closed2 years ago.
I am trying to parse data from the user. I need to get a certain number from the user.
And I do not mean like with strstr(). I mean more like characters 9-12 in an array.
For example:
```
char array[15] = "asdfghjkbruhqw";
^--^
```
I cannot figure out a way to do this. Any help would be appreciated.
|
Use strcnpcy, in the second parameter you pass the starting position:
```
char array[15] = "asdfghjkbruhqw";
char dest[10] = "";
strncpy(dest, &arr[9], 3);
```
|
Why doesn't gcc give any warnings about this code?
```
#include <stdio.h>
void printDigits(int *arr, int arrsize);
int main() {
int number[] = { 1, 7, 8, 3, 6, 5, 4, 2 };
size_t arraysize = (sizeof(number) / sizeof(number[0]));
printDigits(number, arraysize);
return 0;
}
void printDigits(int *arr, int arrsize) {
int i;
for (i=0; i<arrsize, i++;) {
printf("%d ", arr[i]);
}
}
```
Specifically about the for loop in printDigits function. It's:for(i=0; i<arrsize, i++;)while it really should befor(i=0; i<arrsize; i++)
Gcc didn't give me any warnings and it took me a while to figure out why doesn't the array print out.
|
There is a warning.i<arrsizeis computed but then discarded, so gcc warns:
```
warning: left-hand operand of comma expression has no effect [-Wunused-value]
```
(Which is enabled by-Wall)
|
The following code doesn't run. Can I say increment/decrement operators won't work on functions with return type int?
```
int main()
{
char x[] = {"test"};
int size = strlen(x); //works :)
int size2 = --strlen(x); //doesn't work
return 0;
}
```
Error is:
```
error: lvalue required as decrement operand
9 | int size2 = --strlen(x); //doesn't work
| ^~
```
|
The prefix decrement operator--decrements the object which is the subject of the operator. The return value of a function is just that, a value and not an object. It's the same as if you tried to do--4.
If you want to assign 1 less than the length ofxtosize2, you would do it like this:
```
int size2 = strlen(x) - 1;
```
|
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 also noticed that multiples of 0.0625 such as 1.25 keep giving zero but I was unable to find an explanation
|
as per CostantinoGrana
"Do you know how IEEE 754 works? The numbers which you say "give 0"
are multiples of a not too negative negative power of 2. So when you
store them in little endian, the 32 less significant bits, that are
all 0, are the first thing you find in memory as int. Your int is 32
bits wide, thus 0."
|
In SDL, when I destroy a window withSDL_DestroyWindow, do I also need to callSDL_FreeSurfaceto release the surface that is associated with that window?
```
SDL_Window *window = SDL_CreateWindow(/*...*/);
SDL_Surface *wsurface = SDL_GetWindowSurface(window);
/*...*/
SDL_FreeSurface(wsurface); /* <- do I also need this line? */
SDL_DestroyWindow(window);
```
It isn't clear to me if the surface needs to be manually released or if it gets released automatically when I destroy the window.
|
It gets released automatically. Here is the relevantdocumentation:
A new surface will be created with the optimal format for the window, if necessary. This surface will be freed when the window is destroyed.Do not free this surface.
|
My stack_d.h file
```
#ifndef stack_d
#define stack_d
struct s {
int boyut;
int tepe;
int dizi;
};
typedef struct s* stack;
stack * init ();
int pop(stack *);
void push (int, stack *);
void bastir(stack *);
#endif
```
My stack.c file
```
#include <stdio.h>
#include <stdlib.h>
#include "stack_d.h"
stack * init(){
stack *s = (stack *) malloc(sizeof(stack));
s->dizi =NULL;
s->boyut =2;
s->tepe=0;
return s;
}
int pop(stack *s ){
if (s->tepe <= s->boyut/4){
```
I tried this s pointer with -> but my compiler says did you mean to use ->? What should I do?
|
What should I do?
Remove the pointer from thetypedef:
```
typedef struct s stack;
```
and your code should be fine. Do not use pointertypedefs, they are very confusing.
|
I've come across theiso646.hwhich provides some of the nice logical keyword operators that I'm used to from python. Is one of the following approaches preferred over the other?
```
if (x>7 && y<-2)
printf("Normal symbols\n");
```
```
#include<iso646.h>
if (x > 7 and z < 4)
printf("Iso646 is here\n");
```
Is there ever a place where one form would be preferred over the other? Or is this like thebooltype which is a nice way to replace doingint is_valid=1;?
|
As a C developer, I would be puzzled if I seeandinstead of&&. Or should it be a single&? I would need to dig into the include files to be sure how that uncommon keyword is defined.
Indeed&&is much more familiar thanandin the context of a C program.
|
I'm trying to learn C programming right now but I'm a bit stumbled upon the concept of declaring an array of pointers to functions. The statement is right here:
```
int (*menu_option[10])(char *title);
```
What exactly is happening here?
|
from thespiral rulehere
menu_optionis an array of 10function pointersthey takechar*as an argument and return anint
usehttps://cdecl.org/to parse C gibberish to English
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.