question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
Let's say I have aforloop and an array of ints. In myforloop, I sayif (array[i] == 2)then I want to skip all the rest of theforloop and go to the next instance. now I can't use thebreakkeyword as that will exit out of the entire loop.
What can I use to exit out of only one instance?
|
You have to use continue to go to the next iteration:
```
if (array[i] == 2) continue;
```
|
I would like to know which case is SIG_ERR among the return values of the signal function.
```
__sighandler_t oldHandler = signal( SIGSEGV, newSignalHandler );
if( oldHandler == SIG_ERR )
{
// In what case?
}
```
|
The man page for each system call is supposed to list all possible error conditions under the "ERRORS" heading, along with the corresponding values to whicherrnois set in each case.
Theman page forsignal(2)shows only:
EINVALsignumis invalid.
This occurs ifsignum(the first argument) isn't the number of a valid signal, or is eitherSIGKILLorSIGSTOPwhich cannot be caught or ignored.
As such, if you have passedSIGSEGVas the first argument,signal()should never fail.
(I initially thought it could also fail ifhandlerwas an invalid pointer, but it seems in this case that it just installs the invalid pointer as the handler, and thus will segfault or otherwise misbehave should the signal actually be raised.)
|
I expected to find a function along the lines ofkobject_check_refcount, that returned the current refcount without altering it, inkobject.c, but as far as I can see there isn't one. Is there such a function existing in the kernel source somewhere? I can see it being useful for debugging purposes at points.
Edit: foundkref_readwhich sounds like it fits the bill. Just testing to see if it works as I'm expecting.
|
Yes, looks likekref_readis the right way to go.
```
static inline unsigned int kref_read(const struct kref *kref)
{
return refcount_read(&kref->refcount);
}
```
|
I want to build a counting table from 1 to 20 using inner for loop but instead of using multiplication, I want to use summation to build up my answer.
I wrote this code and for only number 1, I can see the correct answer.From number 2, I see that it adds up from the 10th multiplication.
I want to correct my logic error here in this code and any help is highly appreciated.
```
#include <stdio.h>
int main()
{
int m , n=1;
int i;
m = 0;
for(n = 1; n <= 20; n++){
for(i = 1; i <= 10; i++){
m = m + n;
printf("%d * %d = %d\n", n, i, m);
}
}
return 0;
}
```
|
```
#include <stdio.h>
int main(void)
{
int m, n, i;
for (n = 1; n <= 20; n++) {
// reset m before additions
m = 0;
for (i = 1; i <= 10; i++) {
m += n;
printf("%d * %d = %d\n", n, i, m);
}
}
return (0);
}
```
|
I really can't understand what is wrong with my code. My teacher said to addtime.handprocess.hbut still doesn't work. I am usingTDM-GCC-64.Code:
```
#include <conio.h>
#include <string.h>
#include <process.h>
#include <time.h>
int main()
{
char str[30];
int i;
printf("Enter the string: ");
scanf("%s",str);
for(i=0;str[i]!='\0';i++)
{
printf("%c",str[i]);
delay(1000);
}
return 0;
}
```
|
There is nodelayfunction. You should usesleepinstead.
So instead of
```
delay(1000);
```
do
```
sleep(1); // sleep 1 second
```
Don't forget to include <unistd.h>
|
I want to build a counting table from 1 to 20 using inner for loop but instead of using multiplication, I want to use summation to build up my answer.
I wrote this code and for only number 1, I can see the correct answer.From number 2, I see that it adds up from the 10th multiplication.
I want to correct my logic error here in this code and any help is highly appreciated.
```
#include <stdio.h>
int main()
{
int m , n=1;
int i;
m = 0;
for(n = 1; n <= 20; n++){
for(i = 1; i <= 10; i++){
m = m + n;
printf("%d * %d = %d\n", n, i, m);
}
}
return 0;
}
```
|
```
#include <stdio.h>
int main(void)
{
int m, n, i;
for (n = 1; n <= 20; n++) {
// reset m before additions
m = 0;
for (i = 1; i <= 10; i++) {
m += n;
printf("%d * %d = %d\n", n, i, m);
}
}
return (0);
}
```
|
I really can't understand what is wrong with my code. My teacher said to addtime.handprocess.hbut still doesn't work. I am usingTDM-GCC-64.Code:
```
#include <conio.h>
#include <string.h>
#include <process.h>
#include <time.h>
int main()
{
char str[30];
int i;
printf("Enter the string: ");
scanf("%s",str);
for(i=0;str[i]!='\0';i++)
{
printf("%c",str[i]);
delay(1000);
}
return 0;
}
```
|
There is nodelayfunction. You should usesleepinstead.
So instead of
```
delay(1000);
```
do
```
sleep(1); // sleep 1 second
```
Don't forget to include <unistd.h>
|
Ifdbstands forDefine Byteand can hold 8 bits (1 byte), why can we use a 6 bytes string withdb? I know that one character is only 1 byte, anddbholds 1 byte.
```
section .data
text db "Yellow"
```
dbis playing like acharin more high level languages (compared to asm), which we can just increase the buffer, but assembly does it automatically?
```
#include <stdio.h>
int main(void)
{
char c = 'Y';
char string[7] = "Yellow";
return 42;
}
```
|
The data definitionsdb,dw,dd,dqetc. accept more than one value, they are stored successively. For example
```
db 'Y', 'e', 'l', 'l', 'o', 'w', 0
```
is assembled as
```
59 65 6C 6C 6F 77 00
```
Since it is cumbersome to specify all characters individually, there is the notation as a string, both are equivalent:
```
db "Yellow", 0
```
Please note that the terminating zero byte must be specified separately in assembly (in contrast to C).
|
I was reading a C reference about linkage (external, internal and none) and came across the following:
If, within a translation unit, the same identifier appears with both
internal and external linkage, the behavior is undefined.
I wanted to know how this undefined behavior can occur. Based on what I had read, a variable can have only one storage class. So it cannot be declared bothstaticandexternat the same time.
So in what scenario can a variable have both internal and external linkage?
|
In this code:
```
extern int x;
static int x;
```
The first declaration saysxhas external linkage, and the second declaration says it has internal linkage.
|
I am writing a function that takes in a user entered string consisting of o's g's and c's only. I would like to make an if statement that says if string contains any other character besides these three (reading string from left to right), return false, or something like that. How do I go through the string as an array to do this?
|
```
if (s[strspn(s, "ogc")] != 0) {
/* s contains a character other than o, g or c */
}
```
strspn(s, chars)returns the length of the longest prefix ofscontaining only characters inchars. Ifscontains only such characters, that prefix is all ofs, so the character at that index will be the NUL terminator.
If your string might contain a newline or other whitespace after the desired characters, you'll need to adjust the test accordingly.
Seeman strspnfor more information.
|
Imagine I have a struct for a linked list:
```
struct node{
int data;
struct node* next;
struct node* prev;
};
```
I free the last node; does thenextpointer of the node before it becomeNULLautomatically?
Because I noticed I didn't do it in a program but everything runs fine..
|
No.
As for why your program appeared to run OK even if you forgot to reset a pointer, it could be you just got lucky.
|
This question already has answers here:Meaning of U suffix(2 answers)What does 'u' mean after a number?(5 answers)Closed3 years ago.
I am using stm32f407vg and there is a library called HAL library however there is a statemet or definition not sure to return an error message and it like return 0x00U or 0x01U if certain condition met so what is the purpose of those U's i wonder ?
|
uis the "unsigned-suffix" and on its own makes an integer constantunsigned int,unsigned long intorunsigned long long intdepending on the value.
In the C standard, see section 6.4.4.1 (Integer constants) paragraph 5.
|
This question already has answers here:How do I run two commands in one line in Windows CMD?(23 answers)Closed3 years ago.
In macOS whenever I compile and execute my code I use
g++ name.cpp && ./a.out
but in Windows it doesn't work for compile and run i use
```
g++ name.cpp
./a.exe
```
I'm using command prompt.
g++ name.cpp && ./a.exe doesn't work.
But i want to use a single line command like i used to do in macOS
|
In Windows, backslash (or yen mark on some font) is used as separator of directory.
```
g++ name.cpp && .\a.exe
```
worked on Command Prompt (but not on PowerShell).
|
I am unexperienced in C and have a question.
I wanted to ask how to read the hexadecimal numbers out and get into an array
```
#define configMAC_ADDR \
{ \
0x02, 0x12, 0x13, 0x10, 0x15, 0x11 \
}
```
|
The macro is the same as writing{ 0x02, 0x12, 0x13, 0x10, 0x15, 0x11 }. So where you would have normally written that initializer list in your source code, writeconfigMAC_ADDRinstead. It's just text replacement in this case.
The\symbol can appear anywhere in C code and means source code line break. You can use it to break up a long line of code into several and have the compiler treat them as a single line still, so it is commonly used for macros. Without it you'd have to write the macro as:
```
#define configMAC_ADDR { 0x02, 0x12, 0x13, 0x10, 0x15, 0x11 }
```
Which is 100% equivalent but in some cases less readable.
|
I would very much appreciate some explanation, why I misuse memcpy i.e. why the output of the following code is inproper:
```
int main()
{
int array[5] = {1, 2, 3, 4, 5};
int *ptr = malloc(sizeof(int) * 5);
memcpy(ptr, array, 5);
printf("%d\n", ptr[0] );
printf("%d\n", ptr[1] );
printf("%d\n", ptr[2] );
printf("%d\n", ptr[3] );
printf("%d\n", ptr[4] );
free(ptr);
return 0;
}
```
the output is: 1 2 0 0 0
|
The 3rd argument ofmemcpy()is number ofbytesto copy, not number ofelements.
In this case,
```
memcpy(ptr, array, 5);
```
should be
```
memcpy(ptr, array, sizeof(int) * 5);
```
or
```
memcpy(ptr, array, sizeof(*ptr) * 5);
```
or
```
/* copy the whole array, no *5 in this case */
memcpy(ptr, array, sizeof(array));
```
|
I try to learn to binary read blocks of data, instead to read the values one by one. I succesfully read the blocks which contains N bytes of data, but if the last block is not N bytes, the data is lost, because of the while condition.
```
#include<stdio.h>
#include<stdlib.h>
int main(){
int buffer[512];
FILE *data = fopen("new_file.bin","rb");
while( fread(&buffer,sizeof(int),512,data) )
{
... do something
}
return 0;
}
```
If the next block is for example 400 bytes, then the data from that block won't be used. Any idea how can I read all the data till EOF ?
|
Instead of reading N-byte blocks, you should read N 1-byte blocks.
```
#include<stdio.h>
#include<stdlib.h>
#define N 2048
int main(){
char buffer[N];
FILE *data = fopen("new_file.bin","rb");
size_t size_read;
while( (size_read = fread(buffer,1,N,data)) > 0 )
{
... do something
}
return 0;
}
```
|
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.Closed3 years ago.Improve this question
If we set a STATIC REGISTER variable we can optimize the time of use of the variable as well as keep its value from read to read? its that always true, somtimes ture somtimes not or always wrong?
|
The statement is always wrong because we will get compilation error for using bothstaticandregisterfor one variable.
Example:
```
#include <stdio.h>
void foo(void) {
static register int i = 0;
printf("%d\n", i++);
}
int main(void) {
int i;
for (i = 0; i < 10; i++) foo();
return 0;
}
```
I got this error:
```
prog.c: In function 'foo':
prog.c:4:5: error: multiple storage classes in declaration specifiers
4 | static register int i = 0;
| ^~~~~~
```
|
This question already has answers here:How do I run two commands in one line in Windows CMD?(23 answers)Closed3 years ago.
In macOS whenever I compile and execute my code I use
g++ name.cpp && ./a.out
but in Windows it doesn't work for compile and run i use
```
g++ name.cpp
./a.exe
```
I'm using command prompt.
g++ name.cpp && ./a.exe doesn't work.
But i want to use a single line command like i used to do in macOS
|
In Windows, backslash (or yen mark on some font) is used as separator of directory.
```
g++ name.cpp && .\a.exe
```
worked on Command Prompt (but not on PowerShell).
|
I am unexperienced in C and have a question.
I wanted to ask how to read the hexadecimal numbers out and get into an array
```
#define configMAC_ADDR \
{ \
0x02, 0x12, 0x13, 0x10, 0x15, 0x11 \
}
```
|
The macro is the same as writing{ 0x02, 0x12, 0x13, 0x10, 0x15, 0x11 }. So where you would have normally written that initializer list in your source code, writeconfigMAC_ADDRinstead. It's just text replacement in this case.
The\symbol can appear anywhere in C code and means source code line break. You can use it to break up a long line of code into several and have the compiler treat them as a single line still, so it is commonly used for macros. Without it you'd have to write the macro as:
```
#define configMAC_ADDR { 0x02, 0x12, 0x13, 0x10, 0x15, 0x11 }
```
Which is 100% equivalent but in some cases less readable.
|
I would very much appreciate some explanation, why I misuse memcpy i.e. why the output of the following code is inproper:
```
int main()
{
int array[5] = {1, 2, 3, 4, 5};
int *ptr = malloc(sizeof(int) * 5);
memcpy(ptr, array, 5);
printf("%d\n", ptr[0] );
printf("%d\n", ptr[1] );
printf("%d\n", ptr[2] );
printf("%d\n", ptr[3] );
printf("%d\n", ptr[4] );
free(ptr);
return 0;
}
```
the output is: 1 2 0 0 0
|
The 3rd argument ofmemcpy()is number ofbytesto copy, not number ofelements.
In this case,
```
memcpy(ptr, array, 5);
```
should be
```
memcpy(ptr, array, sizeof(int) * 5);
```
or
```
memcpy(ptr, array, sizeof(*ptr) * 5);
```
or
```
/* copy the whole array, no *5 in this case */
memcpy(ptr, array, sizeof(array));
```
|
I try to learn to binary read blocks of data, instead to read the values one by one. I succesfully read the blocks which contains N bytes of data, but if the last block is not N bytes, the data is lost, because of the while condition.
```
#include<stdio.h>
#include<stdlib.h>
int main(){
int buffer[512];
FILE *data = fopen("new_file.bin","rb");
while( fread(&buffer,sizeof(int),512,data) )
{
... do something
}
return 0;
}
```
If the next block is for example 400 bytes, then the data from that block won't be used. Any idea how can I read all the data till EOF ?
|
Instead of reading N-byte blocks, you should read N 1-byte blocks.
```
#include<stdio.h>
#include<stdlib.h>
#define N 2048
int main(){
char buffer[N];
FILE *data = fopen("new_file.bin","rb");
size_t size_read;
while( (size_read = fread(buffer,1,N,data)) > 0 )
{
... do something
}
return 0;
}
```
|
I have been developing my own function block in Scilab/Xcos on the C block basis and I have been struggling with passing parameters defined in the simulation context into the C code. Does anybody know how to do that? Thanks in advance for any ideas.
|
I have found functional solution. Let's say I have following parameters defined in the simulation context:T, RS, RR, LL, LM, pp, K. In case I place instance of the C block into the simulation and double click on it following window opens
Then I fill in the parameters which I want to pass into the C block instance (text field Real parameters vector). The parameters values are then accessible in the C language code inside the C block viablock->rpar[0](parameter Ts),block->rpar[1](parameter RS),block->rpar[2](parameter RR),block->rpar[3](parameter LL),block->rpar[4](parameter LM),block->rpar[5](parameter pp),block->rpar[6](parameter K)`.
|
As I readhereinline functions doesn't have to be inlined. So let's say we have code like this:
```
int a = 0;
inline void myFunc(){
extern int a;
a = 1;
}
int main(){
int a = 0;
myFunc();
}
```
Does standard guarantee whichavariable will be assigned1?Are inline function compiled to a certain code before inlining? If so, what if I useregisterkeyword forainmain?
EDIT: the globalint adoesn't have to be declared in the same .c file
|
Inlining a function does not introduce it into the caller's scope. Identifiers declared within a function (such asainmainin your example) are not visible from other functions.
Soinlineis irrelevant, and the top-levelais the one whose value is changed.
|
```
if ((a % 5) && (a % 11))
printf("The number %d is divisible by 5 and 11\n", a);
else
printf("%d number is not divisible by 5 and 11\n", a);
```
How will the logical&&operator work if I don't add== 0in the expression, if there is no remainder, will it look for the quotient? and the quotient will always be a non zero term so the programme will always return true.
|
In your code
```
if ((a % 5) && (a % 11))
```
is the same as
```
if ( ((a % 5) != 0) && ((a % 11) != 0 ) )
```
Any non-zero value is taken asTRUTHY.
|
Can anyone explain how does this work the output is A3 but how come it print 3
```
#include <stdio.h>
int main() {
int i;
if(printf("A"))
i=3;
else
i=5;
printf("%d",i);
}
```
|
printf()returns the number of characters upon success and negative values on failure.
Therefore, ifprintf("A")succeeds, it will return1.
In C, values other than0is treated as true, soi=3;is executed.
|
I'm new toCprogramming language.I'm aware offunctiondeclaration:
```
// declaring function
void getMax();
```
As well aspointer:
```
//declaring pointer to char
char *p
```
But could you give me the cue what is declaredwith a combination of the above two syntax constructs:
```
static PyObject * spam_system(PyObject *self, PyObject *args){
//some code here
}
```
?
|
static PyObject * spam_system(PyObject *self, PyObject *args)
It's a definition of a static function calledspam_system, returning a pointer to aPyObjectand taking two parameters,selfandargs, both are pointers toPyObject.
What does it mean, if a function is static? A static function is a function that is only visible to other functions in the sametranslation unit.
|
I have been developing my own function block in Scilab/Xcos on the C block basis and I have been struggling with passing parameters defined in the simulation context into the C code. Does anybody know how to do that? Thanks in advance for any ideas.
|
I have found functional solution. Let's say I have following parameters defined in the simulation context:T, RS, RR, LL, LM, pp, K. In case I place instance of the C block into the simulation and double click on it following window opens
Then I fill in the parameters which I want to pass into the C block instance (text field Real parameters vector). The parameters values are then accessible in the C language code inside the C block viablock->rpar[0](parameter Ts),block->rpar[1](parameter RS),block->rpar[2](parameter RR),block->rpar[3](parameter LL),block->rpar[4](parameter LM),block->rpar[5](parameter pp),block->rpar[6](parameter K)`.
|
As I readhereinline functions doesn't have to be inlined. So let's say we have code like this:
```
int a = 0;
inline void myFunc(){
extern int a;
a = 1;
}
int main(){
int a = 0;
myFunc();
}
```
Does standard guarantee whichavariable will be assigned1?Are inline function compiled to a certain code before inlining? If so, what if I useregisterkeyword forainmain?
EDIT: the globalint adoesn't have to be declared in the same .c file
|
Inlining a function does not introduce it into the caller's scope. Identifiers declared within a function (such asainmainin your example) are not visible from other functions.
Soinlineis irrelevant, and the top-levelais the one whose value is changed.
|
```
if ((a % 5) && (a % 11))
printf("The number %d is divisible by 5 and 11\n", a);
else
printf("%d number is not divisible by 5 and 11\n", a);
```
How will the logical&&operator work if I don't add== 0in the expression, if there is no remainder, will it look for the quotient? and the quotient will always be a non zero term so the programme will always return true.
|
In your code
```
if ((a % 5) && (a % 11))
```
is the same as
```
if ( ((a % 5) != 0) && ((a % 11) != 0 ) )
```
Any non-zero value is taken asTRUTHY.
|
I'm a little new to C still, so bear with me.
I am attempting to be able to refer to the elements of a structure via an index. I figured a macro would do the trick, but evidently not. Can anyone explain why the following does not work?
```
#include <stdio.h>
#define E(Structure, Index) Structure.var_Index
typedef struct test{
int var_0;
}TEST;
int main(){
TEST Test;
E(Test, 0) = 0;
return(0);
}
```
My IDE says "No member named 'var_Index' in 'struct test'," but I have no # in front of the word Index in the macro.
|
Merging tokens is done with##
The following change should work:
```
#define E(Structure, Index) Structure.var_##Index
```
|
What does the code below print when running the function print_test()?
```
struct test {
int a, b, c;
};
void print_test(void) {
struct test t = {1};
printf("%d/%d/%d", t.a, t.b, t.c);
}
```
Solution 1\0\0
Why are b and c initialized to zero even though I did not do it? Are there any default values for the struct?
However, the struct is not global and the member is not static. Why are they automatically zero-initialized? And if the data type were not int another data type to which value will be initialized?
|
If you don't specify enough initializers for all members of a struct, you'll faceZero initialization, which will initialize remaining members to0. I think by today's standards this seems a bit odd, especially because C++'s initialization syntax has evolved and matured a lot over the years. But this behavior remains for backwards-compatibility.
|
I am using the library to apply to my project
But I'm not sure what this means.
Is the unit of 127 pixels?
```
LOGICAL_ MINIMUM(1), 0x81, // LOGICAL_ MINIMUM (-127)
LOGICAL_ MAXIMUM(1), 0x7f, // LOGICAL_ MAXIMUM (127)
REPORT_ SIZE(1), 0x08, // REPORT_ SIZE (8)
REPORT_ COUNT(1), 0x01, // REPORT_ COUNT (1)
```
ESP32-BLE-Mouse
|
These values are used to determine the resolution multiplier for the mouse wheel, i.e. how much should be scrolled for oneclickof the mouse wheel.
For detailed documentation, seehttps://www.usb.org/sites/default/files/hut1_2.pdfon page 37.
In your case
the Wheel control delivers one count per detent via a 1-byte field of an Input Report.
This means that you can send from -127 to 127 clicks at a time to the device you are connected to (in your case the iPhone). The OS then translates this to a scroll length in pixels or other metric it uses.
|
I have an old .so file with a very complex clang parser in it and I have to call it from a go module.
```
...
lib := C.dlopen(C.CString("./resources/bin/parser.so"), C.RTLD_LAZY)
functions_address := C.dlsym(lib, C.CString("parse"))
```
|
I have solved this by defining a C typedef, creating a helper method and passing the "functions_address" to that helper method which calls the other function by reference
```
typedef char (*parse) (char *file);
char bridge (parse p, char* file) {
p(file);
}
```
|
I want to print my string which is "Something"without the first N lettersinside theprintfstatement.
Example 1: I can do the "opposite" (printfjust N first letters):
```
#include <stdio.h>
int main() {
char str[] = "Something";
printf("%5s", str);
}
```
Output:Somet
Expected Output:hing
|
Start the printing in the middle:
```
printf("%s", &str[5]);
```
|
Syntax of for loop:
```
for(initialization;condition;increment/decrement){
statements;
}
```
Why is the below code running infinite times and then why there is no syntax error?
```
int x=10;
for(x++;x++;x++){
printf("\n %d",x);
}
```
|
The 3 clauses of theforloop are optional and the only requirement is that they should be valid expressions - the first one could optionally contain a variable declaration. The syntax is valid.
In the 2nd clause the result of the expression is used as a check against zero. You start at 10, so the first check reads the value 10, and so on. It is never zero so the loop won't terminate.
Other than that, there is a sequence point after eachforclause, so the code is also valid as far as sequencing goes. This code will of keep counting up until it hits integer overflow, which is undefined behavior.
|
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.Closed3 years ago.Improve this question
In a recent interview, I was asked the following coding problem. Could someone please help me understand how to address this problem in terms of C coding?
Q.
A processor has a 16*16 multiplier to represent 32-bit value.Take two 32 bit value, multiply them and return in 64 bit format.
|
Let's call the 32 bit numbers A and B. Now, let's split them into 16 bit numbers, a0/b0 and a1/b1 (a0 is the bigger part).
Now,A*B == (a0<<16+a1) * (b0<<16+b1) == (a0 * b0) << 32 + (a1 * b0 + a0 * b1) << 16 + a1 * b1.
note: All the multiplications here are for 16 bit numbers (a0,a1,b0,b1) with the result as 32 bit number casted into 64 bit (the bigger 32 bits of the number are 0).
|
I'm reading thezlib manual, and am wondering about the gzread function:
ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
This gives the number of uncompressed bytes, but does anything else come of this function? I'm skeptical this is the case (because not a pointer is passed to the function it seems,voidp buf), but does gzread also "read" the data intovoidp buf?
Is there an analogue to gzread in the standard library (like gzopen ~ fopen)?
I'm reading a project calledklib, and in one of the files (kseq.h, line 91), gzread is called (there it will be called__read, but I am reading another project,hickit, which calls it asgzread), and wondering if gzread modifies the buf value or not.
|
Yes, up tolenbytes are written tobuf.
|
From the C18 standard (6.7.9):
If the declaration of an identifier hasblock scope, and the
identifier has external orinternal linkage, the declaration shall
have no initializer for the identifier.
I have no problem with block scope + external linkage. But, I can't see how can an identifier have block scope and internal linkage. Is that even possible?
|
If your global is defined
```
static int hui;
```
it has internal linkage. Then
```
void f(void) {
extern int hui;
}
```
refers to the same object with internal linkage, even if the keyword saysextern.
Soexternis a misnomer and should probably belinkageor so.
|
I have this line of code:
```
#define ALPHABET_SIZE 'z' - 'a' + 1
```
When I hover over ALPHABET_SIZE anywhere in my code it tells me that it expands to'z' - 'a' + 1.
So I wondered if this expression has to be recomputed each time I use ALPHABET_SIZE in my code? If so, how can I prevent the recomputation?
|
```
#define ALPHABET_SIZE 'z' - 'a' + 1
```
The pre-processor replaces eachALPHABET_SIZE
With
```
'z' - 'a' + 1
```
The compiler then will most probably performConstant foldingoptimization replacing the computation with 26.
Demohttps://godbolt.org/z/Mo46db, the expression is replaced by26with gcc 10.2
|
I have a problem when it comes to running gdb. I've been given two files. the source codehello.cand a 64-bit ELF calledhello
I want to run gdb but when I rungdb ./helloI get the message(No debugging symbols found in hello)
I can't seem to find out why this happens, and I can't find anyone that has had the same problem before where the, this casehellofile is given. Any help is greatly appreciated!
|
compile the program again with the -g flag.
gcc -g -o hello hello.c
Run gdb with generated executable:
gdb ./hello
now you are able to see this kind of message:
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./hello...done.
(gdb)
|
From the C18 standard (6.7.9):
If the declaration of an identifier hasblock scope, and the
identifier has external orinternal linkage, the declaration shall
have no initializer for the identifier.
I have no problem with block scope + external linkage. But, I can't see how can an identifier have block scope and internal linkage. Is that even possible?
|
If your global is defined
```
static int hui;
```
it has internal linkage. Then
```
void f(void) {
extern int hui;
}
```
refers to the same object with internal linkage, even if the keyword saysextern.
Soexternis a misnomer and should probably belinkageor so.
|
I have this line of code:
```
#define ALPHABET_SIZE 'z' - 'a' + 1
```
When I hover over ALPHABET_SIZE anywhere in my code it tells me that it expands to'z' - 'a' + 1.
So I wondered if this expression has to be recomputed each time I use ALPHABET_SIZE in my code? If so, how can I prevent the recomputation?
|
```
#define ALPHABET_SIZE 'z' - 'a' + 1
```
The pre-processor replaces eachALPHABET_SIZE
With
```
'z' - 'a' + 1
```
The compiler then will most probably performConstant foldingoptimization replacing the computation with 26.
Demohttps://godbolt.org/z/Mo46db, the expression is replaced by26with gcc 10.2
|
I have a problem when it comes to running gdb. I've been given two files. the source codehello.cand a 64-bit ELF calledhello
I want to run gdb but when I rungdb ./helloI get the message(No debugging symbols found in hello)
I can't seem to find out why this happens, and I can't find anyone that has had the same problem before where the, this casehellofile is given. Any help is greatly appreciated!
|
compile the program again with the -g flag.
gcc -g -o hello hello.c
Run gdb with generated executable:
gdb ./hello
now you are able to see this kind of message:
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./hello...done.
(gdb)
|
Is there a specific word in C that is used to refer to a read-write variable? For example, if I have:
```
int a = 2;
const int b = 3;
```
I would refer tobas aconst. What would be the proper terminology to refer toa? (Non-const? Default? Writeable? etc.)
|
bisconst-qualifiedandaisunqualified/non-const-qualified.
constinCdoes not mean that its value cannot change, it just means thatyouas a programmer say that you're not going to change it. The value of aconst volatileobject may well be different on each access, hence it, too, would be ... variable?
|
Is there a way for me to name my exported dll functions? When I use a dll export viewer the function names shown are the full declarations. I would like to use the JNA (JNI) to access functions inside the DLL, and the function names need to be a function name not a full declaration. If this is a duplicate please point it out!
|
It can actually be done with just the __declspec(dllexport) syntax (that is, without a .def file) if you declare the function as extern "C" (or implement it in a C file instead of C++).
```
extern "C"
{
__declspec(dllexport) void __stdcall MyFunc(std::string &);
}
```
Generally much easier than exporting a mangled name with an alias (as you then need to track down the mangled name in order to assign an alias).
|
I have problem with NVIC registers in Keil.
in my data sheet NVIC starts with NVIC_ISERx
But in keil starts with ICTR register
So I have problem with matching addresses
|
the order of the properties is not the same as the order in the peripheral.
It is clearly visible here:
|
As in the title, what does the name of thetimespecstruct intime.hfrom the C standard library stand for?
Is it a "time specification"?
If yes, then what does that mean?
|
what does the name of the timespec struct in time.h from the C standard library stand for?
Time specification.
Is it a "time specification"?
Yes.
If yes, then what does that mean?
Looking atoxford specification meaningand also of time, a "time specification" ortimespecstructure in this context means:
A C language description of how something is or can be measured in seconds and nanoseconds.
|
I wanna make a "Hello, (name)." function in Python by trying to make the Cprintffunction.
I want to turn it from this:
```
name = input("What's your name? ")
print(f"Hello, {name}.")
```
Into this:
```
name = input("What's your name? ")
printf("Hello, %s.", name)
```
I started off the function like this and I knew it wasn't going to work because of the second argument:
```
def printf(text, ...):
print(text)
```
How can I make a properly working printf function like this?
|
```
def printf(text, *args):
print(text % args)
```
That should do the trick, but perhaps just use an f string like you did in the first example, no need to "reinvent the wheel" right?
|
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.Closed3 years ago.Improve this question
Why does when I run the random() function in a while loop it does not need a seed, but when I run it outside of a while loop it requires a seed? I am trying to generate random numbers in rapid succession.
|
code:
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int min;int max;
printf("Enter the random min and random max: ");
scanf("%d %d",&min,&max);
srand(time(NULL));
int ran_num = rand() % max + min;
printf("the random number is %d \n",ran_num);
return 0;
}
```
You can set the seeds like this:srand(time(NULL));,and why you use random function?
|
This question already has answers here:Reading data into an uninitialized char pointer variable using fgets crashes at the second read(2 answers)What is the trick behind strcpy()/uninitialized char pointer this code?(3 answers)Closed3 years ago.
```
#include<stdio.h>
int main()
{
char *string1;
scanf("%s",string1);
printf("\n\nstring 1 is %s\n",string1);
}
```
whenever I run this program it takes the input, but then stops working.
How do I take direct inputs in char pointers in C ?
|
You didn't allocate memory forstring1.
You can do it usingmalloc()function this way:
```
size_t string_size = 16;
char *string1 = (char*)malloc(string_size * sizeof(char));
```
This, the length of provided string should not exceed 15 characters.
|
I have two C programs:
Main.c
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
system("gcc x.c -o x");
system("x.exe");
return 0;
}
```
x.c
```
#include <stdio.h>
int main() {
printf("hello world!");
return 0;
}
```
FromMain.cI need to compile and runx.cwithout using the command line. I've tried this but the code didn't work.
Thanks
|
This function call will compile your file and run it in one line :
```
system("gcc x.c -o x && x.exe");
```
|
I have a function declared as:
```
int func(int a, int b, ...);
```
Then I want to #define a function-like macro as:
```
#define TEST(A,B) func(A,B,0)
```
But the compiler always complains: "error: expected declaration specifiers or '...', before numeric constant".
So, how can I eliminate this error?
|
Make sure the function is defined before the #define statement (could be imported too) so the compiler will the data type of a and b. Or you could also try type defining a and b as (int) a.
|
I'm attempting to useamazon-kinesis-video-streams-webrtc-sdk-cin a Swift project however I'm unsure of how to create aSignalingClientInfo struct. Specifically I'm unsure of how to properly construct theclientId:
```
var signalingClientInfo = SignalingClientInfo(
version: UINT32(SIGNALING_CLIENT_INFO_CURRENT_VERSION),
clientId: clientId,
loggingLevel: UINT32(1)
)
```
|
Kind of annoying, but fixed-sized arrays in C likeclientIdare imported into Swift as tuples.
There's on-going discussions on adding proper fixed-size arrays to Swift, but in the mean time, there are implementation-dependent tricks you can use to construct large tuples from arrays.
Seehttps://oleb.net/blog/2017/12/swift-imports-fixed-size-c-arrays-as-tuples/
Edit: it looks like the layout of homogeneous tuples isguaranteed. So this is safe, just annoying.
|
This question already has answers here:Reading data into an uninitialized char pointer variable using fgets crashes at the second read(2 answers)What is the trick behind strcpy()/uninitialized char pointer this code?(3 answers)Closed3 years ago.
```
#include<stdio.h>
int main()
{
char *string1;
scanf("%s",string1);
printf("\n\nstring 1 is %s\n",string1);
}
```
whenever I run this program it takes the input, but then stops working.
How do I take direct inputs in char pointers in C ?
|
You didn't allocate memory forstring1.
You can do it usingmalloc()function this way:
```
size_t string_size = 16;
char *string1 = (char*)malloc(string_size * sizeof(char));
```
This, the length of provided string should not exceed 15 characters.
|
I have two C programs:
Main.c
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
system("gcc x.c -o x");
system("x.exe");
return 0;
}
```
x.c
```
#include <stdio.h>
int main() {
printf("hello world!");
return 0;
}
```
FromMain.cI need to compile and runx.cwithout using the command line. I've tried this but the code didn't work.
Thanks
|
This function call will compile your file and run it in one line :
```
system("gcc x.c -o x && x.exe");
```
|
I have a function declared as:
```
int func(int a, int b, ...);
```
Then I want to #define a function-like macro as:
```
#define TEST(A,B) func(A,B,0)
```
But the compiler always complains: "error: expected declaration specifiers or '...', before numeric constant".
So, how can I eliminate this error?
|
Make sure the function is defined before the #define statement (could be imported too) so the compiler will the data type of a and b. Or you could also try type defining a and b as (int) a.
|
I'm attempting to useamazon-kinesis-video-streams-webrtc-sdk-cin a Swift project however I'm unsure of how to create aSignalingClientInfo struct. Specifically I'm unsure of how to properly construct theclientId:
```
var signalingClientInfo = SignalingClientInfo(
version: UINT32(SIGNALING_CLIENT_INFO_CURRENT_VERSION),
clientId: clientId,
loggingLevel: UINT32(1)
)
```
|
Kind of annoying, but fixed-sized arrays in C likeclientIdare imported into Swift as tuples.
There's on-going discussions on adding proper fixed-size arrays to Swift, but in the mean time, there are implementation-dependent tricks you can use to construct large tuples from arrays.
Seehttps://oleb.net/blog/2017/12/swift-imports-fixed-size-c-arrays-as-tuples/
Edit: it looks like the layout of homogeneous tuples isguaranteed. So this is safe, just annoying.
|
I am new in C so I need some help.
for example I have this struct object
```
struct Frac {
int num;
int dec
}
```
which i do this in c:
```
struct Frac fract1 = {1, 2};
struct Frac temp;
temp = fract1;
```
Is temp point to a copy of fract1 or is it pointing to the actual fract1?
I tried it on computer by printing the address and it is pointing to a copy of fract1.
If this is in Java, it will be pointing to the actual fract1. Do correct me if I am wrong. Can I ask why temp is pointing to a copy of fract1 in C instead of the actual object itself thanks!
|
Nothing is pointing to anything. Assignment copies values. Assignment always copies values. Sometimes those values are pointers, but if you don't see a pointer, there isn't a pointer. C doesn't have Java's dichotomy between simple types with value semantics and everything-else with reference semantics.
|
Below is my code:
```
//main.c
int f()
{
static int x = 0;
x += 1;
return x;
}
int main()
{
f();
printf("%d", f());
}
```
and the output is2.
I know that static variable will persist state, but since I calledf()twice, each timexis set to 0 first (static int x = 0;), then plus 1, then the output should be1regardless of how many times I callf()?
|
staticvariables not only persist, they are initialized once only, soxisnot"each time set to 0 first", it remains1in the second call and then gets incremented. So indeed
```
static int x = 0; // x is initialized once only
```
is very different from
```
static int x;
x = 0; // x is set to 0 with every call
```
|
This question already has answers here:Double Negation in C++(14 answers)Closed3 years ago.
Came across using!!in C++ during condition check
```
if ( !! (flag != 0 )){..
}
```
This could be directly used like
```
if( flag != 0 ){..
}
```
Is there any specific corner use case in C/C++ or is it just a form of coding style ?
|
In this case, it's superfluous, but in general this style is used to convert the actual expression value to
an integer type inC.a boolean type inC++.
|
I would like to figure out the memory address of the following:
```
>>> ($rbp + $rdi*2 - 8)
```
And then once I have that value, inspect that memory address with:
```
>>> x/wx $address
```
How would I do this in gdb?
|
You can type this in directly after thep(rint) command. For example:
```
>>> p/x ($rbp + $rdi*2 -8)
$2 = 0x7fffffffe43e
>>> x/hx $
0x7fffffffe43e: 0x001b # 27
```
The$symbol stores the last value.
|
I'm new to C, just a question on the header file, below is the code that uses the header file as recommended:
```
//test.h
extern int globalVariable;
```
```
//test.c
#include "test.h"
int globalVariable = 2020;
```
```
//main.c
#include <stdio.h>
#include "test.h"
int main()
{
printf("Value is %d", globalVariable);
}
```
I don't understand that why we need to put#include "test.h"intest.cfile, what's the benefit of doing it?
|
It actually doesn't, but it's a good practice.
If you wrote:
```
double globalVariable = 2020;
```
you would have undefined behavior. Now if you wrote
```
#include "test.h"
double globalVariable = 2020;
```
the compiler will catch your mistake. Since the same definition is available to all modules that useglobalVariableby including the same header file, such a mistake is much less likely.
|
QUESTION->
```
#include<stdio.h>
int main()
{
int a,*b,**c,***d;
int x;
a=&x;
b=&a;
c=&b;
d=&c;
printf("%d\t%d\t%d\t%d",a,b,c,d);
a++;
b++;
c++;
d++;
printf("\n%d\t%d\t%d\t%d",a,b,c,d);
return 0;
}
```
OUTPUT
```
-760636132 -760636128 -760636120 -760636112
-760636128 -760636120 -760636112 -760636104
```
Why after 2nd pointer all the pointers increment by a value of 8?
|
If you checked you would findsizeof(int) == 4andsizeof(int*) == 8. When you print the pointer you see the actual value. Incrementing the pointer adds the size of what the pointer points to.
You are very close to undefined behavior. If you tried to read what these pointers pointed to (or worse, write to them), the results could be very bad.
|
I would like to figure out the memory address of the following:
```
>>> ($rbp + $rdi*2 - 8)
```
And then once I have that value, inspect that memory address with:
```
>>> x/wx $address
```
How would I do this in gdb?
|
You can type this in directly after thep(rint) command. For example:
```
>>> p/x ($rbp + $rdi*2 -8)
$2 = 0x7fffffffe43e
>>> x/hx $
0x7fffffffe43e: 0x001b # 27
```
The$symbol stores the last value.
|
I'm new to C, just a question on the header file, below is the code that uses the header file as recommended:
```
//test.h
extern int globalVariable;
```
```
//test.c
#include "test.h"
int globalVariable = 2020;
```
```
//main.c
#include <stdio.h>
#include "test.h"
int main()
{
printf("Value is %d", globalVariable);
}
```
I don't understand that why we need to put#include "test.h"intest.cfile, what's the benefit of doing it?
|
It actually doesn't, but it's a good practice.
If you wrote:
```
double globalVariable = 2020;
```
you would have undefined behavior. Now if you wrote
```
#include "test.h"
double globalVariable = 2020;
```
the compiler will catch your mistake. Since the same definition is available to all modules that useglobalVariableby including the same header file, such a mistake is much less likely.
|
QUESTION->
```
#include<stdio.h>
int main()
{
int a,*b,**c,***d;
int x;
a=&x;
b=&a;
c=&b;
d=&c;
printf("%d\t%d\t%d\t%d",a,b,c,d);
a++;
b++;
c++;
d++;
printf("\n%d\t%d\t%d\t%d",a,b,c,d);
return 0;
}
```
OUTPUT
```
-760636132 -760636128 -760636120 -760636112
-760636128 -760636120 -760636112 -760636104
```
Why after 2nd pointer all the pointers increment by a value of 8?
|
If you checked you would findsizeof(int) == 4andsizeof(int*) == 8. When you print the pointer you see the actual value. Incrementing the pointer adds the size of what the pointer points to.
You are very close to undefined behavior. If you tried to read what these pointers pointed to (or worse, write to them), the results could be very bad.
|
In this function:
```
void final_delete(node **head) {
node *tmp;
tmp = *head;
while (tmp != NULL) {
tmp = tmp->next;
free(*head);
*head = tmp;
}
*head = tmp; //<-------- HERE
}
```
Is the reported part necessary?*head = tmpisn't it already the last step of thewhileloop?
|
Since you expect to delete the whole list, then *head should be a null pointer after the execution of thefinal_delete()function. Then you could just omit the*head = tmp;line and just add a line after the while loop with*head = NULL;. To answer your question, the last line is redundant.
|
This question already has answers here:In a C function declaration, what does "..." as the last parameter do?(7 answers)Closed3 years ago.
Looking through MSVC's standard libraries, I see the function definition of printf() is:
printf(char const* const _Format, ...)What does the 3 periods mean?
|
That defines the function as aVariadic Function(variable arguments) meaning it is a function which can take any number of arguments. This is useful for functions likeprintfsince there is no way to determine how many arguments might be passed in
```
printf("%d %d", 5, 5); // two args
printf("%d %d %d", 5, 5, 5); // three args
```
This is just a feature of the language that allows you to pass any number of arguments to a function. Without this feature, the user would need to gather each desired parameter into an array beforehand, and pass them as a single parameter.
|
I want to usefgetsandscanfmixing them, but there are leftovers of'\n'characters and they mess up thefgetsoutput, I've tried using:
```
fseek(stdin, 0, SEEK_END);
```
And it worked, is this a bad practice?
|
The behaviour offseekwithSEEK_ENDisn't defined by the C standard.
7.21.9.2/4 The fseek function:
For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET.
Even otherwise, It's unreliable to use fseek onstdin. POSIX saysstreamswith no backing files (pipes, sockets, etc) are not seekable.
But you're attempting a "wrong" solution in my view: don't mixfgetsandscanfto start with.
scanfis fragile for user inputs and propererror handling ofscanfis hard. You might instead use justfgetsto read lines and usesscanfto extract inputs.
|
When I declare:
```
struct str_node{
int data;
struct str_node *next;
}node;
node *head = NULL;
```
Is it something like:
```
head = NULL;
```
or
```
*head = NULL
```
|
Every declaration is in the following format:
```
Type varName = initializer;
```
In your case
```
node * head = NULL;
^ ^ ^
| Type | | varName | = | initializer |;
```
So,headis a variable which type isnode *(pointer tonode). The variable isheadwhich value is initialized toNULL.
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed3 years ago.Improve this question
code
```
main( )
{
int i ;
for ( i = 1 ; i <= 5 ; printf ( "\n%d", i ) ) ;
i++ ;
}
```
output
1infinite times.
|
You have a trailing;at the end of the loop that effectively makes your code:
```
for ( i = 1 ; i <= 5 ; printf ( "\n%d", i ) )
{
}
i++;
```
|
This question already has answers here:Why does #define not require a semicolon?(7 answers)Closed3 years ago.
I'm writing a Producer-Consumer solution but I keep getting "error: expected ']' before ';' token" when declaring "buffer_item buffer[BUFFER_SIZE];". I'm not quite sure what to do?
This is my buffer.h file:
```
typedef int buffer_item;
#define BUFFER_SIZE 5;
```
buffer.c file
```
#include <stddef.h>
#include <stdlib.h>
#include <unistd.h>
#include "buffer.h"
buffer_item buffer[BUFFER_SIZE];
void *producer(void *param);
void *consumer(void *param);
//etc..
```
|
Macros are string replacing, so
```
#define BUFFER_SIZE 5;
buffer_item buffer[BUFFER_SIZE];
```
will become
```
buffer_item buffer[5;];
```
and you have extra semicolon after the number of elements.
You should use
```
#define BUFFER_SIZE 5
```
(without semicolon) instead.
|
This question already has answers here:In a C function declaration, what does "..." as the last parameter do?(7 answers)Closed3 years ago.
Looking through MSVC's standard libraries, I see the function definition of printf() is:
printf(char const* const _Format, ...)What does the 3 periods mean?
|
That defines the function as aVariadic Function(variable arguments) meaning it is a function which can take any number of arguments. This is useful for functions likeprintfsince there is no way to determine how many arguments might be passed in
```
printf("%d %d", 5, 5); // two args
printf("%d %d %d", 5, 5, 5); // three args
```
This is just a feature of the language that allows you to pass any number of arguments to a function. Without this feature, the user would need to gather each desired parameter into an array beforehand, and pass them as a single parameter.
|
I want to usefgetsandscanfmixing them, but there are leftovers of'\n'characters and they mess up thefgetsoutput, I've tried using:
```
fseek(stdin, 0, SEEK_END);
```
And it worked, is this a bad practice?
|
The behaviour offseekwithSEEK_ENDisn't defined by the C standard.
7.21.9.2/4 The fseek function:
For a text stream, either offset shall be zero, or offset shall be a value returned by an earlier successful call to the ftell function on a stream associated with the same file and whence shall be SEEK_SET.
Even otherwise, It's unreliable to use fseek onstdin. POSIX saysstreamswith no backing files (pipes, sockets, etc) are not seekable.
But you're attempting a "wrong" solution in my view: don't mixfgetsandscanfto start with.
scanfis fragile for user inputs and propererror handling ofscanfis hard. You might instead use justfgetsto read lines and usesscanfto extract inputs.
|
When I declare:
```
struct str_node{
int data;
struct str_node *next;
}node;
node *head = NULL;
```
Is it something like:
```
head = NULL;
```
or
```
*head = NULL
```
|
Every declaration is in the following format:
```
Type varName = initializer;
```
In your case
```
node * head = NULL;
^ ^ ^
| Type | | varName | = | initializer |;
```
So,headis a variable which type isnode *(pointer tonode). The variable isheadwhich value is initialized toNULL.
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed3 years ago.Improve this question
code
```
main( )
{
int i ;
for ( i = 1 ; i <= 5 ; printf ( "\n%d", i ) ) ;
i++ ;
}
```
output
1infinite times.
|
You have a trailing;at the end of the loop that effectively makes your code:
```
for ( i = 1 ; i <= 5 ; printf ( "\n%d", i ) )
{
}
i++;
```
|
This question already has answers here:Why does #define not require a semicolon?(7 answers)Closed3 years ago.
I'm writing a Producer-Consumer solution but I keep getting "error: expected ']' before ';' token" when declaring "buffer_item buffer[BUFFER_SIZE];". I'm not quite sure what to do?
This is my buffer.h file:
```
typedef int buffer_item;
#define BUFFER_SIZE 5;
```
buffer.c file
```
#include <stddef.h>
#include <stdlib.h>
#include <unistd.h>
#include "buffer.h"
buffer_item buffer[BUFFER_SIZE];
void *producer(void *param);
void *consumer(void *param);
//etc..
```
|
Macros are string replacing, so
```
#define BUFFER_SIZE 5;
buffer_item buffer[BUFFER_SIZE];
```
will become
```
buffer_item buffer[5;];
```
and you have extra semicolon after the number of elements.
You should use
```
#define BUFFER_SIZE 5
```
(without semicolon) instead.
|
Can someone explain to me why when I dynamic allocate memory withcallocormallocI declare:
```
int *arr
int n
arr = malloc(n * sizeof(int))
```
and not
```
*arr = malloc(n * sizeof(int))
```
|
Because in the first example you are makingarrthe pointer to the memory. In the second example you are making whatarris pointing to the pointer to the memory allocated.
In other words, you declared arr as a pointer. Malloc returns a pointer to allocated memory. So you "fill" arr with that value. In your second example, you are filling *arr--what arr is pointing to--with the value returned by malloc.
|
Suppose the server handles clients in the following manner:
```
void* handle_request(void* client_sck);
int client_sck;
while((client_sck = accept(...)) != -1)
{
/*
.
.
.
*/
pthread_create(&thr, 0, handle_request, (void*)&client_sck);
}
```
Is it safe to say that, on each loop iteration, the last argument passed topthread_createwill be shared among threads? Meaning the second time a around, the client_sck still has the same address from the previous iteration.
|
Yes. This means that thenextaccept()can overwrite the value before thepreviousthread had a chance to fetch the value, so it's not a good design.
|
Does C have a#include<bitset>similar to C++ ? I have been looking for the past week. I can't find a equivalent directive preprocessor!
|
No, it does not. There are, however, ways to implement what you are looking for (or at least some sort of approximation). Take look at:http://c-faq.com/misc/bitsets.html- I think it is going to be useful.
|
We have a C codebase which used to build successfully with SunStudio 12.1 and Solaris 11.3 but recently we have upgraded our OS to Solaris 11.4 and build starts to break with either of below errors.
"<FILE_NAME>", line <LINE_NUMBER>: internal compiler error: cg_inbuf_emit(): messed up relocation
cc: acomp failed for <FILE_NAME>
*** Error code 2
Or
"<FILE_NAME>", line <LINE_NUMBER>: internal compiler error: cg_inbuf_emit(): missed relocation
cc: acomp failed for <FILE_NAME>
*** Error code 2
On inspection I observed that these lines are nothing but ending of either Macro definitons or symbols both which are referenced from other user defined libraries.
|
Those indicate problems in the compiler that you will need to open a support request with Oracle to have them resolve.
|
I would like to know, how to access first member of struct through pointer. I have tried this:
```
#include <stdio.h>
#include <stdlib.h>
struct foo
{
int a;
char *str;
};
int main()
{
struct foo *p = malloc(sizeof(struct foo));
int val = 10;
*(int**)p = &val; //set the value of the first member of struct foo
printf("%i\n",p->a);
}
```
but that print some garbage. How can I set it in similar manner?
|
What you're doing there is setting the value ofp->ato the address ofval(possibly truncated to 32 bits, depending on the implementation).
To access the field via a pointer, you have to take the field's address and then assign to the dereferenced pointer.
```
int *pa = &p->a;
*pa = val;
```
Of course you can also just writep->a = val. Note thatp->ais just an abbreviation for(*p).a.
|
I am working on a C program with some AT terminal and my code was needed to define many string variable like:
```
const char *AT_norn = "AT";
const char *AT = "AT\r\n";
const char *ATI = "ATI\r\n";
```
Like I have 30 or more AT command like above to Serialprint out.
So I have question,
I try to make a new string that like
```
const char *myeol = "\r\n";
```
IN Order to issue "AT\r\n"
I tried to write something like this, but no success:
```
UART_write(handle, AT_norn, sizeof(AT_norn));
UART_write(handle, myeol, sizeof(myeol));
```
How can I use above method to save some RAM size?
|
DefiningAT_nornas
```
const char *AT_norn = "AT";
```
sizeof AT_Nornreturns the size of a pointer, you want
```
const char AT_norn[] = "AT";
```
in order to get the size of the array.
|
I want to substitute a function that usesfwrite. It works like this:
```
static size_t write_data(void *ptr, size_t size, size_t nmemb, void *userdata)
{
//...
//I want to change the call below to instead write to my own function
size_t written = fwrite(ptr, size, nmemb, (FILE *)stream);
return size;
}
```
As you read in the commend, I want to changefwriteto instead write to my own functionmyFunctionWrite(uint8_t* data, size_t size)but as you see, my function only acceptsuint8_t*. Writing a conversion function for all types ofnmembwill be troublesome. Is there some function that does everything for me? Or is it easy to convert touint8_t*always?
|
Multiplysizeandnmemb.
```
static size_t write_data(void *ptr, size_t size, size_t nmemb, void *userdata)
{
//...
size_t written = myFunctionWrite(ptr, size * nmemb);
return size;
}
```
|
I want to scan a value, and print the value that was scanned
```
int main()
{
int n;
printf("enter value: ");
n = scanf("%d",&n);
printf("%d",n);
return 0;
}
```
however, the printed result gave me 1 instead of 9 as shown below. Why is this so and how do i solve this?
|
Becausenget override by the return value of scanf
Just usescanf("%d", &n);if you don't want the number of parsed items assigned ton.
|
I have:
```
char* mem = (char*) 0xB8000;
```
Thenmemis passed to a function. Inside the function, I want to get the number0xB8000back and compare it to some other integers. How do I convertmemback to the original integer?
|
To convert any pointer to an integer, do the following:
```
#include <stdint.h>
uintptr_t ptr_to_integer(const void *ptr) {
return (uintptr_t) ptr;
}
```
Note that the size ofuintptr_tmight vary between platforms. Also this is an optional part of the C standard, so technically onlyuintmax_twould be absolutely portable.
|
There are "sayings" on the web that LLVM (Clang) is built with GCC compatibility in mind and that it uses many of GCC's tools to compile code. However that does not make sense; isn't Clang a more advanced replacement for GCC? So straight to the point, does Clang use GCC at all? Are they related?
|
Depending on how it is configured, clang can use gcc components, e.g: to retain compatibility. Clang, just like gcc, is a compiler, and a compiler frontend. Strictly speaking, a C++ compiler does not link code, the linker does it. Clang can use either gnu ld, gold, lld or others. Those are all linkers, some part of the gcc toolchain. A compiler also needs a standard library, clang can use libstdc++, libc++ or others. libstdc++ is part of the gcc toolchain, and a popular option to remain compatible with other system wide components.
|
I know GCC and probably Clang accept this syntax, but if I'm making games for the common 5 platforms (Mac, Windows, Linux, iOS, Android(Java)) but if I get C to run on Android probably by bridging Java and C, how portable is this? Should this be avoided?
I know that this is a bad funciton because simplyreturn num*num;is enough but this syntax, should I avoid it?
```
int square(int num) {
int x = ({
int y = num;
y*y;
});
return x;
}
```
|
This is not standard C. It's a GNU C extension calledStatement Expressions. You should avoid it if you want maximum portability.
|
I want to scan a value, and print the value that was scanned
```
int main()
{
int n;
printf("enter value: ");
n = scanf("%d",&n);
printf("%d",n);
return 0;
}
```
however, the printed result gave me 1 instead of 9 as shown below. Why is this so and how do i solve this?
|
Becausenget override by the return value of scanf
Just usescanf("%d", &n);if you don't want the number of parsed items assigned ton.
|
I have:
```
char* mem = (char*) 0xB8000;
```
Thenmemis passed to a function. Inside the function, I want to get the number0xB8000back and compare it to some other integers. How do I convertmemback to the original integer?
|
To convert any pointer to an integer, do the following:
```
#include <stdint.h>
uintptr_t ptr_to_integer(const void *ptr) {
return (uintptr_t) ptr;
}
```
Note that the size ofuintptr_tmight vary between platforms. Also this is an optional part of the C standard, so technically onlyuintmax_twould be absolutely portable.
|
There are "sayings" on the web that LLVM (Clang) is built with GCC compatibility in mind and that it uses many of GCC's tools to compile code. However that does not make sense; isn't Clang a more advanced replacement for GCC? So straight to the point, does Clang use GCC at all? Are they related?
|
Depending on how it is configured, clang can use gcc components, e.g: to retain compatibility. Clang, just like gcc, is a compiler, and a compiler frontend. Strictly speaking, a C++ compiler does not link code, the linker does it. Clang can use either gnu ld, gold, lld or others. Those are all linkers, some part of the gcc toolchain. A compiler also needs a standard library, clang can use libstdc++, libc++ or others. libstdc++ is part of the gcc toolchain, and a popular option to remain compatible with other system wide components.
|
I know GCC and probably Clang accept this syntax, but if I'm making games for the common 5 platforms (Mac, Windows, Linux, iOS, Android(Java)) but if I get C to run on Android probably by bridging Java and C, how portable is this? Should this be avoided?
I know that this is a bad funciton because simplyreturn num*num;is enough but this syntax, should I avoid it?
```
int square(int num) {
int x = ({
int y = num;
y*y;
});
return x;
}
```
|
This is not standard C. It's a GNU C extension calledStatement Expressions. You should avoid it if you want maximum portability.
|
I am new to C and when I do this which makes the elements in the list arranged:
```
#include <stdlib.h>
#include <stdio.h>
int main()
{
int list[] = {6, 4, 8, 1, 0, 9, 11, 50, 60, 10};
int i, j, aux, k;
int len = sizeof(list) / sizeof(list[0]);
for (i = 0; i < len; i++)
{
for (j = 0; j < len; j++)
{
if (list[j] > list[j + 1])
{
aux = list[j + 1];
list[j + 1] = list[j];
list[j] = aux;
}
}
}
for (k = 0; k < len; k++)
{
printf("%d ", list[k]);
}
return 0;
}
```
Output :
```
-13168 0 1 4 6 8 9 10 11 50
```
Why is the first value-13168?
|
Both youriand yourjwalk all the range of legal indices in the array.But you do accesslist[j+1]which is one beyond the array, read there and sort the value you get from there.
|
I currently have a problem to read this code.
Does anyone know what it does ?
```
if (c == a)
return q[a] ? 1 : 0;
```
|
The code inside if gets evaluated in order matching operator precedence.
So firsta + 1is evaluated and thenb == (a + 1).
Ifbis equal to(a + 1)then ifq[a]istrue1, is returned, otherwise0.
SeeC# operators and expressionsorPrecedence and order of evaluation(depending on the language, you want to google "language name" + operator precedence).
|
I'm using the paho.mqtt.c library to connect to an Azure IoT Hub. I want to test how my software handles disconnections from the IoT Hub.
How can I simulate the IoT Hub disconnecting the client?
There is no "Stop IoT Hub" button in the Azure Portal -> IoT Hub.
|
The following are some cases for disconnecting a mqtt device from Azure IoT Hub:
connecting a mqtt device with the same deviceIdpublishing on the wrong topic, for instance:abcdDisable a device connection to IoT Hub on the portalusing the REST API for disable a device, see my answerhere
|
In this code whenever I write a new sentence, it replaces the previous sentence in a file that I put earlier. I want to not replace the previous sentence and also allow other sentences in that file line after line.
```
#include <stdio.h>
#include <stdlib.h>
int main() {
char sentence[1000];
// creating file pointer to work with files
FILE *fptr;
// opening file in writing mode
fptr = fopen("file.txt", "w");
// exiting program
if (fptr == NULL) {
printf("Error!");
exit(1);
}
printf("Enter a sentence:\n");
fgets(sentence, sizeof(sentence), stdin);
fprintf(fptr, "%s", sentence);
fclose(fptr);
return 0;
}
```
|
Open the file in append mode.
```
fptr = fopen("file.txt", "a");
```
https://en.cppreference.com/w/c/io/fopen
|
I'm trying to manipulating binary numbers with c. I found a strange thing with the minimum code below. Can anyone tell me what is the difference between "+" and "|" here? Thank you!
```
char next_byte1 = 0b11111111;
char next_byte2 = 0b11110101;
short a = (next_byte1 << 8) | next_byte2;
short b = (next_byte1 << 8) + next_byte2;
printf("a vs b is %d ~ %d.\n", a, b);
```
It showed: a vs b is -11 ~ -267, which is 0b11111111 11110101 and 0b11111110 11110101. I'm very confused with this result.
|
The problem you are seeing is becausenext_byte2is sign-extended to a fullintbefore doing the bitwise operation and thus is "corrupting" the high byte.
When doing bit manipulation it's better to useunsignedtypes (that is actually what unsigned are to be used for). Plainchartypes can be (and normally are) signed types and thus are better avoided for these uses.
|
As static arrays are created during compile-time, may I set the length of the array with a variable obtained through e.g. another function? I believe this is dependent on whether the compiler can be smart enough to know what value this variable will have?
Example code where I obtain the size troughsnprinf(). This code is compiling without errors or warnings usinggccwith the-Wallflag.
```
#include <stdio.h>
int main(void)
{
int mac[6] = {0xAA,0xBB,0xCC,0xDD,0xEE,0xFF};
int size = snprintf(NULL, 0, "%02X", mac[0]);
char str[size + 1];
snprintf(str, size + 1, "%02X", mac[0]);
printf("%s\n", str);
return 0;
}
```
Compiling and running results in:
```
AA
```
Why is this possible?
|
stris not a static array it is what C calls a VLA, variable length array.
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed3 years ago.Improve this question
```
int main()
{
int i= 0;
printf("i value is %d\n",i);
scanf("%c", &i); // I am giving an input of 255 here
printf("i after scan %d\n",i); // This prints 50. How???
return 0;
}
```
Can someone explain how does the printf statement give 50? I have a little-endian machine.
|
Your program won't even compile asIis undeclared. I am assuming that it is a typo. Since you are scanning%cit will read only one character which is 2 from 255. Now 2 has ascii code of 50 which is being printed.
|
I'm new to C and ASCII numbers, so I was using a code sample to print ASCII numbers
```
int main(){
int c;
while ((c = getchar()) != EOF){
printf("%d\n", c);
}
}
```
Output for "d" was
```
100
10
```
Whatever letter I tend to type, the result will be the ASCII code of said letter and 10 at the end as well. I'm not sure where this 10 is coming from.
|
That's the code for the newline character that ended the input line.
if you want to stop at the end of the line and not include it, add another check.
```
while ((c = getchar()) != EOF && c != '\n'){
printf("%d\n", c);
}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.