question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I wrote this C program.
```
#include<stdio.h>
int main()
{
int k=35;
printf("\n%d %d %d",k==35,k=50,k>40);
return 0;
}
```
and got this output.
0 50 0
Now, I am thinking about how the printf function worked and why the output is 0 50 0.
|
You are invoking undefined behavior by modifyingkand using its value in the same statement, before a sequence point.
Whileanyoutput is legal and valid, it is possible to understand why0 50 0happens in this case:
When a C function is called, its parameters can be evaluated inanyorder, but they areoftenevaluated in reverse order (right-most-first, left-most-last).
This isnotguaranteed, but is frequently true.
So the 4 parameters are evaluated as:
1.)k>40(false /0, becausekis 35)2.)k=50(assign 50 tok, and evaluate to 50)3.)k==35(false /0, because k is 50, which is not 35)4.)"\n%d %d %d"(string literal)
Thenprintfprints its parameters:0, 50, 0
|
This is related to a stack smash attack.
Basically, I am trying to smash the stack by giving a program a particular input. The program takes in a user input like this, usinggetchar:
```
for (i = 0; (c = getchar()) != '\n'; i++) buf[i] = c;
```
I want to overwrite memory to become0x000000a1. Unfortunately,0xa1is not an ascii character, so I cannot just input something like¡(inverted exclamation) because that ends up giving0x0000a1c2in memory. How can I overwrite the value to be just0x000000a1without changing how the user input is processed in the program?
|
You can use bash to inject arbitrary characters:
```
echo -e '\xA1' | /path/to/program
```
You can add additional input, put the echo in a loop, etc.
```
echo -e 'Something\xA1\xA1\xA1' | /path/to/program
```
|
I am population an integer stack implemented through an array with integer values, but I am getting a strange boxed output of 4 numbers.https://i.stack.imgur.com/7zWUm.pngThe values being inputted are correct, but it shows up in the bottom right corner of the box instead.
I do not believe this to be an issue with the output itself, but the input into the array.
```
void pushValStack (int stack[], int *top, int val) {
*top + = 1;
stack[*top] = val;
}
// In Main Function
for (i=1; i<argcl; i++) {
char *token = argv[i];
...
int value;
sscanf(token, "%d", &value);
pushValStack(valStack, &valCount, value);
printf("Count %d: %c \n", valCount, valStack[valCount]);
```
|
You are printing the value as a character with%c, try using%d.
Those boxes are one way to represent unprintable characters.
|
I want to verify that if the seed is same, the resulting pseudo random number is same.
Using rand() is the simplest but I'm looking for safer way.
I found that using device entropy with /dev/random of linux is very reliable but cannot find how to set exact same seed.
I also tried cryptgenrandom of window but cannot find the way to set seed.
Can I make manual seed with those random generator, which use device things?
Or is there any other random generator library which I can set manual seed?
|
Yes,<random>allows this, and it's a good idea to switch to it. C++'s<random>library isfar superiorto<stdlib>'srand()function, and allows you toset the seed each time.You should be using<random>for any production code you write.
|
Suppose I have this code :
```
typedef char BLOCK[10];
typedef struct {
BLOCK block;
}Object;
```
And I do this :
```
Object* obj;
obj = malloc(sizeof(obj));
```
My question :Will the array "block" have a default value in each of its cell ?
|
Assuming the 'error' in your code is just a typo (it should beobj = malloc(sizeof(*obj));or you will allocate enough space to hold apointer), then there is nothing in the Standard(s) to specify what the allocated data will initialized to.
If you wantdefinedinitialisation behaviour, then you can usecalloc:
```
obj = calloc(1, sizeof(*obj)); // Note: sizeof(obj) = pointer size but sizeof(*obj) is struct size
```
which will initialize all allocated bytes to zero.
|
```
#include <stdio.h>
#define abs(x) (x < 0 ? -x : x)
int x;
int doubleGlobalX()
{
x*=2;
return x;
}
int main()
{
scanf("%d",&x);//5
printf("%d\n",abs(doubleGlobalX()));//20
return 0;
}
```
When the input is5the output of this code is20. When input is15the output is60. Don't know why it doubles the global twice.
|
```
#define abs(x) (x < 0 ? -x : x)
```
Macros perform textual substitution. Defining anabs()macro like this is a well-known trap because it ends up evaluatingxtwice. If it were a function it'd be fine, but as a macro it's a problem.abs(doubleGlobalX())expands to:
```
doubleGlobalX() < 0 ? -doubleGlobalX() : doubleGlobalX()
```
It ends up callingdoubleGlobalX()twice which causesxto be doubled twice.
|
Why it prints I value as 1, can someone please explain?
```
#include<stdio.h>
int main(i)
{
printf("i = %d\n", i);
}
```
output i = 1.
|
Cis interpretingias typeint-if you don't declare a variable, its default type isint. By coincidence,mainis used to being called asint main(int argc, char **argv), so youri(which is now anint) fits into that first parameter.mainwill allow you to call it with only one argument,but this is technically undefined behavior- don't do it.
The first value,argc, is a number detailing how many command line arguments were given. (The second is the strings of those arguments.) In your case, only one command-line argument was given, that being the name of the executable (probably./a.out).
Try running your code with./a.out some strings here- you'll notice different values printing.
|
How do we add new line to output buffer using printf in C?
Like in c++ we use endl, what do we use in C?
```
cout<<endl;
```
|
You can write like this printf("whatever message you want \n")
"\n" added at the end output a new line in buffer.
|
I'm trying to port some Windows code that usesRtlIpv4StringToAddressExA/RtlIpv6StringToAddressExAandRtlIpv6AddressToStringExA/RtlIpv4AddressToStringExAto Linux and can't seem to find quite equivalent APIs. There seem to be plenty of ways to convert just the IP address to string (and back), but I can't find something that supports the port as well.
For instance, to convert[2001:4898:d8:34:b912:426d:1c88:5859]:443to an IP address from a string (and back).
To reiterate, I explicitly need an API that takesportinto consideration.
|
There is no API to do this. You have to split off the port number yourself.
Also seethis answer, which mentions that most utilities use a-p portargument instead of:portto specify the port.
If you really want something like this, it would probably be trivial to just write it yourself.
|
We've tried to beautify our code a bit with clang-format tool.
In order to get unified result on all machines we've doneclang-format --style=llvm --dump-config, which has been tuned a bit and stored into repo.
The issue is that clang 10 and 9 seem to provide us with different output for exactly the same code. I've seen changes in comments alignment only so far, but it still breaks the whole idea of getting code style consistent.
Another issue is that clang 9 is unable to parse some settings dumped from v10.
Is there any way to insure consistent formatting across multiple versions of clang-format?
|
Just in order to close the thread: it looks like you cant. Just enforce clang tools version check through build system.
|
```
#include <stdio.h>
main()
{
int t,i;
scanf("%d",&t);
check();
return 0;
}
int check()
{
char s[20];
gets(s);
printf("%s",s);
return 1;
}
```
When I run this check function, this function does not take input and immediately exits. I don't know why please tell me
|
Use a space character following the%din scanf to read in the whitepace that follows the value entered.
In other words, use:
```
scanf("%d ", &t);
```
Also note thatgetshas been deprecated for years. It is vulnerable to buffer overrun attacks. Usefgetsinstead.
Here is a fixed version of this program:
```
#include <stdio.h>
#define CHECK_BUFSIZE 19
int check()
{
char s[CHECK_BUFSIZE+1];
fgets(s, CHECK_BUFSIZE, stdin);
printf("%s",s);
}
int main()
{
int t,i;
scanf("%d ",&t);
check();
return(0);
}
```
|
I have the following array:
```
uint8_t cmd_length;
uint8_t ctr = 0;
uint8_t hdr[2] = {cmd_length, ctr};
```
Now I want to alter cmd_length, and have the change made to hdr, without having to write hdr[0] = cmd_length again. I guess this would be possible using pointers, but I don't know how.
Thanks
|
Your question leaves me with some doubts I correctly understand what you want.
My best guess is you are trying to achieve something like this:
```
int main()
{
int ctr = 0;
//replace 42 with what you want cmd_length to be
int hdr[2] = {42, ctr};
int *cmd_length = &hdr[0];
printf("%d \n",*cmd_length);
*cmd_length = 99;
printf("%d \n",hdr[0]);
return 0;
}
```
Beware cmd_length is not anintanymore but a pointer to anint(it"s type isint*). (Or uint8_t* in your case)
The output is:
```
42
99
```
|
I am building a basic C program that continuously asks users for a string input and prints out the entered input. The program is supposed to exit when a user enters a blank line. However, in my following program, even when I have a conditional that checks whether the user entered a blank line, the program still keeps on going until the user types an input. Below is my code:
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
char userString[100];
while (1 == 1) {
scanf("%s", userString);
printf("USER ENTERED %s\n", userString);
if (userString[0] == '\n') {
exit(0);
}
}
}
```
|
```
scanf("%s", userString); scanf("%s", userString);
```
scanfwith%swill read the input stream until it meets any of the whitespace. Thus newline will not be included as part ofuserString.
Usefgetsinstead.
```
fgets(userString, sizeof userString, stdin);
```
|
I'm trying to implement phy statistics reading by ethtool from a custom switch driver.
Ethtool doesn't see the phy_driver structure I declared in my driver, because it simply has an empty dev->phydev pointer in function __ethtool_get_sset_count.
I have a phydev pointer returned from MDIO bus scan, retrieved by:
```
mv_switch->phydev = (struct phy_device *)mv_switch->mii_bus->mdio_map[mv_switch->mdio_addr]
```
but can't understand how to get to the parent net_device pointer.
|
struct phy_devicehas a field calledattached_devfor that purpose, I guess... Proofhere.
So one could assume that the following would work for your use case
```
struct net_device *dev = mv_switch->phydev->attached_dev;
```
|
This is the erroneous code.
```
#include <stdio.h>
#include<stdlib.h>
int main() {
int* t = (int*) malloc(sizeof(int));
int a = 4;
t = &a;
printf("%d\n",*t);
free(t);
return 0;
}
```
How can I fix this?
|
mallocandcallocare used for dynamic memory allocation for arrays. As Blaze said in comments, just removingmallocwill solve your problem:
```
#include <stdio.h>
#include<stdlib.h>
int main() {
int* t;
int a = 4;
t = &a;
printf("%d\n",*t);
return 0;
}
```
You won't needfreeas well, because, you did not allocate dynamic memory. Moreover, if you do create dynamic memory for array, I would recommend you to usecallocovermalloc, as unlikemalloc,callocinitializes memory with zero.
|
Can anyone share me AES algorithm code with Input and Key details in C, i have checked this linkhttps://github.com/kokke/tiny-AES-c/blob/master/aes.c, but couldn't conclude as it not has the main() function.
Thanks in advance
|
Here's the proper way to call it:
```
struct AES_ctx ctx;
AES_init_ctx(&ctx, key);
for (i = 0; i < 4; ++i)
{
AES_ECB_encrypt(&ctx, plain_text + (i * 16));
phex(plain_text + (i * 16));
}
```
You may check other details in the following file from the same repository:https://github.com/kokke/tiny-AES-c/blob/master/test.c
|
Can you please tell me why the following function func1 is not getting inlined?
Code
```
#include <stdio.h>
#include <stdlib.h>
static inline int func1(int a) {
return a*2;
}
int main(int argc, char **argv) {
int value = strtol(argv[1], NULL, 0);
value = func1(value);
printf("value: %d\n", value);
return 0;
}
```
Run
```
$ gcc -Wall -o main main.c
$ objdump -D main | grep func1
0000000000000700 <func1>:
742: e8 b9 ff ff ff callq 700 <func1>
```
|
I believe it is not inlined because one is not doing optimisation, (for debugging, I assume.) Fromthe GCC online docs,
GCC does not inline any functions when not optimizing unless you specify the ‘always_inline’ attribute for the function
|
I'm sending a String from my android device to esp32, I want to store SerialBT.readString() value to a string variable, but it's stored as an empty string, what should I do?
```
if (SerialBT.available()) {
Serial.println(SerialBT.readString()); // this prints the message as well
String ts=SerialBT.readString();
Serial.println(ts); // prints nothing
```
|
Your first call toSerialBT.readString()consumes the available data. Your second call will not re-read the same string.
Remove the line:
```
Serial.println(SerialBT.readString()); // this prints the message as well
```
|
I don't have experience using Visual Studio. The university is conducting a C coding competition and forcing students to use Visual Studio. To practice I created 2 files: "to print helloworld", "finding smallest in the array". Visual studio builds ALL files and I want to create multiple files to save time and keep it ready to code but if I am working on one question and build it, all files get built. How to build one file? Please help.
|
You need to organize your code intoProjectsandSolutions. You use oneProjectper program you write and then group them in aSolution.
Se the docs here:https://learn.microsoft.com/en-us/visualstudio/ide/solutions-and-projects-in-visual-studio?view=vs-2019
|
I was recently asked this question in a programming test. I can't seem to understand why I am getting the answer '1'. I am a beginner in theCprogramming language.
Here is my code:
```
#include<stdio.h>
int main()
{
float c = 0;
int n, i = 1;
printf("Enter the number here: ");
n = getchar();
while (i <= 2*n - 1)
{
c = c + (1/i);
i = i + 2;
}
printf("%f", c);
}
```
I have already tried using aforloop, but the answer remains the same. Any help would be appreciated!
|
The problem in your code lies on this line:
```
c = c + (1/i);
```
Here, the operation performed inside the parentheses isintegerdivision! So, whenihas any value greater than1, the result will be zero. This zero is then converted to a float value.
To force the compiler to usefloating pointdivision, use this:
```
c = c + (1.0/i);
```
|
I'm trying to realize a USART2_RX on aSTM32F411VET.
During a video tutorial, I saw that the teacher use these statements to read data in data register:
```
char USART2_read(void){
while(!(USART2->SR & 0x0020)) {}
return USART2->DR;
}
```
Specifically, he uses
```
while(!(USART2->SR & 0x0020)){}
```
to wait a char. But observing theReference Manual, it seems that the status register (USART_SR) is 0x0C0... in its reset form, so...
Why we check that value (i.e., 0x0020)?
|
In thewhileloop you are waiting for the "Read data register not empty" bit to be set. This is bit number 5 and1 << 5is equal to0x0020. You could equally have written:
```
while(!(USART2->SR & (1 << 5)) {}
```
|
I'm using Visual Studio 2019 and trying to compile a program that was compatible with Windows XP 32-bit.
When I first ran my .exe on my VM it said that it wasn't compatible with Win32.
I've then changed the Platform Toolset to Visual Studio 2017 - Windows XP (v141_xp).
Now it says I'm missing a VCRUNTIME140d.dll, and following instructions that said to change my Runtime Library to /MT I get the error stated in the title.
Any suggestions would be very much appreciated.
|
VCRUNTIME140d.dll isVisual C++ Redistributable for Visual Studio 2015.You need to download and install. And this is Debug versions of DLL. You must compile in Release mode.
|
Here is a piece of my code :
And output looks like: 12, 44, 55,
I need to remove the last one ", " and i tried everything.
```
while ((r = scanf("%d", &v)) > 0){
printf("%d", v);
printf(", ");
}
```
|
Instead of printing the comma after each value, print itbeforeeach value except the first:
```
int first = 1;
while ((r = scanf("%d", &v)) > 0){
if (!first) printf(", ");
first = 0;
printf("%d", v);
}
```
|
In thisimplementation ofmemcpy_s(as well as others) the region pointed to bydestis zeroized when a runtime constraint violation occurs.
Can anyone explain why is this done? I got footguned by this a few days back and I would be interested in knowingwhythis is done.
|
This behavior is documented in section K.3.7.1.1 of theC standardas well as theMicrosoft documentation.
The reason for this most likely is to have deterministic behavior in the failure case so that you don't end up withdestcontaining uninitialized values. This allows for more robust testability.
|
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.Closed3 years ago.Improve this question
The first ScanF takes both inputs when I type a character and an integer is expected.
see image below:
As you can see when I type "55ape" for ScanNum_A it sets ScanNum_B = 0.
Why does this happen?
|
It happens becauseapeis still left in the input stream and your secondscanftries to read it but fails as it was expectingintegerbut foundchars.
You can clear the input buffer after your firstscanfas below.
```
//first scanf
int c;
while ((c = getchar()) != '\n' && c != EOF) { }
//second scanf
```
|
Here is a piece of my code :
And output looks like: 12, 44, 55,
I need to remove the last one ", " and i tried everything.
```
while ((r = scanf("%d", &v)) > 0){
printf("%d", v);
printf(", ");
}
```
|
Instead of printing the comma after each value, print itbeforeeach value except the first:
```
int first = 1;
while ((r = scanf("%d", &v)) > 0){
if (!first) printf(", ");
first = 0;
printf("%d", v);
}
```
|
In thisimplementation ofmemcpy_s(as well as others) the region pointed to bydestis zeroized when a runtime constraint violation occurs.
Can anyone explain why is this done? I got footguned by this a few days back and I would be interested in knowingwhythis is done.
|
This behavior is documented in section K.3.7.1.1 of theC standardas well as theMicrosoft documentation.
The reason for this most likely is to have deterministic behavior in the failure case so that you don't end up withdestcontaining uninitialized values. This allows for more robust testability.
|
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.Closed3 years ago.Improve this question
The first ScanF takes both inputs when I type a character and an integer is expected.
see image below:
As you can see when I type "55ape" for ScanNum_A it sets ScanNum_B = 0.
Why does this happen?
|
It happens becauseapeis still left in the input stream and your secondscanftries to read it but fails as it was expectingintegerbut foundchars.
You can clear the input buffer after your firstscanfas below.
```
//first scanf
int c;
while ((c = getchar()) != '\n' && c != EOF) { }
//second scanf
```
|
Assuming list is some structure
```
list *temp;
temp = new list;
```
the above is in c++, does this have an equivalent in C?
|
```
list *temp;
temp = malloc(sizeof(list));
[...]
free(temp);
```
C doesn't have thenewkeyword - you've got to allocate and free the memory you'd like to use manually.newalso does somework behind the scenes, like calling constructors and returning the proper pointer type -mallocdoesn't cover that, and has to be handled by the programmer.
|
This is my full code, and its printing random negative values each time I run it not sure what is wrong.
using Ubuntu to run and "gcc -Wall -Wextra test.c"
```
#include <stdio.h>
int main () {
unsigned int x = 10;
unsigned int y = 16;
unsigned int p = x + y;
printf("%d\n", &p);
return 0;
}
```
|
You are passing the address ofp. You need to pass the value.
```
printf("%d\n", p);
```
As you have it, your code is printing the address ofp, whatever that happens to be.
In addition, since you are usingunsigned int, you probably want to use the%uformatter insted of%d.
|
I need to assign a pointer to an array of characters:
```
char str1[17];
char* h="hey";
str1 = h;
```
But i get this error :error C2440: '=' : cannot convert from 'char *' to 'char [17]'.
I was thinking that an array name is the same as a pointer to a character and array name is the address of the first character of the array so assigning a pointer to a char to array name would work.
I don't know why i get the error.
How can i fix it?
|
You cannot makestr1point to a different address.
What you can do is usestrncpyto copythe contentsofhintostr1.
|
I have got a question in hackerearth to check if there is an error in this printf statement.Can you tell me if there is any meaning for this line below? Here
```
str="qwertyABC"
printf("%.#s",str)
```
|
This statement will invokeundefined behaviorbecause format specification is invalid since#is not defined as a conversion specifier.
To use#as a flag, it must be placed before., which specifies the precision.
Moreover, using#as a flag, likeprintf("%#.s",str)will also invokeundefined behaviorbecause the#("alternative form") flag is not defined for the%sconversion specifier.
|
Assuming list is some structure
```
list *temp;
temp = new list;
```
the above is in c++, does this have an equivalent in C?
|
```
list *temp;
temp = malloc(sizeof(list));
[...]
free(temp);
```
C doesn't have thenewkeyword - you've got to allocate and free the memory you'd like to use manually.newalso does somework behind the scenes, like calling constructors and returning the proper pointer type -mallocdoesn't cover that, and has to be handled by the programmer.
|
This is my full code, and its printing random negative values each time I run it not sure what is wrong.
using Ubuntu to run and "gcc -Wall -Wextra test.c"
```
#include <stdio.h>
int main () {
unsigned int x = 10;
unsigned int y = 16;
unsigned int p = x + y;
printf("%d\n", &p);
return 0;
}
```
|
You are passing the address ofp. You need to pass the value.
```
printf("%d\n", p);
```
As you have it, your code is printing the address ofp, whatever that happens to be.
In addition, since you are usingunsigned int, you probably want to use the%uformatter insted of%d.
|
I need to assign a pointer to an array of characters:
```
char str1[17];
char* h="hey";
str1 = h;
```
But i get this error :error C2440: '=' : cannot convert from 'char *' to 'char [17]'.
I was thinking that an array name is the same as a pointer to a character and array name is the address of the first character of the array so assigning a pointer to a char to array name would work.
I don't know why i get the error.
How can i fix it?
|
You cannot makestr1point to a different address.
What you can do is usestrncpyto copythe contentsofhintostr1.
|
I have got a question in hackerearth to check if there is an error in this printf statement.Can you tell me if there is any meaning for this line below? Here
```
str="qwertyABC"
printf("%.#s",str)
```
|
This statement will invokeundefined behaviorbecause format specification is invalid since#is not defined as a conversion specifier.
To use#as a flag, it must be placed before., which specifies the precision.
Moreover, using#as a flag, likeprintf("%#.s",str)will also invokeundefined behaviorbecause the#("alternative form") flag is not defined for the%sconversion specifier.
|
Programming Language: C
I'm dealing with a project that requires to recode certain already made functions, while looking at theman pageof some of them to see the original prototype, I found out that some of them contain an asterisk before the name of the function like this one in thestring.hlibrarychar *strchr(const char *s, int c)What I personally understand from the asterisk is that we add it to the declaration of a variable to make it a pointer, but how comes that a function is a pointer.
|
Asterisk is a part of return type, so this function
```
char *strchr(const char *s, int c)
```
Returnschar*
Also,
```
int *c;
```
is not a "pointer variable" to int, but a variable which stores int pointer (int*)
Why is the asterisk before the variable name, rather than after the type?
|
Is there any expression possible for the syntax to include multiple headers at once, with no need to write the "#include"-expression for each file new?
Like, for example:
```
#include <stdio.h>, <stdlib.h>, <curses.h>, <string.h> /* Dummy-Expression 1. */
OR
#include <stdio.h> <stdlib.h> <curses.h> <string.h> /* Dummy-Expression 2. */
```
Question is for C AND C++.
|
No, there is no way to do this. You have to type out (or copy) each#includeto its own line, like this:
```
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
#include <string.h>
```
This applies to both C and C++.
Some of the other answers discuss creating another header file that includes each of these, but I'm not going to discuss doing that. It in general is a bad idea and causes issues like namespace pollution and the need to recompile when you change that header file.
|
In C language, I have created a program with a virtual bot so that when you start the program it introduces itself and I've given it the name Nick. When the user launches the program, it asks for the user's name and I want to write a code that if the user's name is similar to the names: Nick, Nicko, Nic, Nik or with capital letters: NICK, Nicko. Nic etc. the program will greet the user like: "Woah! I have the same name..." but when the user types another name that is not similar to Nick, the program will greet him like "Hello (user's name)...". Can you please help me? Thanks in advance!
|
You could create an array of cstrigns (something likechar dictionary[size][size]) and populate it with words you want to check against. Then iterate through it, checking if the input matches the current string.
|
Programming Language: C
I'm dealing with a project that requires to recode certain already made functions, while looking at theman pageof some of them to see the original prototype, I found out that some of them contain an asterisk before the name of the function like this one in thestring.hlibrarychar *strchr(const char *s, int c)What I personally understand from the asterisk is that we add it to the declaration of a variable to make it a pointer, but how comes that a function is a pointer.
|
Asterisk is a part of return type, so this function
```
char *strchr(const char *s, int c)
```
Returnschar*
Also,
```
int *c;
```
is not a "pointer variable" to int, but a variable which stores int pointer (int*)
Why is the asterisk before the variable name, rather than after the type?
|
Is there any expression possible for the syntax to include multiple headers at once, with no need to write the "#include"-expression for each file new?
Like, for example:
```
#include <stdio.h>, <stdlib.h>, <curses.h>, <string.h> /* Dummy-Expression 1. */
OR
#include <stdio.h> <stdlib.h> <curses.h> <string.h> /* Dummy-Expression 2. */
```
Question is for C AND C++.
|
No, there is no way to do this. You have to type out (or copy) each#includeto its own line, like this:
```
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
#include <string.h>
```
This applies to both C and C++.
Some of the other answers discuss creating another header file that includes each of these, but I'm not going to discuss doing that. It in general is a bad idea and causes issues like namespace pollution and the need to recompile when you change that header file.
|
Can somebody explains how does c process series of +-?
For instance:
```
int x = 5, y = 8;
printf("%d\n", x-+-y); /* out: 13 */
printf("%d\n", x-+-+y); /* out: 13 */
printf("%d\n", x-+-+-y); /* out: -3 */
printf("%d\n", x+-+y); /* out: -3 */
printf("%d\n", x+-+-y); /* out: 13 */
printf("%d\n", x+-+-+y); /* out: 13 */
```
P. S. I use std=c90 so answer for all standards if answer is different, please.
|
x-+-y
This is evaluated asx-(+(-y)).
x-+-+y
This is evaluated asx-(+(-(+y))).
x-+-+-y
This is evaluated asx-(+(-(+(-y)))).
x+-+y
This is evaluated asx+(-(+y)).
x+-+-y
This is evaluated asx+(-(+(-y))).
x+-+-+y
This is evaluated asx+(-(+(-(+y)))).
In this case, there are no concurrent sequences of+or-, so all+s or-s after the initial+or-are unary operators.
|
.I have a big array of coordinates that looks like this
```
triangle_t teapot_model[] = {
{
.x1=5,
.y1=10,
},
{
.x1=20,
.y1=30,
},
(keeps going)
```
How can I print all of the items in this array without knowing their position?
I want this output:
```
Output:
.x1=5 y1=10
.x1=20 .y1=30
```
|
Array in C always has a size although implicit in your case.
To simply print each element of your array, using the below code should suffice
```
int sizearray = sizeof teapot_model / sizeof *teapot_model;
for (int i = 0; i < sizearray; i++)
{
printf(".x1=%d .y1=%d\n", teapot_model[i].x1, teapot_model[i].y1);
}
```
|
I'm trying to copy a uint8_t* into an char array, the uint8_t* is non terminating but I have another uint8_t with the length of the message.
How do I copy the uint8_t* into a char array without getting segfauts.
```
uint8_t *name; //Set to something beforehand, it's part of an server STUN.
uint8 name_length; //Also set to something I just know is less than 255.
//I've tried
char nameArray[255];
memcpy(nameArray, name, name_length-1);
nameArray[name_length] = '\0';
```
Segfaults due to invalid read size
|
Because of integer promotion of the variablename_lengthat the call site ofmemcpy()is converted intoint. If the value is 0 (zero) the subtraction of 1 results in a value of -1. This is then converted intosize_twhich gives SIZE_MAX.memcpy()happily starts copying that amount but runs beyond the limit of the allowed address range.
Since the subtraction of 1 is wrong in the first place, remove it.
|
```
void ft_destroy(char ***factory);
int main()
{
char name[] = "sebastian";
char *pt1 = &name;
char **pt2 = &pt1;
char ***pt3 = &pt2;
printf("%s", ft_destroy(pt3));
return (0);
}
```
```
error: incompatible pointer types initializing 'char *' with an expression of type 'char (*)[10]'
[-Werror,-Wincompatible-pointer-types]
char *pt1 = &name;
```
|
nameis an array of 10char, which is achar [10]. So&nameis a pointer to an array ofchar, which is achar (*)[10]. Sincept1is achar *, you should assign to it a pointer to achar.
Sincenameis an array ofchar,name[0]is achar, and&name[0]is a pointer to achar. So you can dochar *pt1 = &name[0];.
If you just usename, C will automatically convert it to a pointer to its first element, so you can also dochar *ptr1 = name;.
|
Can somebody explains how does c process series of +-?
For instance:
```
int x = 5, y = 8;
printf("%d\n", x-+-y); /* out: 13 */
printf("%d\n", x-+-+y); /* out: 13 */
printf("%d\n", x-+-+-y); /* out: -3 */
printf("%d\n", x+-+y); /* out: -3 */
printf("%d\n", x+-+-y); /* out: 13 */
printf("%d\n", x+-+-+y); /* out: 13 */
```
P. S. I use std=c90 so answer for all standards if answer is different, please.
|
x-+-y
This is evaluated asx-(+(-y)).
x-+-+y
This is evaluated asx-(+(-(+y))).
x-+-+-y
This is evaluated asx-(+(-(+(-y)))).
x+-+y
This is evaluated asx+(-(+y)).
x+-+-y
This is evaluated asx+(-(+(-y))).
x+-+-+y
This is evaluated asx+(-(+(-(+y)))).
In this case, there are no concurrent sequences of+or-, so all+s or-s after the initial+or-are unary operators.
|
.I have a big array of coordinates that looks like this
```
triangle_t teapot_model[] = {
{
.x1=5,
.y1=10,
},
{
.x1=20,
.y1=30,
},
(keeps going)
```
How can I print all of the items in this array without knowing their position?
I want this output:
```
Output:
.x1=5 y1=10
.x1=20 .y1=30
```
|
Array in C always has a size although implicit in your case.
To simply print each element of your array, using the below code should suffice
```
int sizearray = sizeof teapot_model / sizeof *teapot_model;
for (int i = 0; i < sizearray; i++)
{
printf(".x1=%d .y1=%d\n", teapot_model[i].x1, teapot_model[i].y1);
}
```
|
I'm trying to copy a uint8_t* into an char array, the uint8_t* is non terminating but I have another uint8_t with the length of the message.
How do I copy the uint8_t* into a char array without getting segfauts.
```
uint8_t *name; //Set to something beforehand, it's part of an server STUN.
uint8 name_length; //Also set to something I just know is less than 255.
//I've tried
char nameArray[255];
memcpy(nameArray, name, name_length-1);
nameArray[name_length] = '\0';
```
Segfaults due to invalid read size
|
Because of integer promotion of the variablename_lengthat the call site ofmemcpy()is converted intoint. If the value is 0 (zero) the subtraction of 1 results in a value of -1. This is then converted intosize_twhich gives SIZE_MAX.memcpy()happily starts copying that amount but runs beyond the limit of the allowed address range.
Since the subtraction of 1 is wrong in the first place, remove it.
|
```
void ft_destroy(char ***factory);
int main()
{
char name[] = "sebastian";
char *pt1 = &name;
char **pt2 = &pt1;
char ***pt3 = &pt2;
printf("%s", ft_destroy(pt3));
return (0);
}
```
```
error: incompatible pointer types initializing 'char *' with an expression of type 'char (*)[10]'
[-Werror,-Wincompatible-pointer-types]
char *pt1 = &name;
```
|
nameis an array of 10char, which is achar [10]. So&nameis a pointer to an array ofchar, which is achar (*)[10]. Sincept1is achar *, you should assign to it a pointer to achar.
Sincenameis an array ofchar,name[0]is achar, and&name[0]is a pointer to achar. So you can dochar *pt1 = &name[0];.
If you just usename, C will automatically convert it to a pointer to its first element, so you can also dochar *ptr1 = name;.
|
.I have a big array of coordinates that looks like this
```
triangle_t teapot_model[] = {
{
.x1=5,
.y1=10,
},
{
.x1=20,
.y1=30,
},
(keeps going)
```
How can I print all of the items in this array without knowing their position?
I want this output:
```
Output:
.x1=5 y1=10
.x1=20 .y1=30
```
|
Array in C always has a size although implicit in your case.
To simply print each element of your array, using the below code should suffice
```
int sizearray = sizeof teapot_model / sizeof *teapot_model;
for (int i = 0; i < sizearray; i++)
{
printf(".x1=%d .y1=%d\n", teapot_model[i].x1, teapot_model[i].y1);
}
```
|
I'm trying to copy a uint8_t* into an char array, the uint8_t* is non terminating but I have another uint8_t with the length of the message.
How do I copy the uint8_t* into a char array without getting segfauts.
```
uint8_t *name; //Set to something beforehand, it's part of an server STUN.
uint8 name_length; //Also set to something I just know is less than 255.
//I've tried
char nameArray[255];
memcpy(nameArray, name, name_length-1);
nameArray[name_length] = '\0';
```
Segfaults due to invalid read size
|
Because of integer promotion of the variablename_lengthat the call site ofmemcpy()is converted intoint. If the value is 0 (zero) the subtraction of 1 results in a value of -1. This is then converted intosize_twhich gives SIZE_MAX.memcpy()happily starts copying that amount but runs beyond the limit of the allowed address range.
Since the subtraction of 1 is wrong in the first place, remove it.
|
```
void ft_destroy(char ***factory);
int main()
{
char name[] = "sebastian";
char *pt1 = &name;
char **pt2 = &pt1;
char ***pt3 = &pt2;
printf("%s", ft_destroy(pt3));
return (0);
}
```
```
error: incompatible pointer types initializing 'char *' with an expression of type 'char (*)[10]'
[-Werror,-Wincompatible-pointer-types]
char *pt1 = &name;
```
|
nameis an array of 10char, which is achar [10]. So&nameis a pointer to an array ofchar, which is achar (*)[10]. Sincept1is achar *, you should assign to it a pointer to achar.
Sincenameis an array ofchar,name[0]is achar, and&name[0]is a pointer to achar. So you can dochar *pt1 = &name[0];.
If you just usename, C will automatically convert it to a pointer to its first element, so you can also dochar *ptr1 = name;.
|
Testing some integer multiplications on x86.
```
int32_t a = 2097152;
int64_t b = a * a;
```
Why does the abovebevaluate to zero?
|
What are the int64_t range limits on x86?
C11 standard 7.20.2.1says[-2^63; 2^63-1]which is equivalent to[-9223372036854775808;9223372036854775807]You can get it by printingINT64_MAXandINT64_MIN.
Why does the above b evaluate to zero?
Because the promotion does not take place until the multiplication has been evaluated. The result ofa*ais of typeint32_tand when you overflow a signed integer you invoke undefined behavior. What you're doing is essentially this:
```
int32_t a = 2097152;
int32_t tmp = a * a;
int64_t b = tmp;
```
You can get the desired result with:
```
int32_t a = 2097152;
int64_t b = ((int64_t) a) * a;
```
The outer parenthesis is not necessary, but it is important to understand that I'm not talking about(int64_t)(a*a)which wouldn't yield the correct result.
|
in an existing code base written by someone I cannot ask anymore, I see quite some instances of casting a variable into its own type.
```
uint32_t message_id = [...];
[...]
switch ((uint32_t)message_id)
{
[...]
```
It's too many occurences to just say it's left-over from e.g. changing the type of the variable at a later point.
If I try it out in compiler explorer, the compiler generates identical assembly with-O0.
Can anyone think of a reason, the developer might have done it that way?
|
No, I cannot see any reason for that. You should remove them to make the code more readable.
If you want to explicitly document the type of a variable at some point of usage (like Morten suggested in the comment) you could add a comment instead.
|
I would like to execute this command in a C/C++ program:stat -c "%F %A %n" *filename goes here*The filename is stored in themainfunction'sargv[1].
I tried it asexecl("/bin/stat", "stat", "-c", "\"%F %A %n\"", "file", NULL);
How should theexecl()command look like to achieve the result?
|
Your command should look like this:
```
int res = execl("/bin/stat", "stat", "-c", "\"%F %A %n\"", argv[1], NULL);
if (res == -1) {
perror("/bin/stat");
exit(1);
}
```
Then the perror would show you:
```
/bin/stat: No such file or directory
```
and you would realize that stat is in /usr/bin or that using execlp would have been a good idea.
|
I have understood everything I think.
I have not included the rest of the code, but the problem to solve is basically checking all letters and then swap the letters bynplaces.
For example'B'becomes'G'ifnis 5.
As I understand it uses ASCII table values so the code below becomes:(65 + ((66 - 65 + 5)) % 26)
```
character = (char)('a' + ((character - 'a' + n)) % 26);
```
What I don't understand is how the modulus% 26makes the "reset" to start the alphabet over again. If someone were able to explain this in some easy way I would be grateful.
|
The%C operator yields the remainder of the integer division.
For instance:
```
24 % 26 == 24
25 % 26 == 25
26 % 26 == 0
27 % 26 == 1
```
And so on.
Therefore, your example:
```
65 + (66 - 65 + 5) % 26 == 65 + 6 % 26 == 65 + 6 == 71
```
The remainder is there in case you have lowercase letters, which have a higher code point.
|
Is there a more concise way to rewrite the following function without sacrificing clarity?
```
function uint64_t pop_int(uint8_t** p, int num_bytes)
{
uint64_t res = decode_int(*p, num_bytes);
*p += num_bytes;
return res;
}
```
All I can think of is something like
```
return decode_int((*p += num_bytes) - num_bytes, num_bytes);
```
but it would be clearer if the language had something like aFIRSTfunction that you could use like this:
```
return FIRST(decode_int(*p, num_bytes), *p += num_bytes);
```
but it would have to be clear that the arguments are evaluated in order.
|
In C, what you wrote is the idiomatic code for solving the task.
In languages with try-finally you could use that, and it may or may not be clearer. But C doesn't have this feature.
|
I have understood everything I think.
I have not included the rest of the code, but the problem to solve is basically checking all letters and then swap the letters bynplaces.
For example'B'becomes'G'ifnis 5.
As I understand it uses ASCII table values so the code below becomes:(65 + ((66 - 65 + 5)) % 26)
```
character = (char)('a' + ((character - 'a' + n)) % 26);
```
What I don't understand is how the modulus% 26makes the "reset" to start the alphabet over again. If someone were able to explain this in some easy way I would be grateful.
|
The%C operator yields the remainder of the integer division.
For instance:
```
24 % 26 == 24
25 % 26 == 25
26 % 26 == 0
27 % 26 == 1
```
And so on.
Therefore, your example:
```
65 + (66 - 65 + 5) % 26 == 65 + 6 % 26 == 65 + 6 == 71
```
The remainder is there in case you have lowercase letters, which have a higher code point.
|
Is there a more concise way to rewrite the following function without sacrificing clarity?
```
function uint64_t pop_int(uint8_t** p, int num_bytes)
{
uint64_t res = decode_int(*p, num_bytes);
*p += num_bytes;
return res;
}
```
All I can think of is something like
```
return decode_int((*p += num_bytes) - num_bytes, num_bytes);
```
but it would be clearer if the language had something like aFIRSTfunction that you could use like this:
```
return FIRST(decode_int(*p, num_bytes), *p += num_bytes);
```
but it would have to be clear that the arguments are evaluated in order.
|
In C, what you wrote is the idiomatic code for solving the task.
In languages with try-finally you could use that, and it may or may not be clearer. But C doesn't have this feature.
|
Mismatched comparsion when a definition EUSART_BUFFER_SIZE is compared with a variable eusart_rx_buffer_rd of type uint8_t. But if the type of the variable is changed to uint16_t the warning is gone. Why?
```
#define EUSART_BUFFER_SIZE 256
uint8_t eusart_rx_buffer_rd = 0;
if (eusart_rx_buffer_rd >= EUSART_BUFFER_SIZE)
{
eusart_rx_buffer_rd = 0;
}
```
|
The implicit type of the literal constant 256 isint, so you are comparing anintwith auint8_t.
The comparison itself causes an implicit promotion toint, but is in any casealwaysfalse since 256 is not representable by auint8_t.
It is not clear what the appropriate solution might be, but if all values of theuint8_tvariable are valid, the test serves no purpose, and a naive change to a larger type may in fact introduce bugs by allowing invalid values to be assigned.
|
In Linux, dmidecode source code:
https://github.com/mirror/dmidecode/blob/master/dmidecode.c#L273
I see this:
```
static void dmi_print_memory_size(u64 code, int shift)
{
...
split[0] = code.l & 0x3FFUL;
split[1] = (code.l >> 10) & 0x3FFUL;
split[2] = (code.l >> 20) & 0x3FFUL;
split[3] = ((code.h << 2) & 0x3FCUL) | (code.l >> 30);
split[4] = (code.h >> 8) & 0x3FFUL;
split[5] = (code.h >> 18) & 0x3FFUL;
split[6] = code.h >> 28;
```
'code' is a u64 variable, why it has member .l and .h? and what are they for?
|
The u64 type is defined intypes.h:
```
#ifdef BIGENDIAN
typedef struct {
u32 h;
u32 l;
} u64;
#else
typedef struct {
u32 l;
u32 h;
} u64;
#endif
```
So it appears that the.land.hmembers represent the "low" and "high" 32 bits of a 64-bit number.
|
I read themanpage offgets(). It states "Reading stops after an EOF or a newline". My code is as follows.
```
#include <stdio.h>
#define MAX 50
int main()
{
char buf[MAX];
fgets(buf, MAX, stdin);
printf("string is: %s\n", buf);
return 0;
}
```
I gave this input :Welcome to -1 kkWorld.Output is: string is: Welcome to -1 kkWorldfgetsshould stop reading when it sees -1 in the input. Why is fgets reading even though there is -1 or EOF in the string? Am I missing something here? Please help.
|
As stated by Adrian, inputing "-1" ends up being two characters; '-' and '1'. To emulate an EOF character, you must enter the single EOF value constant.
EOF can be input to the program withCtrl-D(Unix/Linux), orCTRL-Z(Microsoft).
|
When compiling the following code on CodeBlocks it shows me "Hello, world", the returned value and the execution time, but when I compile it on Atom or on terminal with "gcc code.c" and running the executable, it only prints "Hello, world".
How can I get the returned value and the execution time?
```
#include <stdio.h>
int main() {
printf("Hello, world");
return 0;
}
```
I am getting this
I expect to get this instead (like I do with CodeBlocks)
|
The only output command in your code is:
```
printf("Hello, world");
```
There is no command (function call) to calculate or output the execution time. When you run your program from within the IDE / debugger, it's the IDE / debugger itself which give you that information. It isnotpart of the output of your program.
If you'd like to have that output, you would have to add code to measure and output the execution time yourself.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed3 years ago.Improve this question
Examplechar fi= 'a';.
What do we call it here: apostrophe or single inverted comma?
|
In code it’s called asingle quote(C 2018 6.4.4.4 3) to contrast it withdouble quotes(").
“Apostrophe” and “inverted comma” are typographical terms commonly used in regard to English text. Neither is used in a programming context.
|
I have a struct
```
typedef struct {
char name[100];
int born_date;
}patient;
```
I have to write a function that will be sorting this array by born date.
The function look likevoid rendez(patient patients[], int n) {}Where the n number is the array length & patients[] array include the data about the patients.
I know this not a hard task but I learning this language still (C).
I can use the qsort function but this is new for me.
I listen every tipps & thanks for helping
|
qsort works with a user-defind compare. You will need a helper function to compare 2 items
```
int compare_patient_dob(void *a, void *b)
{
patient *pa = (patient *) a ;
patient *pb = (patient *) b ;
// Assuming born_dates are comparable, e.g., YYYYMMDD
return pa->born_date - pb->born_date ;
}
...
// Later in the rendez function.
qsort(patients, n, sizeof(patients[0], compare_patient_dob) ;
```
|
A simple question that I cannot seem to find. When I am compiling a program with gcc my professor tells me to have -g and -o when I am compiling it and I am not too sure why. I could not find it in the man pages of gcc with there being so much on there.
For example...
```
gcc -g -o myprogram myprogram.c
```
|
-gmeans to include debugging information, which enables a debugger to know where a named object (variable) is in the memory or registers of the executing process and to know which instructions correspond to which lines of source code.
-o myprogramsays to put the output file inmyprogram. (If you do not specify-owith a file name, GCC defaults to putting the output in a file nameda.out.)
|
```
# include <stdio.h>
int main()
{
char p[]={0x01,0x02,0x03,0x04};
int *q = p;
printf("%x",*q);
return 0;
}
```
When I run the above code, the answer is 4030201. Why?
|
It is because you compile and run your code on little-endian architecture machine (x86 for example)
At first you put 4 bytes in memory in order:01 02 03 04. Than convert pointer to this array to pointer to int. On little-endian machine memory block01 02 03 04represents integer value 0x04030201 which is printed on next step.
Seehttps://en.m.wikipedia.org/wiki/Endiannessfor more information
|
I'm trying to save 4 characters in one unsigned int using bitwise operator. However, it just skips scanf and prints next message. Here's my code:
```
printf("1st: ");
scanf("%c", &a);
printf("2nd: ");
scanf("%c", &b);
printf("3rd: ");
scanf("%c", &c);
printf("4th: ");
scanf("%c", &d);
num = a;
num |= b << 8;
num |= c << 16;
num |= d << 24;
printf("result: %x\n", num);
```
I expected the output of
```
1st: a
2nd: b
3rd: c
4th: d
result: 64636261
```
but actual output was
```
1st: a
2nd: 3rd: b
4th: result: a620a61
```
How can I solve this?
|
PressingEnterkey is also considered a new character or\n. That's whybgoes tocinstead.
|
I'm trying to write a program in C that copies its input to its output while replacing each string of one or more Spaces with a single Space.
My code isn't doing that but is instead taking away every second character.
This is my code:
```
#include <stdio.h>
main()
{
int c;
int lastc;
lastc = 0;
while(getchar() != EOF){
c = getchar();
if(c == 32 && lastc == 32)
;
else
putchar(c);
lastc = c;
}
}
```
|
Your loop should look like:
```
while((c = getchar()) != EOF){
if(c == 32 && lastc == 32)
;
else
putchar(c);
lastc = c;
}
```
In your version you get a char with getchar while checking the condition for the while loop and then as a next step you again get a char with getchar. So the first one is not used in your code. Therefore it is taking away every second character.
|
I'm trying to compile a C library of mine for WebAssembly, using clang (no emscripten), and it compiles fine withclangversion8.0.1, but fails withclangversion9.0.0. The reported error iswasm-ld: error: ….o: undefined symbol: __heap_base. Has__heap_basebeen replaced with some other symbol?
The library is open source and compilation instructions can be foundhere
|
Actually, I believe I found the culprit: the linker in9.0.0seems to require the--export=__heap_base(-Wl,--export=__heap_basefor theclang). This works for my project.
|
```
int op_type(const char *input, int op_pos)
{
int category;
if (input[op_pos] == '+')
category = 1;
if (input[op_pos] == '*')
category = 2;
if (input[op_pos] == '/')
category = 3;
if (input[op_pos] == '^')
category = 4;
return category;
}
```
This function will be used for doing basic math.
|
Theoretically the answer should be:
```
int op_type(const char *input, int op_pos)
{
int category;
switch (input[op_pos]){
case '+':
category = 1;
break;
case '*':
category = 2;
break;
case '/':
category = 3;
break;
case '^':
category = 4;
break;
}
return category;
}
```
Hope this answered your question.
|
This question already has answers here:How do you convert a byte array to a hexadecimal string in C?(19 answers)Closed3 years ago.
I have a given simple code snippet that is supposed to generate a 128-bit encryption key. How do I print out the values to the console?
Here's the code:
```
#include <stdio.h>
#include <stdlib.h>
#define LEN 16 // 128 bits
void main()
{
unsigned char *key = (unsigned char *) malloc(sizeof(unsigned char)*LEN);
FILE* random = fopen("/dev/urandom", "r");
fread(key, sizeof(unsigned char)*LEN, 1, random);
fclose(random);
}
```
To be more specific: the instructions say: "Print out the numbers."
|
Generating human readable binary data will usually involve hex or base64. Assuming hex code is acceptable:
```
for (int i=0 ; i<LEN ; i++ ) {
printf("%02x", key[i]) ;
} ;
printf("\n") ;
```
|
I want to check if the last character of my string is equal to a "#", and delete it if it is. However, I am unable to do a comparison. What is wrong with my code?
```
char* involved_node_string(int shared_val, int values[], int directions[]){;
char involved_nodes[1024] = {};
char *p = involved_nodes;
char result[1024];
int k;
for (k = 0; k < 4; k++){
if (values[k] == shared_val){
sprintf(result, "%d", directions[k]);
strcat(involved_nodes, result);
strcat(involved_nodes, "#");
}
}
char v = p[strlen(p)-1];
if (v == "#"){
printf("Yes\n");
}
return p;
}
```
|
Could the issue be that you are comparing achar(v) to a string-literal ("#")? Maybe try using the expression(v == '#')(using single quotes instead of double quotes to denote achar) and see if that works?
|
```
int op_type(const char *input, int op_pos)
{
int category;
if (input[op_pos] == '+')
category = 1;
if (input[op_pos] == '*')
category = 2;
if (input[op_pos] == '/')
category = 3;
if (input[op_pos] == '^')
category = 4;
return category;
}
```
This function will be used for doing basic math.
|
Theoretically the answer should be:
```
int op_type(const char *input, int op_pos)
{
int category;
switch (input[op_pos]){
case '+':
category = 1;
break;
case '*':
category = 2;
break;
case '/':
category = 3;
break;
case '^':
category = 4;
break;
}
return category;
}
```
Hope this answered your question.
|
This question already has answers here:How do you convert a byte array to a hexadecimal string in C?(19 answers)Closed3 years ago.
I have a given simple code snippet that is supposed to generate a 128-bit encryption key. How do I print out the values to the console?
Here's the code:
```
#include <stdio.h>
#include <stdlib.h>
#define LEN 16 // 128 bits
void main()
{
unsigned char *key = (unsigned char *) malloc(sizeof(unsigned char)*LEN);
FILE* random = fopen("/dev/urandom", "r");
fread(key, sizeof(unsigned char)*LEN, 1, random);
fclose(random);
}
```
To be more specific: the instructions say: "Print out the numbers."
|
Generating human readable binary data will usually involve hex or base64. Assuming hex code is acceptable:
```
for (int i=0 ; i<LEN ; i++ ) {
printf("%02x", key[i]) ;
} ;
printf("\n") ;
```
|
I want to check if the last character of my string is equal to a "#", and delete it if it is. However, I am unable to do a comparison. What is wrong with my code?
```
char* involved_node_string(int shared_val, int values[], int directions[]){;
char involved_nodes[1024] = {};
char *p = involved_nodes;
char result[1024];
int k;
for (k = 0; k < 4; k++){
if (values[k] == shared_val){
sprintf(result, "%d", directions[k]);
strcat(involved_nodes, result);
strcat(involved_nodes, "#");
}
}
char v = p[strlen(p)-1];
if (v == "#"){
printf("Yes\n");
}
return p;
}
```
|
Could the issue be that you are comparing achar(v) to a string-literal ("#")? Maybe try using the expression(v == '#')(using single quotes instead of double quotes to denote achar) and see if that works?
|
I am trying to join a string usingstrcpyusing the following approach:
```
char * concat(char ** buffer) {
char * joined_string = malloc(50);
int offset=0;
while (*buffer) {
strcpy(joined_string+offset, *buffer++); // seg fault, how to advance offset?
offset += strlen(*buffer);
}
return joined_string;
}
```
Is there a way to keep advancing via an offset to keep writing to the string buffer? If so, how would that be done?
|
The main bug is that you're advancingoffsetby the length of thenextstring inbufferinstead of by the one you just appended.
|
The series is mixed with multicharacters as well as integer, so What will be the code to print the output?
```
#include<stdio.h>
int main(){
int fi=0;
while(fi<=26)
{
if(fi>=97||fi<=122||fi>=1)
{
printf("%c%d%c",fi);
}
fi++;
}
return 0;
}
```
I tried this code but got no output
|
Instead of usingint fi='a1z';here, you should use a counter that starts at zero and ends at 26.
You also can't useprintflike this. It's not some sort of general-purpose formatting tool like it is in some other languages, you haveoneformat string and the rest is what you want to print.
Here's probably what you want to do:
```
#include <stdio.h>
int main(void)
{
int ctr;
for(ctr = 0; ctr < 26; ctr++)
{
printf("%c%d%c\n", 'a' + ctr, ctr + 1, 'z' - ctr);
}
return 0;
}
```
|
Say theres a recursive function which runs n times and a nested for loop that runs n^2 times, what will be its time complexity O(n) or O(n^3)
For example :
```
fun(int n) {
if(n==1) return;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
printf("A");
}
```
|
the time complexity of the above function is O(n^3).
look as it as for every n, the loops s will run n(n+1)/2 times and this will take place n time. So the total number of iterations will be (n^2)(n+1)/2 which is O(n^3).
|
I am creating static library with gcc using:ar rcs libMylib.a objA.o objB.o objC.o
How to add shared libraries to the static library, in other words what is the equivalent to the-lcuda -lopencv_coreoption when creating static library?what, if any, is the equivalent togccoption-Wl,--no-undefinedwhen creating static library?
|
Static library is an archive (collection) of object files. Therefore, external symbols remain unresolved. Same as when creating a single object file.
Only when you create an executable or dynamic shared library, you'll fail (or get a warning) for unresolved symbols.
|
How to combine to send everything at once?
```
int data = 5;
int data2 = 15;
int data3 = 25;
sendto(sock, (char*)&data, sizeof data, 0, (LPSOCKADDR)&ipAddr, sizeipAddr);
sendto(sock, (char*)&data2, sizeof data2, 0, (LPSOCKADDR)&ipAddr, sizeipAddr);
sendto(sock, (char*)&data3, sizeof data3, 0, (LPSOCKADDR)&ipAddr, sizeipAddr);
```
|
You could create an array and pass the address and size of the array:
```
int data[3] = {5, 15 25};
sendto(sock, (char*)&data[0], sizeof(data), 0, (LPSOCKADDR)&ipAddr, sizeipAddr);
```
But this is very bad style for sending data over a network. You have to take byte order and variable sizes into account.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed3 years ago.Improve this question
This code does not generates an output.. please tell what is missing.. I'm new to programming.
```
int main()
{
int num;
scanf("%d", &num);
for (int i = 1; i++; i <= num)
{
int f = 0;
for (int t = 1; i++; i<i)
{
if (i%t == 0)
f++;
}
if (f == 2)
printf("%d ", &i);
}
}
```
|
youfor (int i = 1; i++; i <= num)is wrong should befor(int i = 1; i <= num; i++)(intialize var , condition, increment).
Another problem found atprintf("%d", &f)doing this you are printing address of memory.
You should be more carefull, writing you code and be a beginner dont rush it.
|
Say theres a recursive function which runs n times and a nested for loop that runs n^2 times, what will be its time complexity O(n) or O(n^3)
For example :
```
fun(int n) {
if(n==1) return;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
printf("A");
}
```
|
the time complexity of the above function is O(n^3).
look as it as for every n, the loops s will run n(n+1)/2 times and this will take place n time. So the total number of iterations will be (n^2)(n+1)/2 which is O(n^3).
|
I am creating static library with gcc using:ar rcs libMylib.a objA.o objB.o objC.o
How to add shared libraries to the static library, in other words what is the equivalent to the-lcuda -lopencv_coreoption when creating static library?what, if any, is the equivalent togccoption-Wl,--no-undefinedwhen creating static library?
|
Static library is an archive (collection) of object files. Therefore, external symbols remain unresolved. Same as when creating a single object file.
Only when you create an executable or dynamic shared library, you'll fail (or get a warning) for unresolved symbols.
|
How to combine to send everything at once?
```
int data = 5;
int data2 = 15;
int data3 = 25;
sendto(sock, (char*)&data, sizeof data, 0, (LPSOCKADDR)&ipAddr, sizeipAddr);
sendto(sock, (char*)&data2, sizeof data2, 0, (LPSOCKADDR)&ipAddr, sizeipAddr);
sendto(sock, (char*)&data3, sizeof data3, 0, (LPSOCKADDR)&ipAddr, sizeipAddr);
```
|
You could create an array and pass the address and size of the array:
```
int data[3] = {5, 15 25};
sendto(sock, (char*)&data[0], sizeof(data), 0, (LPSOCKADDR)&ipAddr, sizeipAddr);
```
But this is very bad style for sending data over a network. You have to take byte order and variable sizes into account.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed3 years ago.Improve this question
This code does not generates an output.. please tell what is missing.. I'm new to programming.
```
int main()
{
int num;
scanf("%d", &num);
for (int i = 1; i++; i <= num)
{
int f = 0;
for (int t = 1; i++; i<i)
{
if (i%t == 0)
f++;
}
if (f == 2)
printf("%d ", &i);
}
}
```
|
youfor (int i = 1; i++; i <= num)is wrong should befor(int i = 1; i <= num; i++)(intialize var , condition, increment).
Another problem found atprintf("%d", &f)doing this you are printing address of memory.
You should be more carefull, writing you code and be a beginner dont rush it.
|
Im trying to print out a format of lets say x levels of accuracy meaning it should print if x = 10
```
float foo;
printf("levels of accuracy %.10f", foo);
```
What i've tried:
I already have the math to convert the x to the desired decimal place.
something like..
```
int multiplier = 10;
float initialaccuracy = 1.0;
float threshold = initialaccuracy / ((float)(pow(multiplier, accuracy)));
```
What I want to know:
How do i use the format of that x into the printf so if i pick x= 4 it would be %.4f or if i pick 15 it would be %.15f, without hardcoding those values just using it of whatever i pass in?
|
You can put a*in place of the precision specifier and pass it as a separate parameter:
```
int accuracy = 10;
printf("levels of accuracy %.*f", accuracy, foo);
```
|
I have a binary number of 01000001
I would like to add 4 parity numbers to that binary code.
I have an array of 8 bits unsigned char arr[8];
each index has digit of the bit
ex:
arr[0] = 0
Using hammingcode so it should be 12 digits with the parity (8 + 4parity)
p[0] = sequence[10] + sequence[8] + sequence[6] + sequence[4] + sequence[2]
```
What i'm getting is 1110 and it should be 1001 for parity
```
|
I don't know what language you're using but it seems to use 0-based array indexing.
However, you are indexingarrfromarr[1]toarr[8].
|
I'm trying to convert ASCII strings into Binary so i can add Parity to it (Hamming Code). But the output is not right at all.
If i enter 'A' on the input it should return:
01000001
and i've tried it with 'B' but it doesn't return that
```
unsigned char bits[8];
for(int i = 8; i >= 1; i--){
```
i expect the output to be 01000001 for 'A'
but the actual output is 00100000
Same for ABC or B or C
|
iis off by one, so you are accessing elementsbitC[8]tobitC[1](even thoughbitC[8]is out of bounds), and you are printing bits 8 to 1 instead of bits 7 to 0.
Replace
```
for(int i = 8; i >= 1; i--){
```
with
```
for(int i = 8; i--; ){
```
|
I have the following:
```
//h.h file
#pragma once
struct A { int x; };
//a.c file
#include "h.h"
struct A* a;
//b.c
#include "h.h"
extern struct A* const a;
int main() {}
```
I added an extraconstonexterndeclaration. Adding thisconstwould be UB?
If It's not UB, doing like below insidemainwould be UB?
```
(*(struct A**)&a) = malloc(sizeof(struct A));
```
|
Yes. From Annex J.2:
Two declarations of the same object or function specify types that are not compatible (6.2.7).
And 6.2.7 ¶2:
All declarations that refer to the same object or function shall have compatible type; otherwise, the behavior is undefined.
And 6.7.3 ¶10:
For two qualified types to be compatible, both shall have the identically qualified version of a compatible type; the order of type qualifiers within a list of specifiers or qualifiers does not affect the specified type.
|
Im trying to print out a format of lets say x levels of accuracy meaning it should print if x = 10
```
float foo;
printf("levels of accuracy %.10f", foo);
```
What i've tried:
I already have the math to convert the x to the desired decimal place.
something like..
```
int multiplier = 10;
float initialaccuracy = 1.0;
float threshold = initialaccuracy / ((float)(pow(multiplier, accuracy)));
```
What I want to know:
How do i use the format of that x into the printf so if i pick x= 4 it would be %.4f or if i pick 15 it would be %.15f, without hardcoding those values just using it of whatever i pass in?
|
You can put a*in place of the precision specifier and pass it as a separate parameter:
```
int accuracy = 10;
printf("levels of accuracy %.*f", accuracy, foo);
```
|
I have a binary number of 01000001
I would like to add 4 parity numbers to that binary code.
I have an array of 8 bits unsigned char arr[8];
each index has digit of the bit
ex:
arr[0] = 0
Using hammingcode so it should be 12 digits with the parity (8 + 4parity)
p[0] = sequence[10] + sequence[8] + sequence[6] + sequence[4] + sequence[2]
```
What i'm getting is 1110 and it should be 1001 for parity
```
|
I don't know what language you're using but it seems to use 0-based array indexing.
However, you are indexingarrfromarr[1]toarr[8].
|
I'm trying to convert ASCII strings into Binary so i can add Parity to it (Hamming Code). But the output is not right at all.
If i enter 'A' on the input it should return:
01000001
and i've tried it with 'B' but it doesn't return that
```
unsigned char bits[8];
for(int i = 8; i >= 1; i--){
```
i expect the output to be 01000001 for 'A'
but the actual output is 00100000
Same for ABC or B or C
|
iis off by one, so you are accessing elementsbitC[8]tobitC[1](even thoughbitC[8]is out of bounds), and you are printing bits 8 to 1 instead of bits 7 to 0.
Replace
```
for(int i = 8; i >= 1; i--){
```
with
```
for(int i = 8; i--; ){
```
|
I want to store a bunch of strings, but I'm having trouble on how to store them. And after that I want to print them but later on in the program, not after I input them.
```
#include <stdio.h>
int main() {
int total_people, i;
char name[total_people][20];
scanf("%d", &total_people);
for(i = 0; i < total_people; i++) {
scanf("%[^\n]", name[i][0]);
}
for(i = 0; i < total_people; i++) {
printf("%s", name[i][0]);
}
return 0;
}
```
I tried inputting3and I got a runtime error.
|
name[i][0]is the firstcharacterof the arrayname[i]. You need apointerto that first character, which you can get with the address-operator&as in&name[i][0].
Or since array naturally decays to pointers to their first element, justname[i].
|
I was writing a program that involvesmallocto create a global array. I tried this (outsidemain(), of course):
```
int *arr=malloc(5*sizeof(int));
```
In the GCC compiler, the following error is flashed:
```
main.c:4:10: error: initializer element is not constant
int *arr=(int *)malloc(5*sizeof(int));
^
```
I tried this on Dev-C++, but no such error interrupted the compilation.
What is meant by the error and why is it specific to GCC?
|
Variables declared at file scope must have initializers that are compile time constants. A function call is considered executable code and cannot exists outside of a function.
The best way to handle this would be to initialize the pointer to NULL and perform themallocin themainfunction.
The reason you're not seeing an error with DEV-C++ is because it is a C++ compiler and C++ allows file scope variables to be initialized with function calls.
|
At the moment I'm developing a network monitoring with the Azure Sphere Dev Kit.
I'm using the MT3620 Dev Kit from Seeed.
My problem at the moment is that I want to use ICMP packets to create something like ping but I always get the message that the "Operation is not permitted".
I have read some articles and one said that Azure VMs block ICMP traffic (seehere).
So, my question is if it is possible to creaete and send ICMP packets with the Azure Sphere Dev Kit? Does anyone have experience with that?
|
ICMP (“ping”) is not supported. You can’t ping the device, nor can it send pings. You can open a Feature request for Azure Sphere team here:https://feedback.azure.com/forums/915433-azure-sphere
|
I want to reverse a string(user gives at runtime) using array of pointers,malloc and not by using array of characters. Can anybody help me by giving me a code? I am very new to C. Thanks in advance.
|
I am not sure what you are asking, But the following program meets your conditions,
1. there is array of pointers
2. there is malloc
3. there is no character array
```
#include <stdio.h>
#include <stdlib.h>
#define STR_MAX_SIZE 256
int main()
{
char *str;
char *pos[2];
char c;
if((str = malloc(STR_MAX_SIZE)) ==NULL) {
return -1;
}
scanf("%s",str);
pos[0] = str;
pos[1] = str;
while(*pos[1]) {
pos[1]++;
}
pos[1] -= 1;
while(pos[0] < pos[1]) {
c = *pos[0];
*pos[0] = *pos[1];
*pos[1] = c;
pos[0]++;
pos[1]--;
}
printf("reversed : %s\n",str);
return 0;
}
```
|
This question already has answers here:How to Run Only One Instance of Application(6 answers)Closed3 years ago.
I want to check if a win32 EXE file is already running (only knowing the file path and name).
Please tell me how to realize it with win32 API code.
Thanks a lot!
I mean tohave each EXE pathonly running one instance.
|
Given only a path to the EXE, you will need to enumerate the running processes until you find one with a matching path. Look atEnumProcesses()orProcess32First()/Process32Next()for that. SeeProcess Enumerationon MSDN for more details and code examples.
|
If I have a structure with some of the members being volatile but not all and I pass a pointer to this structure as a function argument, would the compiler prevent optimization to those members within the functions or do I have to declare the pointer as volatile as well?
```
typedef struct {
volatile uint16_t reg1;
volatile uint16_t reg2;
const uint32_t speed;
uint8_t error;
}uart;
void uartInitialize(uart *const hdlPtr);
//void uartInitialize(volatile uart *const hdlPtr); is this required?
```
|
Short answer: No need to add volatile on hdlPtr.
Long Answer: Unless the hdlPtr can be changed in some unexpected way, there is no need to declare it volatile. Given that it's being local to the function, it can not be changed by anything other than the uartInitialize. Given that you declared it 'const', it can not be changes by the uartInitialize itself.
|
Im trying to get the hexadecimal representation of a floating point value and so far I have been able to accomplish this:
```
float num = 263.3
int hexInt = *(int*)#
printf("%d", hexInt); // some integer value i dont understand
printf("%x", hexInt); //the hexidecimal represenation of num
```
I'm just curious as to what the integerhexIntrepresents when formatted as an integer.
|
... to get the hexadecimal representation of a floating point value
Simply use"%a\n"
```
printf("%a\n", 263.3f); // May print `0x1.074cccp+8
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.