question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I'm new to C, and I'm trying to print an array consisting of whole numbers upto a certain number(excluding this number) received as input. Here's my code:
```
#include <stdio.h>
int main(void) {
int n; int* k;
k = &n;
printf("Enter number");
scanf("%d", &n);
int set[*k];
for(int i=0; i<=n;i++){
set[i]= i;
}
}
```
I usedprintfin the last line with different inputs to check if it was working properly. I expected the output to be0 1 2 3....n-1but instead I got the output1 2 3 4 ....n. Doesn't the index of an array begin with a zero? What am I missing here?
|
Array indices in C do start at 0 but your loop is written incorrectly, and will letiiterate all the way up ton. Replacei <= nwithi < nso the loop stops aftern - 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.Closedlast year.Improve this question
I have a list of number : -1.5 , - 1 , -0,5 , ... , 100.
I want to assign them to an array.
E.g :
```
a[0] = -1.5;
a[1] = -1;
....
a[202] = 100;
```
Can you show me how to do it ?
Thanks.
|
If you want to initialize array with several values, you can usethis:
```
int a[4] = {1, 2, 3, 4};
```
But it should not be used, if you have a lot of numbers. If you need to assign list of numbers, that you stated in question, you should describe them with mathmetical expression in cycle:
```
for(int i = 0; i < 203; i++)
{
a[i] = -1.5 + 0.5 * i;
}
```
If you want to assign array with list of values, that can't be described with mathematical expression, you should read them fromfile.
|
Code
```
#define TEXT_LEN 256
#define NUM_NUMBERS (2*65536)
int numNumbers = NUM_NUMBERS;
```
PuTTY command for global variablenumNumbers
```
objdump -s -j .data assign1-0
```
Output of command
```
602070 00000000 00000200
```
Hello,
Can someone help me understand this output or if I put the wrong command?
Im trying to find global variablenumNumbersusingobjdump.
But im pretty sure the output should be 00020000 because numNumbers is 131072 (2*65536) but it's coming out 00000200 which is 512 from hexadecimal to decimal.
Am I reading it wrong and the output is correct or is the command wrong to find a global variable?
|
You are probably on alittle endiancomputer, and so the bytes that make up your int are not in the order in which you're used reading digits or bits as a human. Familiarize yourself with the concept of endianness.
|
I have written the following make file
```
all: writer.o
writer.o:
gcc -Wall writer.c -o writer
clean:
rm *.o
```
How do I add a functionality to this make file such that I am able to generate an application for the native build platform when GNU make variable CROSS_COMPILE is not specified on the make command line.However, when CROSS_COMPILe is set, I should generate a cross compiled output file using the compiler, aarch64-none-linux-gnu-gcc.
|
Set theCROSS_COMPILEvariable itself to the compiler prefix. So for native builds:
```
CROSS_COMPILE =
```
(i.e. there's nothing, the variable is "empty").
And for cross-compilation:
```
CROSS_COMPILE = aarch64-none-linux-gnu-
```
Then set:
```
CC = $(CROSS_COMPILE)gcc
```
To complement the above, useimplicit rulesto build the program:
```
all: writer
writer: writer.o
```
That's all that you need.
|
Code
```
#define TEXT_LEN 256
#define NUM_NUMBERS (2*65536)
int numNumbers = NUM_NUMBERS;
```
PuTTY command for global variablenumNumbers
```
objdump -s -j .data assign1-0
```
Output of command
```
602070 00000000 00000200
```
Hello,
Can someone help me understand this output or if I put the wrong command?
Im trying to find global variablenumNumbersusingobjdump.
But im pretty sure the output should be 00020000 because numNumbers is 131072 (2*65536) but it's coming out 00000200 which is 512 from hexadecimal to decimal.
Am I reading it wrong and the output is correct or is the command wrong to find a global variable?
|
You are probably on alittle endiancomputer, and so the bytes that make up your int are not in the order in which you're used reading digits or bits as a human. Familiarize yourself with the concept of endianness.
|
I have written the following make file
```
all: writer.o
writer.o:
gcc -Wall writer.c -o writer
clean:
rm *.o
```
How do I add a functionality to this make file such that I am able to generate an application for the native build platform when GNU make variable CROSS_COMPILE is not specified on the make command line.However, when CROSS_COMPILe is set, I should generate a cross compiled output file using the compiler, aarch64-none-linux-gnu-gcc.
|
Set theCROSS_COMPILEvariable itself to the compiler prefix. So for native builds:
```
CROSS_COMPILE =
```
(i.e. there's nothing, the variable is "empty").
And for cross-compilation:
```
CROSS_COMPILE = aarch64-none-linux-gnu-
```
Then set:
```
CC = $(CROSS_COMPILE)gcc
```
To complement the above, useimplicit rulesto build the program:
```
all: writer
writer: writer.o
```
That's all that you need.
|
Can someone explain
Why does the below code work for saving a string in a struct member
```
struct prefix {
char aString[70];
};
struct prefix data={
.aString = "d08430c90b467422ae9bf7f8ecf8a77682f92764efe53e0ebe26d4ffb6fb96bf"
};
```
while the code below does not?
```
struct prefix {
char aString[70];
};
struct prefix data;
data.aString = "d08430c90b467422ae9bf7f8ecf8a77682f92764efe53e0ebe26d4ffb6fb96bf";
//Array type 'char [70]' is not assignable
```
|
initialization: create an object and specify its value in oneinstruction;assignment: change the value of a pre-existing object
```
struct prefix data = { ... }; // initialization;
struct prefix data; // not initialized now, cannot ever initialize it later, only assign
```
|
I'm enabling IPO (inter-procedural optimization) for a C compilation of mine, using CMake:
```
set_property(TARGET foo PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
```
As expected, this causes an-fltocompiler flag to be added. However, it also adds-fno-fat-lto-objects: That means that the resulting object file willonlyhave intermediate code, rather than both properly-compiled and intermediate code; and that means that the linker must support my system compiler's intermediate representation and be IPO/LTO-aware.
I didn't ask for-fno-fat-lto-objects, nor did I want it. Can I get CMake tonotadd this option?
|
I believe this is a CMake bug... which I havenow filed:
The developers have simply made the incorrect assumption that this is what people want.
|
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.Closedlast year.Improve this question
How to search the entire binary tree for ints under x and write them to txt file in C.
I tried this code but only part of the tree gets searched.
```
void save_tree_to(FILE *out, bst *root, unsigned x)
{
if (root == NULL)
{
return;
}
save_tree_to(out, root->left, x);
if (root->price <= x)
{
save_item_to(out, root);
}
save_tree_to(out, root->right, x);
}
void save_item_to(FILE *out, bst *m)
{
fprintf(out, "%d\n", m->price);
}
```
|
A subtree that has a root>xcan very well contain elements≤x, you terminate the search too early.
Stop the search only when you have reached aleaf>x.
|
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.Closedlast year.Improve this question
How to search the entire binary tree for ints under x and write them to txt file in C.
I tried this code but only part of the tree gets searched.
```
void save_tree_to(FILE *out, bst *root, unsigned x)
{
if (root == NULL)
{
return;
}
save_tree_to(out, root->left, x);
if (root->price <= x)
{
save_item_to(out, root);
}
save_tree_to(out, root->right, x);
}
void save_item_to(FILE *out, bst *m)
{
fprintf(out, "%d\n", m->price);
}
```
|
A subtree that has a root>xcan very well contain elements≤x, you terminate the search too early.
Stop the search only when you have reached aleaf>x.
|
I don't know how to Replace 3 first elements of string by other 2 from keyboard in C.
Can I change the 2th and 3th and print from the 2th?
|
```
#include <stdio.h>
#include <string.h>
int main()
{
char c[] = "my string";
int i=0;
for (i=0; i<strlen(c); i++){
if(i==0 || i==1 || i==2){
printf("Enter a character to replace %dth element: ", i+1);
scanf(" %c", &c[i]);
}
}
printf("\nString is: %s", c);
}
```
In the following code, we have treated string as an array and in thefor loopthere is aifstatement which checks for the first 3 characters of the stringthen we just replace the letters using scanf, inscanf(" %c", &c[i]);, NOTE that there is a space before%c, it is because if that is not done the 2nd scanf will get skipped because of the new line from 1stscanf().
|
Would there be any difference between both notations when compiling in a .c file or within a .cpp file ?
|
extern "C"and__declspec(dllimport)are totally orthogonal.
extern "C"means that C linkage should be used for that symbol. I.e. no C++ name mangling will be applied. It also limits functions' interfaces to C-compatible things: built-in types, trivial structs, and pointers. Essentially, it tells the compiler and linker that a symbol should be found in the "C way" rather than the "C++ way".extern "C"is generally used for either calling C functions from C++ code or creating a C-compatible interface to C++ code.__declspec(dllimport)tells the linker that a symbol will be loaded dynamically at runtime from a DLL.
The two can be combined as well. A function markedextern "C" __declspec(dllimport)will be dynamically linked and use C-style linkage.
|
```
char command[6];
int command_num=0;
scanf("%s %d", command, &command_num);
```
If command is "top", I want to input only command, not command_num.
But when i input just command, input is continue.
How can I solve this?
|
Your description is basically pseudo code, just translate it to C:
```
char command[LARGE_ENOUGH]; // probably no reason to allocate just 6 bytes
if(scanf("%s", command) != 1) // read only command and check result
{
/* handle error - abort program etc */
}
if(strcmp(command, "top") != 0) // if command wasn't top
{
if(scanf("%d", &command_top) != 1)
{
/* handle error - abort program etc */
}
}
```
Place this all in awhileloop if needed.
However, a better solution might be to take the input as string and accept digits in the string as commands.
|
This question already has answers here:Why do you have to link the math library in C?(14 answers)Closedlast year.
I want work with this function and it will take a variable as argument but is not working with me. If i put the number it works but a number in argument does not work.
```
#include <stdio.h>
#include <math.h>
int main(void)
{
float x;
x = 7;
printf("%f", sqrtf(x)); // produces error "undefined reference to `sqrtf'"
}
```
```
int main(void)
{
printf("%f", sqrtf(7)); // works
}
```
|
sqrtf(7)is evaluated compile time andsqrtffunction is not called. (it "works")sqrtf(x)is evaluated run time andsqrtffunction is called. (it does not "work" - ie it does not link)https://godbolt.org/z/oY6zfqxd1
You need to add-lmcompile option to link against the math library. If you do not, the program will not link.
|
Is negating the integer-2^(31)defined as undefined behavior in the C standard or simply-2^(31)again? Trying it the latter holds, but it would be interesting to know how the C standard specifies it.
|
The standard (n2176 draft) says explictely at 6.5 Expressions § 5:
If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not
mathematically defined or not in the range of representable values for its type), the behavior is
undefined.
We are exactly there: the result is not is the range of representable values for the type, so it is explicitely UB.
That being said, most implementation use 2'complement for negative values and process operations on signed types as the operation on the unsigned type values having the same representation. Which is perfectly defined.
So getting-2^(31)again can be expected on common implementations. But as the standard says that it is UB, it cannot be relied on.
|
I tried the code given below and found that it actually prints "yes", which means that the character array is taken as true in if statement. But i wonder what is the reason. I mean its an array so did it returned the whole "string". Or it returned its first element that is "s", or it returned its memory location which is processed as true as anything other than 0 is true.
```
char a[] = "string";
if (a)
{
printf("yes");
}
```
|
```
if (a)
```
In this context, a reference to an array decays to a pointer to the first value of the array. The same thing would happen ifawere to get passed as a function parameter.
So, here,ais just a pointer. And since it's not a null pointer this always evaluates to true.
```
char a[6] = "string";
```
This is not really relevant, but this literal string has seven characters, not six, by the way. You forgot about the trailing\0.
|
Imagine some array
```
uint8_t var[5] = {1,2,3,4,5};
```
sovarwill be pointer to the first element of this array, and
```
uint 8_t* a=var;
b=a[3]
```
and
```
b=var[3]
```
will give the same result.
But will
```
a = &var[2];
b = a[1];
```
and
```
b=var[3];
```
be same?
|
After this assignment
```
a = &var[2];
```
that is the same as
```
a = var + 2;
```
due to the implicit conversion of the array designator to a pointer to its first element the pointerapoints to the elementvar[2].
Soa[0]yieldsvar[2]anda[1]yieldsvar[3].
Pay attention to that the subscript operatora[i]is evaluated like*( a + i ).
So you havea[1]is equivalent to*( a + 1 )that is in turn equivalent to*( var + 2 + 1 )that is to*( var + 3 ).
|
On some platforms like Microsoft Windows no need to link against the "Standard C Library" with-lcflag, But on some other platforms it requires linking, But on macOS/OSX though it's Unix-based we don't link with-lcwhile we need to link on Linux and BSDs...
That made me a bit confused when writing Cross-Platform C libraries, Where and When to/not to link against the "Standard C Library" with-lcflag?
And is linking just for Linux and BSDs? Or also some other Unix platforms requires linking?
|
Essentially every hosted C implementation requires you to link programs with an implementation of the standard C library.
Some commands for building programs have the inclusion of the standard C library built-in as a default, so you do not need to add it explicitly on the command library. Some commands do not have it as a default, so you do need to add it on the command line.
|
Imagine some array
```
uint8_t var[5] = {1,2,3,4,5};
```
sovarwill be pointer to the first element of this array, and
```
uint 8_t* a=var;
b=a[3]
```
and
```
b=var[3]
```
will give the same result.
But will
```
a = &var[2];
b = a[1];
```
and
```
b=var[3];
```
be same?
|
After this assignment
```
a = &var[2];
```
that is the same as
```
a = var + 2;
```
due to the implicit conversion of the array designator to a pointer to its first element the pointerapoints to the elementvar[2].
Soa[0]yieldsvar[2]anda[1]yieldsvar[3].
Pay attention to that the subscript operatora[i]is evaluated like*( a + i ).
So you havea[1]is equivalent to*( a + 1 )that is in turn equivalent to*( var + 2 + 1 )that is to*( var + 3 ).
|
On some platforms like Microsoft Windows no need to link against the "Standard C Library" with-lcflag, But on some other platforms it requires linking, But on macOS/OSX though it's Unix-based we don't link with-lcwhile we need to link on Linux and BSDs...
That made me a bit confused when writing Cross-Platform C libraries, Where and When to/not to link against the "Standard C Library" with-lcflag?
And is linking just for Linux and BSDs? Or also some other Unix platforms requires linking?
|
Essentially every hosted C implementation requires you to link programs with an implementation of the standard C library.
Some commands for building programs have the inclusion of the standard C library built-in as a default, so you do not need to add it explicitly on the command library. Some commands do not have it as a default, so you do need to add it on the command line.
|
I wonder if there is a way to declare multiple structs in C.
For example, I made this:
```
struct Team{
char TeamName[20];
int Point;
int Goals;
};
typedef struct TeamCup {
char GroupID;
struct Team team;
}Group;
Group g1, g2;
```
I want each TeamCup to have 4 teams. But when it comes to input process, in my loop, the variable here is undefined:
```
g1.Team[i].Point;
```
|
I want each TeamCup to have 4 teams
In this case you need to write
```
typedef struct TeamCup {
char GroupID;
struct Team team[4];
}Group;
```
and
```
g1.team[i].Point;
```
Thar is you need to declare an array of objects of the typestruct Teamwithin the structurestruct TeamCup.
|
How can i print out the second byte in a stored integer in one line on printf as shown in
in the second printf()
```
unsigned int aNum = 258; // 4 bytes in allocated memory
unsigned char * newP = &aNum;
printf("\n with a pre-created pointer %02i",newP[1]); //getting the second byte[02]
printf("\n address without a pre-created pointer %02i",(unsigned char)aNum); // getting the first byte[01]
```
|
Consider this solution:
```
#include <stdio.h>
int main(void) {
unsigned int aNum = 0x1a2b3c4du; // 4 bytes in allocated memory
for (int i = 0; i < 4; ++i) {
printf("\nbyte %d %02x", i, (unsigned int) ((unsigned char *) &aNum)[i]);
}
}
```
|
This question already has answers here:How do I write file modification dates programmatically in POSIX?(4 answers)Closedlast year.
I am writing a C program to change the modified timestamp(time and date) of a file in linux. I found the commands to that but I am looking for a way I can do that through a C program. Is there a way I can do that?
|
For linux try
```
int utimensat(int dirfd, const char *pathname,
const struct timespec times[2], int flags);
```
or legacy command
```
int utime(const char *filename, const struct utimbuf *times);
```
|
Today I find the following piece of code
```
void func(int A[const 10]) { ... }
```
By compiling it using gcc, I conclude thatint A[const]is equivalent toint* const Ainstead ofconst int *A. I wonder why here:constis inside the brackets, why does it not modify elements ofAbutAitself?
|
I wonder why
Because the C standard explicitly says so.
6.7.6.3 ¶ 7A declaration of a parameter as "array of type" shall be adjusted to "qualified pointer to type", where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation.
Note, "qualified pointer to type", not "pointer to qualified type". The latter is expressible with the ordinary syntaxconst int A[10].
This syntax was invented specifically to express "a qualified pointer to type, adjusted from an array type with an optional size provided for documentation". It is only valid in function prototypes.
|
```
void* aPtr = NULL; // we don't yet know what it points to.
...
aPtr = &height; // it has the address of height, but no type yet.
...
int h = (int)*aPtr; // with casting, we can now go to that address
// and fetch an integer value.
```
(Learn C Programming; Jeff Szuhay)
'with casting, we can now go [...]'
The question is - can we really?
|
Dereferencing and Casting Void Ptr (Learn C Programming, Jeff Szuhay)'with casting, we can now go [...]'The question is - can we really?
Yes, but the shown code doesn't do any dereferencing. Well, ittriesto dereference avoid*and cast the result toint. That's not how it should be done. You must first cast toint*andthendereference thatint*.
```
int h = *(int*)aPtr; // now dereferenced ok (assuming `height` is an `int`)
// ^ ^
// | |
// | proper cast
// |
// dereferencing the right thing
```
|
Do you know how a number can be rounded up and printed with a precision that is not fixed by some natural number, but by some variable? If the user needs to enter how many decimal places to round, how to solve it?
```
#include <stdio.h>
int main()
{
int r;
double var = 37.66666;
scanf("%d", &r);
printf("%.2f", var);
return 0;
}
```
|
Here's simple approach that would work in your case:You just need to put * before f, and that's it.
```
#include <stdio.h>
int main()
{
int r;
double var = 37.66666;
scanf("%d", &r);
printf("%.*f",r, var);
return 0;
}
```
|
I am trying to find an equivalent forsetenvto use in a C program. What I am trying to do is to modify the values of all the environment variables of the currently running process. I am trying to useputenvbut it doesn't change the variables` values in any way. What could I do?
|
Those are the correct methods for setting the environment variables. The issue you are hitting is thatSetEnvironmentVariablewhich is what is used by the C Runtimesetenvdoes not change system-wide environment variables; only the environment of the currently running process.
Changing the system-wide or per-user environment variables on Windows is normally done using scripts or UI. To modify the system-wide environment variables from a C program, you need (a) to run it withadministrator rights, (b) you need to modify theSystem Registry, and (c) you need to send aWM_SETTINGSCHANGEWin32 message to get the changes picked up by the Windows shell.
|
Do you know how a number can be rounded up and printed with a precision that is not fixed by some natural number, but by some variable? If the user needs to enter how many decimal places to round, how to solve it?
```
#include <stdio.h>
int main()
{
int r;
double var = 37.66666;
scanf("%d", &r);
printf("%.2f", var);
return 0;
}
```
|
Here's simple approach that would work in your case:You just need to put * before f, and that's it.
```
#include <stdio.h>
int main()
{
int r;
double var = 37.66666;
scanf("%d", &r);
printf("%.*f",r, var);
return 0;
}
```
|
I am trying to find an equivalent forsetenvto use in a C program. What I am trying to do is to modify the values of all the environment variables of the currently running process. I am trying to useputenvbut it doesn't change the variables` values in any way. What could I do?
|
Those are the correct methods for setting the environment variables. The issue you are hitting is thatSetEnvironmentVariablewhich is what is used by the C Runtimesetenvdoes not change system-wide environment variables; only the environment of the currently running process.
Changing the system-wide or per-user environment variables on Windows is normally done using scripts or UI. To modify the system-wide environment variables from a C program, you need (a) to run it withadministrator rights, (b) you need to modify theSystem Registry, and (c) you need to send aWM_SETTINGSCHANGEWin32 message to get the changes picked up by the Windows shell.
|
Why does
```
printf("%ld\n", (void *)0 - (void *)0);
```
compile, but
```
printf("%ld\n", (void *)0 + (void *)0);
```
does not?
|
It is useful to find the difference between two pointers. This gives an integer (aptrdiff_t).[1]
It is useful to add a difference to a pointer, so we can add an integer to a pointer (and vice-versa). The inverse operation ofptrdiff = p2 - p1isp2 = p1 + ptrdiff.[1]
However, there's no sensible meaning to adding two pointers together. So that's not allowed.
Note that this is undefined behaviour forvoid *pointers, and for pointers that aren't to parts of the same object.
|
This question already has answers here:Int to char conversion rule in C when int is outside the range of char(2 answers)Closedlast year.
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
signed char chr=128;
printf("%d\n",chr);
return 0;
}
```
|
Do you know about integer limits? Acharvalue takes up 1 byte. A byte is usually 8 bits. To calculate the limit through the number of bits, the calculation is2^n-1meaning an integer with 8 bits has a range from 0 to 255 when unsigned. Since your variable is signed, it allocates a bit to the sign, meaning it has a range from -128 to 127. Since you assigned it as 128, it overflowed, rolling back over to -128. If your program doesn't use negative numbers, you should usesigned char, otherwise you might want to use ashortwhich is 2 bytes.
|
In C89 A.1.2.2 Declarations
direct-declarator [ constant-expression ]
In C99 A.2.2 Declarations
direct-declarator [ type-qualifier-list_opt assignment-expression_opt ]
I understandassignment-expression_optasvar = 1;. But arrays are not declared likeint arr[i = 0];. Why does C99 use the term "assignment-expression" instead of "constant-expression"and what does it mean?
|
In C89 there was no support for variable length arrays. This means that array sizes must be fixed at compile time.
Starting with C99, declarations and statements may be mixed within a block, so full expressions that must be executed are now allowed as an initializer. This also is what allows for variable length arrays to be created.
So a declaration likeint arr[i=0];is valid syntax, although it's invalid because it created an array of size 0.int arr[i=2];is valid and will createarras an array ofintof size 2, and it setsito 2.
|
This question already has answers here:What does =+ (equals-plus) mean in C?(7 answers)Closedlast year.
I often confuse both "-=" and "=-", like what is the exact difference between them?
```
int main()
{
int x=10, a=-3;
x=-a;
printf("%d",x);
return 0;
}
```
Output
```
3
```
|
-=is a compound assignment operator.=-is two operators applied seperately.
While
```
a =- 3;
```
is the same as
```
a = (-3);
```
This
```
x -= a;
```
is more or less equivalent to
```
x = x - a;
```
"More or less" because operators can be overloaded (in C++) and typically the compound operator avoids the temporary right hand side.
Btw you are using=-twice in your code while the questions asks for+=vs=+.+=is a compound operator as well.
|
I've declared a typedef:
```
typedef float Matrix[3][3];
```
And I'm now trying to allocate memory for that array:
```
Matrix* matPtr = malloc(sizeof(Matrix));
if (matPtr != NULL)
{
for (int r = 0; r < 3; r++)
{
for (int c = 0; c < 3; c++)
{
*matPtr[r][c] = 0;
}
}
}
```
But I'm getting the error:
Severity Code Description Project File Line Suppression State
Warning C6200 Index '2' is out of valid index range '0' to '0' for non-stack buffer 'matPtr'.
What am I doing wrong?
|
Do not hide arrays and pointers behind typedefs. It is a very very bad practice.Use pointers to array
```
int (*matrix)[3] = malloc(3 * sizeof(*matrix));
```
and use as a normal matrix
```
matrix[1][2] = 5;
```
|
Is this identifier non-problematic:
```
_var
```
C11, 7.1.3 Reserved identifiers, 1
All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.
Does it follow from this that user-defined identifiers beginning with a single underscore are non-problematic?
|
Yes. As long as:
are at block scope (includes enum/struct/union tags)OR are struct/union membersOR are function parameters_is followed by neither capital nor another underscore
E.g.
```
struct X { int _a; };
int main() { int _a; }
void foo(int _a);
```
|
I am trying to write wrapper for a log function with a printf-like behavior.
Can anyone tell me why the following example does not work?
```
#include <stdarg.h>
void message(int level, const char* format, ...)
{
if(level > 3)
return;
static char msgBuff[1024] = {0};
va_list argptr;
va_start(argptr, format);
snprintf(msgBuff, sizeof(msgBuff), format, argptr);
va_end(argptr);
printf("%s", msgBuff); // Dummy Call
}
int main()
{
int a = 42;
message(3, "This is a test: %s %i", "The answer is ", a);
return 0;
}
```
Output:
```
This is a test: 0
```
|
The arguments tosnprintfafter the format string must be the individual arguments expected according to the conversion specifiers in the format string.argptris not such an argument, so the call is incorrect.
To print variable arguments using ava_list, callvsnprintfinstead ofsnprintf.
|
```
for (int i = 0; i < n+1; ++i)
{
sum = sum + i;
}
for (int i = 0; i < n+1; i++)
{
sum = sum + i;
}
```
Two paragraphs are different because of ++i and i++ in function call argument.
but it works like i only starts with 0. Why does even ++i starts with 0?
|
There are absolutely no difference between these two snippets.i++vs++ionly matters when mixed with other operators in the same expression. Which is a bad idea most of the time, sincei++/++icomes with a side effect.
|
I am implementing a Binary Search Tree. And it so happens one of my sources have a function written such that:
```
Node * BST_Insert(Node *root, int val)
{
//Body
}
```
I already know that a pointer is a variable which contains the address of another variable and we can't assign a value to a pointer, but we can assign the address of another variable to the pointer.
My Question is what the pointers on this prototype do exactly?
```
Node * BST_Insert(Node *root,int val)
```
|
Nodeis most likely atypedefof a structure representing a node in the Binary Search Tree.
ThusNode *rootrepresents a pointer to the root of the BST, i.e. a handle to the tree structure.
Since insertion of a new node may change which node is the root of the tree, the function most likely returns a pointer to the new root node.
|
This question already has answers here:Stringification - how does it work?(2 answers)Closedlast year.
```
#define S(x) (cout<<#x<<endl)
```
Using # will print whatever string, int, float I place in S(x).For example:
```
S(Door Class Default Constructor);
```
will print
Door Class Default Constructor
I Wasn't able to find any documentation regarding it.Explain how is it able to do so.
|
It causes the expandedxto be wrapped in double quoates,"
It's often called the stringize operator and you can find more informationhere.
|
I am trying to write wrapper for a log function with a printf-like behavior.
Can anyone tell me why the following example does not work?
```
#include <stdarg.h>
void message(int level, const char* format, ...)
{
if(level > 3)
return;
static char msgBuff[1024] = {0};
va_list argptr;
va_start(argptr, format);
snprintf(msgBuff, sizeof(msgBuff), format, argptr);
va_end(argptr);
printf("%s", msgBuff); // Dummy Call
}
int main()
{
int a = 42;
message(3, "This is a test: %s %i", "The answer is ", a);
return 0;
}
```
Output:
```
This is a test: 0
```
|
The arguments tosnprintfafter the format string must be the individual arguments expected according to the conversion specifiers in the format string.argptris not such an argument, so the call is incorrect.
To print variable arguments using ava_list, callvsnprintfinstead ofsnprintf.
|
```
for (int i = 0; i < n+1; ++i)
{
sum = sum + i;
}
for (int i = 0; i < n+1; i++)
{
sum = sum + i;
}
```
Two paragraphs are different because of ++i and i++ in function call argument.
but it works like i only starts with 0. Why does even ++i starts with 0?
|
There are absolutely no difference between these two snippets.i++vs++ionly matters when mixed with other operators in the same expression. Which is a bad idea most of the time, sincei++/++icomes with a side effect.
|
I am implementing a Binary Search Tree. And it so happens one of my sources have a function written such that:
```
Node * BST_Insert(Node *root, int val)
{
//Body
}
```
I already know that a pointer is a variable which contains the address of another variable and we can't assign a value to a pointer, but we can assign the address of another variable to the pointer.
My Question is what the pointers on this prototype do exactly?
```
Node * BST_Insert(Node *root,int val)
```
|
Nodeis most likely atypedefof a structure representing a node in the Binary Search Tree.
ThusNode *rootrepresents a pointer to the root of the BST, i.e. a handle to the tree structure.
Since insertion of a new node may change which node is the root of the tree, the function most likely returns a pointer to the new root node.
|
This question already has answers here:Stringification - how does it work?(2 answers)Closedlast year.
```
#define S(x) (cout<<#x<<endl)
```
Using # will print whatever string, int, float I place in S(x).For example:
```
S(Door Class Default Constructor);
```
will print
Door Class Default Constructor
I Wasn't able to find any documentation regarding it.Explain how is it able to do so.
|
It causes the expandedxto be wrapped in double quoates,"
It's often called the stringize operator and you can find more informationhere.
|
C2x (N2596), 6.2.7 Compatible type and composite type, 1:
Two types havecompatible typeif their types are the same.
The grammar of that sentence is confusing.
For example:
How type can have a type? Or what does "their types" mean?What does it mean "compatible type"? Any examples?
Please clarify who knows the topic well.
UPD. Here is the rephrased sentence:
Two types are compatible if they are the same.
|
The sentence means if the typeXand the typeYare the same type, thenXis compatible withY(and vice-versa, of course).
In mathematical terms, it means compatibility is reflexive (any type is compatible with itself).
|
C2x (N2596), 6.2.7 Compatible type and composite type, 1:
Two types havecompatible typeif their types are the same.
The grammar of that sentence is confusing.
For example:
How type can have a type? Or what does "their types" mean?What does it mean "compatible type"? Any examples?
Please clarify who knows the topic well.
UPD. Here is the rephrased sentence:
Two types are compatible if they are the same.
|
The sentence means if the typeXand the typeYare the same type, thenXis compatible withY(and vice-versa, of course).
In mathematical terms, it means compatibility is reflexive (any type is compatible with itself).
|
0.c
```
int test();
int main(){
return test();
}
```
1.c
```
void test(){
//
}
```
Above compiles fine withgcc 0.c 1.cand main returns0.
Is this undefined behaviour? astesttechnically doesn't return anything.
|
Opposite to C++ C does not stores in external names of functions their return types and argument types. It only specifies that (relative to the provided code) there is an external name of the functiontestused for linkage.
As for C++ then for example in the documentation for MS VC++ there is written about decorated names
If you change the function name, class, calling convention, return type, or any parameter, the decorated name also changes. In this
case, you must get the new decorated name and use it everywhere the
decorated name is specified.
Decorated names are implementation-defined in C++.
As a result the provided code in the question has undefined behavior.
|
unsigned short num = 258;
//How can i read the byte value as on how this num 258 is getting store (by default is stored as litle indian right?) so the value should be something like this[ 2, 1 ]or[0x02,0x01]<- as litle endian
how do i printf it out?
|
A pointer to anunsigned charcan be used to read the byte representation of an object.
```
unsigned char *p = (unsigned char *)#
int i;
for (i=0; i<sizeof num; i++) {
printf("%02x ", p[i]);
}
```
|
This question already has answers here:Is floating point math broken?(33 answers)Closedlast year.
Can someone please explain the output here?
```
#include <stdio.h>
int main(void) {
float f = 0.1 ;
printf ("%f\n",f ) ;
if (f == 0.100000) {
printf ("true ") ;
}
else {
printf ("False") ;
}
return 0;
}
```
output:
```
0.100000
False
```
|
You are trying to compare afloatnumber with adouble. The number0.100000is considered asdoubletype unless you specify with a trailingfthat it is afloat.Thus:
```
int main(){
float x = 0.100000;
if (x == 0.100000)
printf("NO");
else if (x == 0.100000f)
// THE CODE GOES HERE
printf("YES");
else
printf("NO");
}
```
You mat refer tosingle precisionanddouble precisionfor theoritical details
|
I run into something like this in C:
```
struct{
int a;
int b;
} cmd = {1,1);
```
What is this? iscmdis the name of the struct? the name of the variable? how can it be both? can you make more variables of this struct?
|
What you have here is a variable namedcmdwhose type is ananonymous struct.
Because the structure type doesn't have a name ortypedefalias, this means it can't be used as a parameter to a function, and that no other variables of this type can be defined except in the same declaration ascmd.
Also, note that you have a syntax error in the initializer forcmd. Instead of{1,1)it should be{1,1}.
|
```
int foo (int x) {
int (*d)(int *) = foo; //what is the meaning of this line?
...
}
```
this is an old practice question from my school, but i couldn't find the solution for it.
Is it initializing a variable to a function?
|
This record
```
int (*d)(int *) = foo;
```
is a declaration of the function pointerdto function that has the return typeintand one parameter of the typeint *. This pointer is initialized by the address of the functionfoo(the function designator is implicitly converted to pointer to it).
Pay attention to that either the functionfooshould be declared like
```
int foo (int *x) {
```
or the pointer should be declared like
```
int (*d)(int ) = foo;
```
Otherwise in this declaration
```
int (*d)(int *) = foo;
```
there are used incompatible pointer types.
|
I have 3 files00.c,01.c,02.c, each one of these files contains one function, and the 3 functions are accessible bymain.c. What I want to do is to run these functions in the right order depending on the file name (call the function inside00.c, then the one inside01.c, then02.c). Is it possible to do that in C (preferably without defining macros)?
|
Unfortunately not. The functions within a binary are in some undefined order (probably related to the link command line).
This means that functions can not be found in the correct order.
You could use the MACROFILEto identify the file name of a file, then use a structure with that and the function to call to sort the functions in the required order.
|
```
int foo (int x) {
int (*d)(int *) = foo; //what is the meaning of this line?
...
}
```
this is an old practice question from my school, but i couldn't find the solution for it.
Is it initializing a variable to a function?
|
This record
```
int (*d)(int *) = foo;
```
is a declaration of the function pointerdto function that has the return typeintand one parameter of the typeint *. This pointer is initialized by the address of the functionfoo(the function designator is implicitly converted to pointer to it).
Pay attention to that either the functionfooshould be declared like
```
int foo (int *x) {
```
or the pointer should be declared like
```
int (*d)(int ) = foo;
```
Otherwise in this declaration
```
int (*d)(int *) = foo;
```
there are used incompatible pointer types.
|
I have 3 files00.c,01.c,02.c, each one of these files contains one function, and the 3 functions are accessible bymain.c. What I want to do is to run these functions in the right order depending on the file name (call the function inside00.c, then the one inside01.c, then02.c). Is it possible to do that in C (preferably without defining macros)?
|
Unfortunately not. The functions within a binary are in some undefined order (probably related to the link command line).
This means that functions can not be found in the correct order.
You could use the MACROFILEto identify the file name of a file, then use a structure with that and the function to call to sort the functions in the required order.
|
I am aware that when using theprintffunction I can express the octal value of an integer with%oand its hexadecimal value with%x.How can I represent a floating-point value as octal or hexadecimal, though?When trying to use the same specifiers, Xcode 13.x predictably throws a warning telling me I am trying to use an integer specifier with a floating-point value.
How can I work around this?Thank you
|
You can format afloatordoublein hexadecimal using%aor%A(to use lowercase or uppercase letters, respectively). There is no conversion specifier for octal for floating-point.
This formats the value. If you want to view the representation of the floating-point object, you should access its bytes using anunsigned char *, and then you can format those bytes using theo,x, orXconversion specifiers.
|
I'm looking at a very old C based project. It adds the-D_LARGEFILE_SOURCEdefine when building.
Is that preprocessor macro still needed on modern Linux (and if so, why)?
|
I checked the headers. If you are compiling for 64 bit,_LARGEFILE_SOURCEwill be defined for you every time. This only does anything for 32 bit. And yes this is the switch, if you use modern 32 bit Linux, you still need it to access files > 2GB.
The macro definition changes the size of the file size parameters from 32 to 64 bit inlseek()andfseek(), changes the system call number forlseek()to callllseek(), and the size of the file size member ofstruct statto 64 bit. (The syscall change happens elsewhere for*statunless you still build against libc5.)
|
This question already has answers here:With arrays, why is it the case that a[5] == 5[a]?(20 answers)Closedlast year.
in the online course from my university I met the next interesting fact:
The executing of the next line will produce'\0':
5["Peklo"]
I also tried some different examples by passing different integers and string literals. I know that C strings areconst char *pointers therefore that code is valid and will compile, but I can not figure out how the output calculates/depends on the passing integer value of the string indexer. If someone knows, can you explain to me in detail why0["P"],0["A"]and1["A"]produces different results (80, 65, 0)?
|
```
5["Peklo"] === "Peklo"[5] == (char[]){'P','e','k','l','o','0'}[5] == 0 == '\0'
[0] [1] [2] [3] [4] [5]
```
|
i want to zero all the bits after the 2nd index (Including the 2nd) in an unsigned int. Here's the non working code i wrote so far: (temp is an unsigned int.)
```
for(int i=2; i< DSLength(dnaS); i++)
{
temp = temp & (0 << i);
}
```
It keeps zeroing the whole number...
|
If I understand you correct, and you want to preserve the lowest two bits and zero all the rest, you don't need a loop:
```
x &= 3
```
does exactly that withx.
|
I would like to know how I could transform a character string to an ASCII value, such as "12ASD132 hello" in its ASCII values
a greeting,
|
To answer your first question: all C implementations I have ever seen store their characters in ASCII, so if your implementation is like that too, you can simply print each character in the string as an integer:
```
#include <stdio.h>
int main() {
const char * str = "12ASD132 hello";
for (const char * p = str; *p; p++) {
printf("%d\n", *p);
}
}
```
|
i only found K_ANY event in thedoc(Events and Callbacks -> Common -> K_ANY).
how do i handle keypress and keyrelease events separately?
is it possible in this library?
can anyone help?
|
Only on IupCanvas and derived controls using the KEYPRESS_CB callback. It has an extra parameter that indicates if the key is being pressed or released.
|
i only found K_ANY event in thedoc(Events and Callbacks -> Common -> K_ANY).
how do i handle keypress and keyrelease events separately?
is it possible in this library?
can anyone help?
|
Only on IupCanvas and derived controls using the KEYPRESS_CB callback. It has an extra parameter that indicates if the key is being pressed or released.
|
I want to use GraphViz as a C library(cgraph) but I don't know how to actually "import" it.The folder containsmakefile.am, so I should use automake to get amakefile.infile. Where do I go from there?
I'm really confused on the actual procedure to follow.
|
just share my experience. I have no permission to post a comment, thus I post an answer for your reference. I am using ubuntu 20.04.
In the beginning,
```
foo.c:4:10: fatal error: graphviz/cgraph.h: No such file or directory
4 | #include <graphviz/cgraph.h>
| ^~~~~~~~~~~~~~~~~~~
compilation terminated.
```
Then, I install graphviz-dev and it works.
```
$ sudo apt-get install graphviz-dev
```
If this is not the answer you expected, please let me know. I will remove this post. Thank you.
|
Sincepthread_tis a struct, I thought that I could simply get the attributes directly. Checked this page and saw the names of the thread attributes (detachedstate, schedparam etc) so I tried it like this:
```
pthread_t t1;
void routine() {
printf(t1.inheritsched);
}
int main(int argc, char **argv) {
pthread_create(&t1, NULL, &routine, NULL);
pthread_join(t1, NULL);
return 0;
}
```
But i got an error saying basically thatpthread_tisn’t a struct, which surprised me.
What exactly is going on, and how can i display a thread's attributes?
|
Thespecification says:
Upon successful completion,pthread_create()shall store the ID of the created thread in the location referenced bythread.
Thus we know thatpthread_tis just the ID of the thread, with the exact typenot stated in the specification.
|
This question already has answers here:What is the benefit of putting #undef before #define?(2 answers)Closedlast year.
I'm reviewing the open sourceFANNlibrary. As far as I have examined, the developers contributing to the project are quite experienced in C. But I wonder why they do the following indoublefann.hfile:
```
#undef DOUBLEFANN
#define DOUBLEFANN
```
What's the purpose of removing an identifier using#undefand then redefining it using#define?
|
I don't think there's any secret; it's just that the author of that code wanted to override any existing preprocessor-value ofDOUBLEFANN(e.g. as set by an earlier line in some header-file, or perhaps as provided by a-DDOUBLEFANN=somethingargument on the compiler's command-line) and replace it with his own definition ofDOUBLEFANNas a defined preprocessor macro with an empty value.
As towhythe author felt it was necessary to do that, I have no idea.
|
```
int main() {
FILE* o = fopen("o.txt","r+");
char c;
while(!feof(o)){
c = fgetc(o);
if(c == 'h'){
fputc('#',o);
}else {
fputc(c,o);
}
}
return 0;
}
```
this is code, I am trying to edit text file, Whenever h letter appears I want to change it with # and other stays same. But when I run this code program does not. what am I doing wrong.
|
char cit has to beint cwhile(!feof(o))- read Andreas Wenzel'scomment
```
while((c = fgetc(o)) != EOF)
```
The read moves the file pointer onecharahead, so you need to move it back to write to the previous position.
for example
```
fseek(o, -1L, SEEK_CUR);
```
|
```
char* s_ptr = "hello"; // (1)
int* a = 5; // (2)
```
Why does the first line work and the second doesn't? In the first case, there is no variable that stores"hello", and as I understand it, a"hello"object (char array) is created in memory and as_ptrpoints to first element in array. Why is number5not created in memory in second case?
|
If you runprintf("%p\n%p\n", s_ptr, a);it will probably be a little bit clearer."hello"decays to a pointer (which arrays often does) and that pointer is assigned to the pointers_ptr. On the other hand, the pointerawill simply be assigned to the value5.
Try it out:https://onlinegdb.com/73pgzVmCJ
Related questions:
String literals: pointer vs. char array
What is array to pointer decay?
|
According to crypt.h:
```
extern char *crypt_gensalt (const char *__prefix, unsigned long __count,
const char *__rbytes, int __nrbytes)
```
I understand that__prefixis encryption type (i.e. $2a$, $5$, $6$,...). My guess is__rbyteis the passphrase and__nrbytesis the size of passphrase.
How about__count? What should I pass into it? I'm going to use$6$prefix.
|
From the man page:https://manpages.debian.org/experimental/libcrypt1-dev/crypt_gensalt_rn.3.en.html
countcontrols the CPU time cost of the hash; the valid range for count and the exact meaning of “CPU time cost” depends on the hashing method, but larger numbers correspond to more costly hashes.
See alsohttps://manpages.debian.org/experimental/libcrypt1-dev/crypt.5.en.html
For$6$(which issha512crypt)
CPU time cost parameter1000 to 999,999,999
and
The default CPU time cost parameter is 5000, which is too low for modern hardware.
|
So I have the following code snippet in C:
```
int a = 25, b = 100, c;
if (b++ <= (a * 4))
c = 3;
else
c = 20;
printf ("%f\n", (float) (b / c));
```
When I ran the code, the output returned the value33.0000. I was expecting the output to be33.6667.
I was wondering why was it so?
My calculations are as follows:
In line 2, b is incremented post-operation, and therefore while the statement will return true (100 <= 25*4), the value of b after this operation will be 101.In the output, we calculate 101/3, which should return 33.6667This is not the case, however.
Thank you for your help!!
|
The expressionb / cis performing integer division because both operands are integers. This means the resulting value gets truncated.
If you want to perform floating point division, cast one of the operands tofloat.
```
printf ("%f\n", (float)b / c);
```
|
As the title says, I am wondering if there is a way to start my program in administrative mode using a function, code, command of some sort included in it. The reason is,my program cannot delete a file without having to be run as an administrator. and yes a simple way of solving this would be to edit the properties of the exe so that it uses UAC to start as admin but I have to distribute the source code for my reviewers to compile it and wanted to save them the trouble.
Any comments,solutions etc are appreciated, thanks.
|
You could use PowerShell for this:
```
PowerShell Start yourprogram.exe -Verb Runas
```
This should be portable enough to run on most Windows systems.
|
Let's say I have the following program (a.c):
```
#include <stdio.h>
void f()
{
printf("Hello, world!");
}
int main(void)
{
f();
return 0;
}
```
```
$ gcc -g a.c
```
Havinga.out, how do I find out wheremain()is defined? I mean, in a big project it's not always clear wheremain()comes from.
|
You can usegdb. Probably there's a better command, anyway I know of:
```
$ gdb -batch -ex "info function main" a.out
All functions matching regular expression "main":
File a.c:
8: int main(void);
```
|
I need to generate a random number that has 4 digits, but I have to make sure that every digit is not higher than 6, Is it possible? if so, how can I do that? :)
(In C)
|
Simplest option would be to generate 4 different random numbers in the range of 0 to 6, then add them up, but multiply the first one by 1, second one by 10 etc.
```
int a = rand() % 7;
int b = rand() % 7;
int c = rand() % 7;
int d = rand() % 7;
int e = a + 10 * b + 100 * c + 1000 * d;
```
|
I'm making program which converts sum of the numbers entered by user to binary, octal and hexadecimal. I would like to give a user an option to run program once again but with different numbers. Here is the problem - each time user repeats numbers, sum of these numbers are added to the previous entry. How do I stop incrementing? Is there any way to reset sum to 0? Thank you so much for your help!
|
Is there any way to reset sum to 0?
Yes, setsumto 0 right before the inner loop.
```
sum = 0;
while(1)
{
printf("Enter number: ");
scanf("%d", &value);
sum += value;
if(value == 0)break;
}
```
Also, rather then usingwhile (1)with abreakcondition at the end, use ado..whileloop.
```
sum = 0;
do {
printf("Enter number: ");
scanf("%d", &value);
sum += value;
} while (value != 0);
```
|
Please explain to me why this program is printing12 12as output, and not7 7?
```
#include <stdio.h>
int addmult(int ii, int jj){
int kk, ll;
kk = ii + jj;
ll = ii * jj;
return(kk,ll);
}
int main(void) {
int i = 3, j = 4, k, l;
k = addmult(i,j);
l = addmult(i,j);
printf("\n%d\n%d",k,l);
}
```
|
C does not allow the returning of multiple values from the same function. You could create a structure that holds the 2 values inside the function and return that, but a better approach would be to just call the function once each time.
|
In C, the type of a string literal ischar [].
gdbdebugger:
```
(gdb) ptype ""
type = char [1]
(gdb) ptype "abc"
type = char [4]
```
lldbdebugger:
```
(lldb) p ""
(const char [1]) $0 = ""
(lldb) p "abc"
(const char [4]) $1 = "abc"
```
Thegdbdebugger shows type of string literal aschar [N](which is as per language standard) butlldbdebugger showsconsttype-qualifier in string literal type -const char [N].Is this a bug inlldbdebugger? Or, am I missing something?
|
Quotingcppreference.com:
"String literals arenot modifiable(and in fact may be placed in read-only memory such as .rodata). If a program attempts to modify the static array formed by a string literal, the behavior is undefined."
lldbis just showing the type of the real memory under the hood even though it's formally reachable through a pointer to const.
|
I need to generate a random number that has 4 digits, but I have to make sure that every digit is not higher than 6, Is it possible? if so, how can I do that? :)
(In C)
|
Simplest option would be to generate 4 different random numbers in the range of 0 to 6, then add them up, but multiply the first one by 1, second one by 10 etc.
```
int a = rand() % 7;
int b = rand() % 7;
int c = rand() % 7;
int d = rand() % 7;
int e = a + 10 * b + 100 * c + 1000 * d;
```
|
I'm making program which converts sum of the numbers entered by user to binary, octal and hexadecimal. I would like to give a user an option to run program once again but with different numbers. Here is the problem - each time user repeats numbers, sum of these numbers are added to the previous entry. How do I stop incrementing? Is there any way to reset sum to 0? Thank you so much for your help!
|
Is there any way to reset sum to 0?
Yes, setsumto 0 right before the inner loop.
```
sum = 0;
while(1)
{
printf("Enter number: ");
scanf("%d", &value);
sum += value;
if(value == 0)break;
}
```
Also, rather then usingwhile (1)with abreakcondition at the end, use ado..whileloop.
```
sum = 0;
do {
printf("Enter number: ");
scanf("%d", &value);
sum += value;
} while (value != 0);
```
|
Please explain to me why this program is printing12 12as output, and not7 7?
```
#include <stdio.h>
int addmult(int ii, int jj){
int kk, ll;
kk = ii + jj;
ll = ii * jj;
return(kk,ll);
}
int main(void) {
int i = 3, j = 4, k, l;
k = addmult(i,j);
l = addmult(i,j);
printf("\n%d\n%d",k,l);
}
```
|
C does not allow the returning of multiple values from the same function. You could create a structure that holds the 2 values inside the function and return that, but a better approach would be to just call the function once each time.
|
In C, the type of a string literal ischar [].
gdbdebugger:
```
(gdb) ptype ""
type = char [1]
(gdb) ptype "abc"
type = char [4]
```
lldbdebugger:
```
(lldb) p ""
(const char [1]) $0 = ""
(lldb) p "abc"
(const char [4]) $1 = "abc"
```
Thegdbdebugger shows type of string literal aschar [N](which is as per language standard) butlldbdebugger showsconsttype-qualifier in string literal type -const char [N].Is this a bug inlldbdebugger? Or, am I missing something?
|
Quotingcppreference.com:
"String literals arenot modifiable(and in fact may be placed in read-only memory such as .rodata). If a program attempts to modify the static array formed by a string literal, the behavior is undefined."
lldbis just showing the type of the real memory under the hood even though it's formally reachable through a pointer to const.
|
why does this code work?
```
#include <stdio.h>
void func(int v[]){
v[0] = 1;
}
int main(){
int v[5] = {0};
func(v);
for (int i = 0; i < 5; i++)
{
printf("%d ", v[i]);
}
}
```
The output I get from this is '1 0 0 0 0' but why? I'm not passing a pointer, why can the function change the array in my main?
|
Yes, you are passing a pointer.
When you writevoid func(int v[])to declare your function signature, it is equivalent to writingvoid func(int * v).
When you writefunc(v)to call your function, it is equivalent tofunc(&v[0]).
|
I am new to C programming.
I am trying to split a string using strtok(), using multiple delimiters. The line of code is :
```
char *token = strtok(st, " +-*/^()");
```
I want to know at which delimiter it got split. Is it possible? Please help.
I mean in this example whether the token got split at space, plus, minus, etc.
|
The functionstrtokchanges the found delimiter by the zero character'\0'. So it is impossible to determine what delimiter was encountered.
Instead of the functionstrtokyou can use functionsstrspnandstrcspn. Using these functions you can determine what delimiter was encountered.
For example
```
size_t n = strcspn( st, " +-*/^()" );
if ( st[n] != '\0' )
{
switch ( st[n] )
{
case ' ':
//...
break;
case '+':
//...
break;
//...
}
}
```
|
I am writing a code for Dots and boxes game in C and I need a function that exit the game and close the window based on an input from the user for example when he presses the letter 'e' on keyboard the game should close and I have no idea how to do that
|
There are also predefined exit codesEXIT_SUCCESSandEXIT_FAILURE
```
#include <stdlib.h>
...
exit(0);
...
```
e.g.exit(EXIT_SUCCESS);
|
I am writing a code for Dots and boxes game in C and I need a function that exit the game and close the window based on an input from the user for example when he presses the letter 'e' on keyboard the game should close and I have no idea how to do that
|
There are also predefined exit codesEXIT_SUCCESSandEXIT_FAILURE
```
#include <stdlib.h>
...
exit(0);
...
```
e.g.exit(EXIT_SUCCESS);
|
Why is it that the computer/compiler "reads"a=b+afrom right to left but notfloat b=a+1.2, a=1.0?Both lines of code being completely unrelated.
If the compiler does read from right to left then this:float a=1.0, b=a+1.2should give an error because "a" hasn't been declared yet, right?
Isfloat a=1.0, b=a+1.2logically correct orfloat b=a+1.2, a=1.0?
Background:I am just starting out C programming, and this is my 3rd program after hello world. So please keep that in mind while answering.
Thanks.
|
The compiler does not 'read' in any particular direction -- the scope of a variable name starts at the declarator for the variable and extends to the end of the block containing the declaration (or the file if at global scope). So it includes both the initializer of the declarator and any subsequent declarators in the same declaration, and any subsequent declarations.
|
I've tried using printf to print a zero width spaceprintf("%c", '');
I get a warning whenever I try compilingwarning: multi-character character constant [-Wmultichar]And when I run the program, I get whitespaces instead of the invisible character, so I placed letters in between the character to see if I get any different results, and it printed nothingprintf("a%cb\n", '');
|
The answer to this can be found from this postPrinting a Unicode Symbol in C
This will let you print any unicode character if you have the right code for it. In this case the 0 width space is0x200B
```
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
int main() {
setlocale(LC_CTYPE, "");
wchar_t space = 0x200B;
wprintf(L"%lc\n", space);
}
```
|
I'm new to coding and i need help with my project: so, what i need to do is code a "finding the two same cards game", in which every card has a number and we're basically trying to find that two equal numbers. those numbers should be generated withrand()function but i cannot think a way to how to make two random numbers equal to each other if I'm using therand()function. i don't know if i worded this the best way but i hope you get what i mean and if you don't I'm open to explain it with an example.
thanx in advance!
|
Just create half as many elements and duplicate them. You can actually take consecutive numbers and shuffle them. This way you make sure every number is repeated exactly once:
```
int main()
{
enum { size = 10 };
int cards[size];
for (int i = 0; i != size / 2; ++i)
{
cards[i] = i;
cards[size/2 + i] = i;
}
// now shuffle the array
}
```
|
When I type '#' vscode suggests "#pragma region" and "#pragma endregion". I never use those snippets and the suggestions can be quite annoying especially if I intend to navigate using arrow keys after typing '#'. I figured out that the suggestions come from snippets in the built-in extension "C/C++ Language Basics". Disabling that extension is not an option because syntax highlighting goes away with it.
|
Individual snippets may be disabled by opening the command palette (ctrl+shift+p), typing "insert snippet", pressing enter, and clicking with the mouse on the pictogram of an eye with a line over it thus removing the line.
I don't know how to do the last part without a mouse. If you know please comment.
|
This question already has answers here:When can I use a forward declaration?(13 answers)What are forward declarations in C++?(8 answers)Closed1 year ago.
Please refer to the attached screenshot of two different implementations of a JPEG library file (linux/windows). Filename is/libijg12/jcarith.c
One of them has an extra macro, both have the same function name.
My question is:
Does the first version is overridden by the second one?
|
In the one in the right (Windows) the top one is just a declaration or prototype, it does not include the body of the function. Declarations come usually in headers. In this case, it's unusual that the author put the declaration together with the definition of the function. The opposite is more common - to place the body of a function in the header (inlined).
|
I want to write a function that will filter the input of the user and then give the filtered string back to the function that had called it.
Is this possible without creating an global variable as in my example?
```
#include <stdio.h>
char input[10]; //global variable is meh!
char* input_function() {
scanf("%s", input);
return input;
}
int main(void) {
printf("%s", input_function());
}
```
|
Create a character pointer in themain()function and then pass it as an argument toinput_function().
```
#include <stdio.h>
char* input_function(char* input) {
scanf("%s", input);
return input;
}
int main(void)
{
char input[10]; // Need to allocate space
printf("%s", input_function(input));
}
```
|
Alpine is a Linux distribution that I guess it must have the header files. How to solve it in alpine container?
|
linux-headersshould be installed exlicitly in alpine linux.
```
apk add linux-headers
```
|
Alpine is a Linux distribution that I guess it must have the header files. How to solve it in alpine container?
|
linux-headersshould be installed exlicitly in alpine linux.
```
apk add linux-headers
```
|
This question already has answers here:Why does division result in zero instead of a decimal?(5 answers)Closed1 year ago.
I am trying to do a division to get a decimal answer and every time I try it it returns either 1 or 0 which annoying as the actual answer is 0.017... as I am effectively doing 1/560 however I cannot just use this case as I want it to be variable, as in I want to be able to put in different values and do this function.
Here is my code:
```
float x = 1/width;
mat4 matrix =
{
{x, 0.0f, 0.0f, 0.0f},
{0.0f, 0.00416f, 0.0f, 0.0f},
{0.0f, 0.0f, 1.0f, 0.0f},
{0.0f, 0.0f, 0.0f, 1.0f},
};```
```
|
In code:
```
int width = 2;
float x = 1/width;
```
operation1/widthis integer division which is rounded to the nearest integer.
To perform floating point division do:
```
float x = 1.0f / width;
```
widthwill be automatically converted to float.
|
I have anUbuntu 17.04virtual machine. On this OS, that is shipped with GCC 6.x, I installed GCC4.9from official repository, then I compiled:
GCC4.7.0fromGCC 4.9GCC3.0.4from GCC4.7.0GCC2.95.3from GCC3.0.4
Now, when I build an old C code I receive this error on a multiline macro:
```
stray '\' in program
```
I wrote a Python script for automatically change the line terminators from Windows one (CRLF) to Linux one. In this way the code is compiled fine.
Is there a way for GCC 2.95.3 to correctly understand the code without changes? AFAIK GCC must understands well the difference
|
I removed all CRLF with my Python script and the code compiles fine without any errors
|
Trying to compile a c project then encountered error like below
```
undefined reference to `__llvm_profile_instrument_target'
undefined reference to `llvm_gcda_start_file'
undefined reference to `llvm_gcov_init'
```
|
It works withllvmcompiler too, just add--coverage.
https://clang.llvm.org/docs/SourceBasedCodeCoverage.html
|
In theuser.h
https://github.com/mit-pdos/xv6-riscv/blob/a1da53a5a12e21b44a2c79d962a437fa2107627c/user/user.h#L6
exit is only syscall defined this wayint exit(int) __attribute__((noreturn));why this is needed for the exit function declaration?
|
I don't think thenoreturnattribute is strictly required, but it helps.
Thenoreturnattribute tells the compiler that theexitfunction will never return. In theory, this allows the compiler to better understand the possible code paths of any code that callsexit, so it can display more accurate warnings and optimize the code better.
|
I have anUbuntu 17.04virtual machine. On this OS, that is shipped with GCC 6.x, I installed GCC4.9from official repository, then I compiled:
GCC4.7.0fromGCC 4.9GCC3.0.4from GCC4.7.0GCC2.95.3from GCC3.0.4
Now, when I build an old C code I receive this error on a multiline macro:
```
stray '\' in program
```
I wrote a Python script for automatically change the line terminators from Windows one (CRLF) to Linux one. In this way the code is compiled fine.
Is there a way for GCC 2.95.3 to correctly understand the code without changes? AFAIK GCC must understands well the difference
|
I removed all CRLF with my Python script and the code compiles fine without any errors
|
Trying to compile a c project then encountered error like below
```
undefined reference to `__llvm_profile_instrument_target'
undefined reference to `llvm_gcda_start_file'
undefined reference to `llvm_gcov_init'
```
|
It works withllvmcompiler too, just add--coverage.
https://clang.llvm.org/docs/SourceBasedCodeCoverage.html
|
In theuser.h
https://github.com/mit-pdos/xv6-riscv/blob/a1da53a5a12e21b44a2c79d962a437fa2107627c/user/user.h#L6
exit is only syscall defined this wayint exit(int) __attribute__((noreturn));why this is needed for the exit function declaration?
|
I don't think thenoreturnattribute is strictly required, but it helps.
Thenoreturnattribute tells the compiler that theexitfunction will never return. In theory, this allows the compiler to better understand the possible code paths of any code that callsexit, so it can display more accurate warnings and optimize the code better.
|
Instead of writing anifor aswitchstatement, like this:
```
if (a == 1)
<some code here 1>
else if (a == 2)
<some code here 2>
else if (a == 3)
<some code here 3>
```
I want to run somthing like this:
```
l[1] = here1;
l[2] = here2;
l[3] = here3;
goto l[a];
here1:
<some code here 1>
here2:
<some code here 2>
here3:
<some code here 3>
```
Is it possible to do this in C?
|
No it isn't but there is a GCC extension for that.https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html#Labels-as-Values.
So your code would be:
```
void *l[3] = {&&here1, &&here2, &&here2};
goto *l[a];
here1:
<some code here 1>
here2:
<some code here 2>
here3:
<some code here 3>
```
|
I am trying to understand the commaOperatorin C and I have encountered this compilation error. Can somebody help me?
```
#include <stdio.h>
int main(void)
{
int a = (1,2);
printf("%d", a);
}
```
I am using a GCC compiler.
I expect the variable "a" value to equal 2 and print it out as output by the printf. But the following warning is generated.
Output:
```
test.c:5:11: warning: expression result unused [-Wunused-value]
int a = (1,2);
^
1 warning generated.
```
|
Your compiler is configured to treat warnings as being fatal. Normally it is not a good idea to disable that but for this experimental case you can disable it with-Wno-error.
```
$ gcc -Wno-error test.c
test.c:9:14: warning: expression result unused [-Wunused-value]
int a = (1,2);
^
1 warning generated.
$ ./a.out
2
```
|
How can I copy a file without using standard C library functions in Linux? In other words, I would like to copy a file directly with system calls. Is it possible?
|
file directly with system calls. Is it possible?
In pseudocode, usingsendfile:
```
int in = open("input", ...);
fstatat(in, &stat);
int out = open("output", ...);
sendfile(in, out, NULL, stat.st_size);
```
|
This question already has an answer here:Double data type giving garbage value as output after taking input through scanf()(1 answer)Closed1 year ago.
When I use float, like this:
```
#include <stdio.h>
int main()
{
float g;
float f;
scanf("%f", &f);
g = f / .5;
printf("%f", g);
return 0;
}
```
and enter 2 I get back 4.000. When instead in the place offloatI usedoublethe result is always 0.000. Why is this am I missing something?
|
```
#include <stdio.h>
int main()
{
double g;
double f;
scanf("%lf", &f);
g = f / .5;
printf("%lf", g);
return 0;
}
```
You need to use the format specifier specifically for doubles (%lf) here.
Seeformat string specificationsfor more information about different format specifiers.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.