question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I write test script in C, compiled it and put to /usr/bin directory, to execute it from anywhere likemkdirorls. But then I wrote$ testnothing happen, if i wrote$ /usr/bin/testit works well. What I did wrong? I got Ubuntu 14.
|
In shells (such as bash), there's ashell builtinnamedtest. So, when you executetest, shell builtintestis executed even though you havetestin/usr/bin/assuming you have/usr/bin/in yourPATH. When you give full path, there's no ambiguity there (like other binaries namedtestwhich might be there in PATH or builtins).
You can test this by running:
```
$type test
```
Name your binary to something else that doesn't interfere with system binaries or shell builtins. It's generally recommended to put your binaries in designated locations such asusr/local/bin/even if your binary is uniquely named.
|
im trying to scan (perhaps using fgets) 6 different strings from the same line in a file that is accessed by the program. i used the following struct to hold the 6 different strings:
```
struct _entry {
char subject[10];
char prof_name[10];
char prof_surname[10];
int period;
int credits;
int pass_rate;
};
struct _entry entry[MAX_LINES];
```
if someone could help me on what i can do to scan 1 line from a file, and it will be 3 strings and 3 digits that i can assign to each of the struct values.
|
Read file line by line using -
```
fgets() or getline
```
( getline() is not portable. Its only for linux based application )
Parse line using -
```
strtok or strtok_r or sscanf
```
Convert parsed string into Integer using-
```
atoi
```
|
If you scroll to the end, there should be comments like these. What do they do, what do they mean?
```
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* indent-tabs-mode: t
* End:
*/
```
I found a reference to GNU Emacs, but I am not familiar with it and a quick read didn't help much either. Is it a script that later generates emacs customizations from them?
https://github.com/php/php-src/blob/master/ext/reflection/php_reflection.h
|
These are EmacsFile Variables. They tell the Emacs text editor to set various per-buffer options. In your example, it instructs it on the preferred indentation style when editing that program, so that it will indent each block by 4 columns.
SeeSpecifying File Variablesin the Emacs manual for more details.
|
I'm writing a vim auto-command for cpp files where I want an abbreviation for#includelines.
The goal is for the abbreviation to expand to#include <▐>with the pipe being the location of the cursor after expansion.
Since naturally the abbreviation is to be followed by a space I'm trying to remove the input space from the register and move on.
However even after exiting insert mode and returning, or any trick I could think of: deleting next key, keying in bs etc, the space is being entered after whatever series of commands the iabbrev includes.
Therefore I'm looking for something that will remove the space from the register AND put me still in insert mode.
Thanks.
|
Add this to your.vimrc:
```
autocmd FileType cpp iab <buffer> #i #include <><Left><C-R>=Eatchar('\s')<CR>
func Eatchar(pat)
let c = nr2char(getchar(0))
return (c =~ a:pat) ? '' : c
endfunc
```
|
I have a question that should be fairly straightforward (I hope).
In c, the size of an array delcared asint array[10][10];,
for example, I understand as having 10 spots in which to store 10 integers. However, what's the size of an array declared asint *array[10];? I know that*arrayhas 10 elements, but how many elements doesarrayhave?
This is a hole in my understanding I would really like to clear up. Thanks for any help!
|
int *array[10];is an array of 10int *s, so the number of elements is 10.
To elaborate, forint *array[10];, ty type ofarrayvariable isint * [10], an array of 10 elements of type pointer to integers.
The array size would be10 * sizeof pointer-to-integer-in-your-platform.
|
I am using Eclipse CDT and MinGW to do C development on Windows 8.1.
I have unpacked company internal MinGW package and just copied it toc:\MinGW, so it was not installer. I also addedc:\MinGW\binto path.
When I run Eclipse CDT, it does detect MinGW toolchain. However, after I set up a C project and tell it to use MinGW toolchain, and build it, I see in the console output the C compiler used isgcc, and I would like to usemingw32-g++.exe.
How do I define this in Eclipse CDT?
I checked projectProperties\C C++ Build\Tool Chain Editor\and underused toolsI see the following:
GCC AssemblerGCC ArchiverGCC C++ CompilerGCC C CompilerMinGW C LinkerMinGW C++ Linker
|
The compiler is defined under project properties\C C++ Build\Settings\Tool Settings. Here one should selectGCC Compilerand specifymingw32-g++or justg++, or whichever compiler is desired.
|
I want to convert ADC Values to float numbers.
This is my code:
```
uint32_t ADCValue;
char str[15];
ADCValue = HAL_ADC_GetValue(&hadc1);
ADCValue=ADCValue*3.3/4095;
sprintf(str, "%d", Voltage);
HAL_UART_Transmit(&huart2, (uint8_t*)(&str), 6, 100);
HAL_UART_Transmit(&huart2, (uint8_t*) "\n\r", 2, 100);
HAL_Delay(500);
```
I am reading value of 4095 at 3.3V but I am transmitting 3 to buffer. I want to transmit exact value of voltage.
|
There is no apparent reason why you need to use float numbers here in the first place. They are needlessly slow. Simply do this:
```
uint32_t millivolts = ADCValue*3300/4095.
```
For an input of 4095, you get the result 3299mV. This is possibly more accurate than what you would get through float numbers, because of floating-point inaccuracy.
|
im trying to scan (perhaps using fgets) 6 different strings from the same line in a file that is accessed by the program. i used the following struct to hold the 6 different strings:
```
struct _entry {
char subject[10];
char prof_name[10];
char prof_surname[10];
int period;
int credits;
int pass_rate;
};
struct _entry entry[MAX_LINES];
```
if someone could help me on what i can do to scan 1 line from a file, and it will be 3 strings and 3 digits that i can assign to each of the struct values.
|
Read file line by line using -
```
fgets() or getline
```
( getline() is not portable. Its only for linux based application )
Parse line using -
```
strtok or strtok_r or sscanf
```
Convert parsed string into Integer using-
```
atoi
```
|
If you scroll to the end, there should be comments like these. What do they do, what do they mean?
```
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* indent-tabs-mode: t
* End:
*/
```
I found a reference to GNU Emacs, but I am not familiar with it and a quick read didn't help much either. Is it a script that later generates emacs customizations from them?
https://github.com/php/php-src/blob/master/ext/reflection/php_reflection.h
|
These are EmacsFile Variables. They tell the Emacs text editor to set various per-buffer options. In your example, it instructs it on the preferred indentation style when editing that program, so that it will indent each block by 4 columns.
SeeSpecifying File Variablesin the Emacs manual for more details.
|
I'm writing a vim auto-command for cpp files where I want an abbreviation for#includelines.
The goal is for the abbreviation to expand to#include <▐>with the pipe being the location of the cursor after expansion.
Since naturally the abbreviation is to be followed by a space I'm trying to remove the input space from the register and move on.
However even after exiting insert mode and returning, or any trick I could think of: deleting next key, keying in bs etc, the space is being entered after whatever series of commands the iabbrev includes.
Therefore I'm looking for something that will remove the space from the register AND put me still in insert mode.
Thanks.
|
Add this to your.vimrc:
```
autocmd FileType cpp iab <buffer> #i #include <><Left><C-R>=Eatchar('\s')<CR>
func Eatchar(pat)
let c = nr2char(getchar(0))
return (c =~ a:pat) ? '' : c
endfunc
```
|
I have a question that should be fairly straightforward (I hope).
In c, the size of an array delcared asint array[10][10];,
for example, I understand as having 10 spots in which to store 10 integers. However, what's the size of an array declared asint *array[10];? I know that*arrayhas 10 elements, but how many elements doesarrayhave?
This is a hole in my understanding I would really like to clear up. Thanks for any help!
|
int *array[10];is an array of 10int *s, so the number of elements is 10.
To elaborate, forint *array[10];, ty type ofarrayvariable isint * [10], an array of 10 elements of type pointer to integers.
The array size would be10 * sizeof pointer-to-integer-in-your-platform.
|
I am using Eclipse CDT and MinGW to do C development on Windows 8.1.
I have unpacked company internal MinGW package and just copied it toc:\MinGW, so it was not installer. I also addedc:\MinGW\binto path.
When I run Eclipse CDT, it does detect MinGW toolchain. However, after I set up a C project and tell it to use MinGW toolchain, and build it, I see in the console output the C compiler used isgcc, and I would like to usemingw32-g++.exe.
How do I define this in Eclipse CDT?
I checked projectProperties\C C++ Build\Tool Chain Editor\and underused toolsI see the following:
GCC AssemblerGCC ArchiverGCC C++ CompilerGCC C CompilerMinGW C LinkerMinGW C++ Linker
|
The compiler is defined under project properties\C C++ Build\Settings\Tool Settings. Here one should selectGCC Compilerand specifymingw32-g++or justg++, or whichever compiler is desired.
|
I want to convert ADC Values to float numbers.
This is my code:
```
uint32_t ADCValue;
char str[15];
ADCValue = HAL_ADC_GetValue(&hadc1);
ADCValue=ADCValue*3.3/4095;
sprintf(str, "%d", Voltage);
HAL_UART_Transmit(&huart2, (uint8_t*)(&str), 6, 100);
HAL_UART_Transmit(&huart2, (uint8_t*) "\n\r", 2, 100);
HAL_Delay(500);
```
I am reading value of 4095 at 3.3V but I am transmitting 3 to buffer. I want to transmit exact value of voltage.
|
There is no apparent reason why you need to use float numbers here in the first place. They are needlessly slow. Simply do this:
```
uint32_t millivolts = ADCValue*3300/4095.
```
For an input of 4095, you get the result 3299mV. This is possibly more accurate than what you would get through float numbers, because of floating-point inaccuracy.
|
I have a question that should be fairly straightforward (I hope).
In c, the size of an array delcared asint array[10][10];,
for example, I understand as having 10 spots in which to store 10 integers. However, what's the size of an array declared asint *array[10];? I know that*arrayhas 10 elements, but how many elements doesarrayhave?
This is a hole in my understanding I would really like to clear up. Thanks for any help!
|
int *array[10];is an array of 10int *s, so the number of elements is 10.
To elaborate, forint *array[10];, ty type ofarrayvariable isint * [10], an array of 10 elements of type pointer to integers.
The array size would be10 * sizeof pointer-to-integer-in-your-platform.
|
I am using Eclipse CDT and MinGW to do C development on Windows 8.1.
I have unpacked company internal MinGW package and just copied it toc:\MinGW, so it was not installer. I also addedc:\MinGW\binto path.
When I run Eclipse CDT, it does detect MinGW toolchain. However, after I set up a C project and tell it to use MinGW toolchain, and build it, I see in the console output the C compiler used isgcc, and I would like to usemingw32-g++.exe.
How do I define this in Eclipse CDT?
I checked projectProperties\C C++ Build\Tool Chain Editor\and underused toolsI see the following:
GCC AssemblerGCC ArchiverGCC C++ CompilerGCC C CompilerMinGW C LinkerMinGW C++ Linker
|
The compiler is defined under project properties\C C++ Build\Settings\Tool Settings. Here one should selectGCC Compilerand specifymingw32-g++or justg++, or whichever compiler is desired.
|
I want to convert ADC Values to float numbers.
This is my code:
```
uint32_t ADCValue;
char str[15];
ADCValue = HAL_ADC_GetValue(&hadc1);
ADCValue=ADCValue*3.3/4095;
sprintf(str, "%d", Voltage);
HAL_UART_Transmit(&huart2, (uint8_t*)(&str), 6, 100);
HAL_UART_Transmit(&huart2, (uint8_t*) "\n\r", 2, 100);
HAL_Delay(500);
```
I am reading value of 4095 at 3.3V but I am transmitting 3 to buffer. I want to transmit exact value of voltage.
|
There is no apparent reason why you need to use float numbers here in the first place. They are needlessly slow. Simply do this:
```
uint32_t millivolts = ADCValue*3300/4095.
```
For an input of 4095, you get the result 3299mV. This is possibly more accurate than what you would get through float numbers, because of floating-point inaccuracy.
|
I am writing a program where I have an infinite loop doing something with a stopping condition to break if some variablea == 1using only bitwise operators.
How would I do this?
Example code:
```
while(1){
int a;
//do some work
if (a==1){ // how do I say this with bitwise operators and no "!"
break;
}
}
```
|
Since OP's stopping condition is at the end of the loop, code can use ado()loop.
```
int a;
do {
// some work that sets `a`
} while (a^1);
```
Whenahas the value of 1,a ^ 1-->0.
|
This line get me asegmentation fault:
```
g_object_set(G_OBJECT(data.udpsrc), "port", 5000, "caps", caps, NULL);
```
where
data.udpsrc = gst_element_factory_make("udpsrc", "source");caps = gst_caps_new_empty_simple("application/x-rtp");
Here's the output with gdb :
```
Program received signal SIGSEGV, Segmentation fault.
strchr () at ../ports/sysdeps/arm/armv6/strchr.S:28
28 ../ports/sysdeps/arm/armv6/strchr.S: No such file or directory.
(gdb) bt
#0 strchr () at ../ports/sysdeps/arm/armv6/strchr.S:28
#1 0x76e618d8 in g_param_spec_pool_lookup () from /usr/lib/arm-linux-gnueabihf/libgobject-2.0.so.0
#2 0x76e5c6a4 in g_object_set_valist () from /usr/lib/arm-linux-gnueabihf/libgobject-2.0.so.0
#3 0x76e5d00c in g_object_set () from /usr/lib/arm-linux-gnueabihf/libgobject-2.0.so.0
#4 0x00010dc4 in main ()
```
|
This isBug 740191. You need to update Gstreamer to 1.4.5 version at least.
|
I read the following code fragment:
```
va_list args;
memset(&args, 0, sizeof(va_list));
va_start(args, xxx);
...
va_end(args);
```
What is the implication ofmemset()here directly beforeva_start()?
What is the difference if thememset()line is removed?
|
The implication is that the programmer who wrote this does not know what they are doing, and enjoys wasting code.
They may be blindly following the directive of some static analysis tool that variables must be initialized before they are used.
va_start(args, xxx);does all the necessary initialization, and overwrites all the 0-values thatmemsetjust put in, making the work ofmemsetworthless.
|
I need an entire string to be one char of another string.
```
const char *const_string = "FOOBAR";
char *character_string = malloc(1024);
// character_string = const_string[3];
```
How can I make the last (commented) line work?
|
It seems you mean the following
```
void do_something(char *str, int idx)
{
str[0] = glob_str[idx];
str[1] = '\0';
}
```
You can add a check to the function that the index is not outside the string literal pointed to byglob_str.
|
The title says it all. Callingmysql_get_server_inforeturns(null)but everything works fine.
mysql_get_client_info()returns the correct value:6.1.6
What can be the reason I don't receive the correct server information5.7.17-log?
|
mysql_get_server_infoassumes that there is an existing connection to a MySQL server created earlier in the running process. You'd need to callmysql_connectfirst, if you want it to return anything.
This is much easier to visualize (and more future proof) withmysqli_get_server_info, which takes an initializedMySQLiobject as a parameter.
|
I read the following code fragment:
```
va_list args;
memset(&args, 0, sizeof(va_list));
va_start(args, xxx);
...
va_end(args);
```
What is the implication ofmemset()here directly beforeva_start()?
What is the difference if thememset()line is removed?
|
The implication is that the programmer who wrote this does not know what they are doing, and enjoys wasting code.
They may be blindly following the directive of some static analysis tool that variables must be initialized before they are used.
va_start(args, xxx);does all the necessary initialization, and overwrites all the 0-values thatmemsetjust put in, making the work ofmemsetworthless.
|
I need an entire string to be one char of another string.
```
const char *const_string = "FOOBAR";
char *character_string = malloc(1024);
// character_string = const_string[3];
```
How can I make the last (commented) line work?
|
It seems you mean the following
```
void do_something(char *str, int idx)
{
str[0] = glob_str[idx];
str[1] = '\0';
}
```
You can add a check to the function that the index is not outside the string literal pointed to byglob_str.
|
The title says it all. Callingmysql_get_server_inforeturns(null)but everything works fine.
mysql_get_client_info()returns the correct value:6.1.6
What can be the reason I don't receive the correct server information5.7.17-log?
|
mysql_get_server_infoassumes that there is an existing connection to a MySQL server created earlier in the running process. You'd need to callmysql_connectfirst, if you want it to return anything.
This is much easier to visualize (and more future proof) withmysqli_get_server_info, which takes an initializedMySQLiobject as a parameter.
|
I created this array:
```
char** command=malloc(sizeof(*command)*MAX_COMMANDS+1);
```
and after that every command[i] gets this:
```
command[i]=malloc(sizeof(*command[i])*strlen(token)+1);
```
How do I free the command 2d array?
|
There is a rule of a thumb - each call to malloc corresponds to one call to free and typically you free the memory in reverse order of its allocation. In this case you should iterate overcommandcallingfreefor eachcommand[i]and only after that can youfreecommand.
|
This question already has answers here:Undefined reference to `sin` [duplicate](4 answers)Closed6 years ago.
I'm trying to use the function casin from the complex.h library, but an error ocurres. This is the code:
```
#include <stdio.h>
#include <complex.h>
#include <math.h>
int main() {
double complex z = 1.0 - 1.0 * I;
double complex arcz = casin(z);
return 0;
}
```
I'm getting an "Undefined reference to casin"
|
You lacked#include <complex.h>, and need to specify the math library while compile, e.g.,
```
gcc -std=c11 -Wall test.c -o test -lm
```
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed6 years ago.Improve this question
Does linux provide any tools to provide the information like man which will give me the details about the c keywords?
For. e.g. man auto
|
You cannot do it directly. As P.P. pointed out in the comments you can check out the doc on thecppreferencewebsite.
However you can installcpp manon your machine, which will allow you to consult these reference pages as a man page offline on your computer.
It is quite convenient especially if you have to work without a network connexion for a while (e.g. in the plane or train).
|
This question already has answers here:Undefined reference to `sin` [duplicate](4 answers)Closed6 years ago.
I'm trying to use the function casin from the complex.h library, but an error ocurres. This is the code:
```
#include <stdio.h>
#include <complex.h>
#include <math.h>
int main() {
double complex z = 1.0 - 1.0 * I;
double complex arcz = casin(z);
return 0;
}
```
I'm getting an "Undefined reference to casin"
|
You lacked#include <complex.h>, and need to specify the math library while compile, e.g.,
```
gcc -std=c11 -Wall test.c -o test -lm
```
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed6 years ago.Improve this question
Does linux provide any tools to provide the information like man which will give me the details about the c keywords?
For. e.g. man auto
|
You cannot do it directly. As P.P. pointed out in the comments you can check out the doc on thecppreferencewebsite.
However you can installcpp manon your machine, which will allow you to consult these reference pages as a man page offline on your computer.
It is quite convenient especially if you have to work without a network connexion for a while (e.g. in the plane or train).
|
```
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int *x= 0;
int y = 0;
x = &y;
*x = 1;
printf("%i\n",x);//an address
printf("%i\n",*x);//1
*(x+1)=10;
printf("%i\n",x);//10 ---->unexpected
printf("%i\n",x+1);//14 ---->more wierd
printf("%i\n",*(x+1));//seg fault
return 0;
}
```
In this case the last printf statement will output a seg fault. The value of x changes to 10 after *(x+1)=10. However the value of *(&y+1) is indeed changed to 10. The statement *(x+1)=10 should not affected x imo.
|
You used wrong control string for pointer (%i)
```
printf("%i\n",x);//10 ---->unexpected
```
You should use%pinstead
```
printf("%p\n",(void*) x);
```
Also the access to pointer(x + 1)is causes undefined behavior, because the initial pointerxpoints to a single integer, and so dereferencing(x + 1)is out of bound and undefined.
|
I'm making a program which reads from stdin or from a file and counts number of if statements. I've done it but if for example I have a variable called "asdifasd" or "ifasd" it shall be counted as an if statement. How do I extract solely the if-statements? Here's my code:
```
char str[150];
int ifs = 0;
while (fgets(str, sizeof(str), stdin) != NULL)
{
char *p = str;
while (((p = (strstr(p, "if"))) != NULL)) {
ifs++;
++p;
}
}
```
I've been thinking about doing something withstrncmpbut I'm not sure how.
|
After you've found "if" using strstr, check the characters immediately before and after to make sure they're not a letter. Like:
```
{
char *p = str;
while (((p = (strstr(p, "if"))) != NULL)) {
if ((p == str || !isalnum((unsigned char) p[-1])) &&
!isalnum((unsigned char) p[2]))
++ifs;
++p;
}
}
```
|
I am having a hard time using TinyXML2 (https://github.com/leethomason/tinyxml2) to write a C/C++ method that replaces a given node like:
```
<doc>
<replace>Foo</replace>
</doc>
```
...with another node:
```
<replacement>Bar</replacement>
```
...so that the outcome is:
```
<doc><replacement>Bar</replacement>
</doc>
```
However, the node to be replaced may appear multiple times an I would like to keep the order in case I replace the second node with something else.
This should actually be straight-forward, but I am failing with endless recursions.
Is there probably an example around of how to do that? Any help would be greatly appreciated.
|
Do you have sample code?
You could try callingtinyxml2::XMLNode::InsertAfterChildto insert<replacement>followed by a deletion of<replace>.
This answer also seems related:Updating Data in tiny Xml element
|
I want to populate a grid with 1s and 0s.
My program crashes due to the random variable r. It works perfectly fine with a constant(eg: say r=8). I have usedsrand(time(NULL));
```
void initGrid(int grid[GRID_HEIGHT][GRID_WIDTH])
{
int i,j,r;
for(i=0;i<GRID_HEIGHT;i++)
{
r = rand()%10;
for(j=0;j<GRID_WIDTH;j++)
{
grid[i][j]= (i*j+i+j)%(r)<=2?1:0;
}
}
}
```
|
You have a "Divide by 0" error.
```
r = rand()%10;
```
gives the range ofras0..9so using that0for the modulus in(i*j+i+j)%(r)is causing the error.
I suggest you use
```
r = 1 + rand()%10;
```
|
I want to populate a grid with 1s and 0s.
My program crashes due to the random variable r. It works perfectly fine with a constant(eg: say r=8). I have usedsrand(time(NULL));
```
void initGrid(int grid[GRID_HEIGHT][GRID_WIDTH])
{
int i,j,r;
for(i=0;i<GRID_HEIGHT;i++)
{
r = rand()%10;
for(j=0;j<GRID_WIDTH;j++)
{
grid[i][j]= (i*j+i+j)%(r)<=2?1:0;
}
}
}
```
|
You have a "Divide by 0" error.
```
r = rand()%10;
```
gives the range ofras0..9so using that0for the modulus in(i*j+i+j)%(r)is causing the error.
I suggest you use
```
r = 1 + rand()%10;
```
|
I have long line to configure 14 GPIO pins in intel quark D2000 microcontroller this line written by C language
the code:
```
cfg.direction = PM[0]<<(TPN[0])|PM[1]<<(TPN[1])|PM[2]<<(TPN[2])|PM[3]<<(TPN[3])|PM[4]<<(TPN[4])|PM[5]<<(TPN[5])|PM[6]<<(TPN[6])|PM[7]<<(TPN[7])|PM[8]<<(TPN[8])|PM[9]<<(TPN[9])|PM[10]<<(TPN[10])|PM[11]<<(TPN[11])|PM[12]<<(TPN[12])|PM[13]<<(TPN[13]);
```
Is it possible to rewrite this code by using "for loop"?
Note: "TPN" and "PM" are arrays. "direction" declared as uint8_t variable in the cfg structure
|
Should be possible like:
```
int j;
cfg.direction = 0;
for (j=0; j<14; ++j)
{
cfg.direction |= PM[j]<<TPN[j]);
}
```
If you can't write tocfg.directionuntil you have the final value just use a temp variable:
```
int j;
temp = 0;
for (j=0; j<14; ++j)
{
temp |= PM[j]<<TPN[j]);
}
cfg.direction = temp;
```
|
In file "cerberOS_BSP.h" I have the following:
```
extern char cmp_ids[][];
extern UInt8 periph_list[];
```
In file "BSP_unpnp.c", I have:
```
UInt8 periph_list[AMOUNT_OF_PERIPH] = {0};
char cmp_ids[MAX_CMPS][4] = {0};
```
This gives no errors for periph_list but gives the following for cmp_ids:
```
../../uJ/cerberOS_BSP.h:55:13: error: array type has incomplete element type
extern char cmp_ids[][];
```
Unsure on how to solve this since I don't fully understand the issue, any ideas?
|
In the case of …
```
char cmp_ids[][];
```
… you have two dimensions with open (unspecified) size. Since the location of an element is calculated bystart + index * sizeofelements, it is necessary to know the size of the elements.
The element of the outer array is the inner arraychar[]. The size is not known.
You can only omit the most outer size. All other sizes have to be specified.
|
In VStudio 2010, I'm trying to create a union to access a 2-byte value conveniently:
```
#pragma pack(push,1) // disable padding
typedef struct {
uint8_t r:3;
uint8_t g:3;
uint8_t b:3;
}tsRgb;
typedef union {
uint16_t raw;
tsRgb rgb;
}tPixelData;
#pragma pack(pop)
int main(){
tPixelData pixel;
pixel.raw = 0xABE5;
return 0;
}
```
I'm expecting to see pixel.r = 5, pixel.g = 4, pixel.b = 7.
the r and g are ok, but the b is 3.
What am I doing wrong? I assume I'm not alligning the bits correctly?
|
The third field will be in a separate byte.
In VC++ the bitfields do not cross the boundaries of the underlying type. When you have used 3+3 bits there are only 2 left, so the next field will use 3 bits from a fresh byte.
It might work better if you useuint16_tinstead ofuint8_t.
"Disable padding" works on the byte level, not on the bit level.
|
I have a code like this in C:
```
typedef struct _a1{
int d1;
} a1, *pa1;
```
I can create another pointer and use it like:
```
a1 *pa2 = NULL;
pa2 = (a1*)malloc(sizeof(a1));
```
Trying the same for "pa1" fails. How do I use pointer "pa1"?
|
In case it's not clear,pa1 is not a pointer to an a1 struct. What you're doing with the typedef is just defining two types - one a type that is pointer to your struct (p1=a1*), and one the struct itself (a1). For me this works without a problem:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct _a1{
int d1;
} a1, *p1;
int main() {
p1 p2 = NULL;
p2 = (p1)malloc(sizeof(a1));
printf("%p\n",p2);
return 0;
}
```
And I suggest readingIs it a good idea totypedefpointers?— I wholeheartedly agree.
|
I have downloaded some library and it declares the functions the following way:
```
#if !defined(__ANSI_PROTO)
#if defined(_WIN32) || defined(__STDC__) || defined(__cplusplus)
# define __ANSI_PROTO(x) x
#else
# define __ANSI_PROTO(x) ()
#endif
#endif
int httpdAddVariable __ANSI_PROTO((httpd*,char*, char*));
```
What is the role of__ANSI_PROTOhere? Why it is preferred to declaring simply as
```
int httpdAddVariable (httpd*,char*, char*);
```
|
Pre-ANSI C didn't support this:
```
int httpdAddVariable (httpd*,char*, char*);
```
It only supported this:
```
int httpdAddVariable (); /* = arguments unspecified*/
```
So that's what the macro does. It pastes the argument types into the declaration if it detects prototype support; otherwise, it just pastes().
|
I want to print prime numbers between 1 to 100, I write my code like the following but when I run it, it starts printing 3,7,11,17....91
Why not the code print 2?
Please help me friends
```
#include <stdio.h>
int main(void)
{
for(int i=2;i<100;i++)
{
for(int j=2;j<i;j++)
{
if(i%j==0)
break;
else if(i==j+1)
printf("%d\n",i);
}
}
}
```
|
The conditioni==j+1will not be true fori==2. This can be fixed by a couple of changes to the inner loop:
```
#include <stdio.h>
int main(void)
{
for (int i=2; i<100; i++)
{
for (int j=2; j<=i; j++) // Changed upper bound
{
if (i == j) // Changed condition and reversed order of if:s
printf("%d\n",i);
else if (i%j == 0)
break;
}
}
}
```
|
```
#include <stdio.h>
int main(void) {
printf("%d\n", 50.2);
return 0;
}
```
~ When I execute it.
Binary of 50.2 is ( 0100 0010 0100 1000 1100 1100 1100 1101 ).
So, I expected 1,112,067,277, but, the values are not, nor fixed.
The values are changed every time, Why?
|
This is because, using wrong argument type for a format specifier invokesundefined behavior.
QuotingC11, chapter §7.21.6.1,fprintf()
d,iTheintargument is converted to signed decimal
which tells that%dexpects an argument of typeintand,
[....] If any argument is
not the correct type for the corresponding conversion specification, the behavior is
undefined.
So, you're passing adouble(in general, even afloatargument also gets promoted todouble.) where anintis expected.
|
In Python, I can initialize variables with itterables and automatic unpacking like in
```
a,b,c = [1,2,5]
```
In (openCL) C, can I do something similar, like so
```
uint4 vec = (uint4)(1,2,3,4);
uint a,b,c,d;
a,b,c,d = vec;
```
or do I have to use explicit vector components? Or is there any other good way to do this in a simple and correct way?
|
You need to assign values to each of the variables separately. You of course can write some specific function/macro do this task, but it's not worth it.
|
How can multiple process access STDIN,STDOUT at the same time. And each of them has its own instances running independently without causing problem in other process i/o ?
|
STDIN and STDOUT are just aliases for I/O streams. Each process has its own STDIN and STDOUT.
However, it is possible for two processes to have their own STDIN and STDOUT mapped to the same stream. The results are bizarre.
Try running multiple programs in the background that read from and write to the console.
The way the system avoids chaos is through system protection. A normal user cannot run a program from a terminal that reads and writes to someone else's terminal.
But, if you want to screw yourself up by running multiple programs that read from and write to YOUR console/terminal, the system does not protect you from yourself.
|
When writing to a binary file, when should I use.binvs.dat? If I'm just trying to store information not meant to be read by humans, like item description/serial number pair, does it matter which one I pick if I'm just trying to make it unreadable from a text editor?
|
Let me give you some brief details about these files :
.BIN File : The BIN file type is primarily associated with 'Binary File'. Binary files are used for a wide variety of content and can be associated with a great many different programs. In general, a .BIN file will look like garbage when viewed in a file editor.
.DAT File : The DAT file type is primarily associated with 'Data'. Can be just about anything: text, graphic, or general binary data. Data file in special format or ASCII.
Reference:Abhijit Banerjee answered that question on quora
|
I am writing C++ program with use of glew,glut and GLM.
When I am creating shader like this:
```
GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER);
```
it says "Segmentation fault(core dumped)".My hardware is Intel Atom CPU.OS:OpenSuse 13.2 32-bit.What I need to do to make it work?
|
You're not checking OpenGL extensions, version, or etc.
```
GLenum err = glewInit();
if (err != GLEW_OK)
exit(1); // or handle the error in a nicer way
if (!GLEW_VERSION_2_1) // check that the machine supports the 2.1 API.
exit(1); // or handle the error in a nicer way
```
This code needs to happen after creating the OpenGL context, but before using any potentially-not-existing functions. More details on theGLEW web page
|
```
#include<stdio.h>
#include<conio.h>
void main(){
printf("Hello%c%cWorld",92,110);/*92 is ASCII value of \ and 110 is ASCII value of n*/
getch();
}
```
Output of above program is Hello\nWorld.
|
The interpretation of escape sequence happens in translation phase whereas, in your code, the sequence onlyappearsat runtime.
Moreover, the newline,\nis not acombinationof two separatecharliterals\andn, it is a single value, denoted ny\n.
See theASCII table, a newline has ASCII value of 10.
|
I'm planning a function that takes the user's input (4 integers) and checks if each integer is bigger than 1 and smaller than 6, I wanted something simple, and thought that if the function 'getche()' (I want to use this particular function because I don't want the user to type the 'enter' key after he gives the input) could get four integers in one code.
I want to avoid this(if possible):
```
int num1 = 0, num2 = 0, num3 = 0, num4 = 0;
num1 = getche();
num2 = getche(); ...
```
And I was thinking if something like this is possible:
```
int num = 0;
num = getche(4)
```
Thanks.
|
Couldn't you just use a loop with appropriate conditions and getch() function? It might turn out to be easier.
```
int l = 0;
while (l < 4)
{
x = getch();
// your conditions
}
```
|
I have a code like this in C:
```
typedef struct _a1{
int d1;
} a1, *pa1;
```
I can create another pointer and use it like:
```
a1 *pa2 = NULL;
pa2 = (a1*)malloc(sizeof(a1));
```
Trying the same for "pa1" fails. How do I use pointer "pa1"?
|
In case it's not clear,pa1 is not a pointer to an a1 struct. What you're doing with the typedef is just defining two types - one a type that is pointer to your struct (p1=a1*), and one the struct itself (a1). For me this works without a problem:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct _a1{
int d1;
} a1, *p1;
int main() {
p1 p2 = NULL;
p2 = (p1)malloc(sizeof(a1));
printf("%p\n",p2);
return 0;
}
```
And I suggest readingIs it a good idea totypedefpointers?— I wholeheartedly agree.
|
I have downloaded some library and it declares the functions the following way:
```
#if !defined(__ANSI_PROTO)
#if defined(_WIN32) || defined(__STDC__) || defined(__cplusplus)
# define __ANSI_PROTO(x) x
#else
# define __ANSI_PROTO(x) ()
#endif
#endif
int httpdAddVariable __ANSI_PROTO((httpd*,char*, char*));
```
What is the role of__ANSI_PROTOhere? Why it is preferred to declaring simply as
```
int httpdAddVariable (httpd*,char*, char*);
```
|
Pre-ANSI C didn't support this:
```
int httpdAddVariable (httpd*,char*, char*);
```
It only supported this:
```
int httpdAddVariable (); /* = arguments unspecified*/
```
So that's what the macro does. It pastes the argument types into the declaration if it detects prototype support; otherwise, it just pastes().
|
I want to print prime numbers between 1 to 100, I write my code like the following but when I run it, it starts printing 3,7,11,17....91
Why not the code print 2?
Please help me friends
```
#include <stdio.h>
int main(void)
{
for(int i=2;i<100;i++)
{
for(int j=2;j<i;j++)
{
if(i%j==0)
break;
else if(i==j+1)
printf("%d\n",i);
}
}
}
```
|
The conditioni==j+1will not be true fori==2. This can be fixed by a couple of changes to the inner loop:
```
#include <stdio.h>
int main(void)
{
for (int i=2; i<100; i++)
{
for (int j=2; j<=i; j++) // Changed upper bound
{
if (i == j) // Changed condition and reversed order of if:s
printf("%d\n",i);
else if (i%j == 0)
break;
}
}
}
```
|
I've got this (example) code:
```
int c = getchar();
int other_variable = rand();
// set conditions based on user input, etc.
if (c == 'a') {
// some code here
return;
}
if (c == 'b') {
// some code here
if (other_variable == 0)
return;
}
if (c == 'c') {
// some code here
return;
}
// rest of the conditions
```
I'd like to shorten this code by usingelse ifs and removing thereturns. I don't know how to do this, because the program should keep going through the if-statements only whenother_variableisn't 2. What should I do?
|
Probably you can add the check in the condition and leave the body empty:
```
if (condition1) {
do_something();
}
else if (condition2 && !do_stuff()) {
} else if (...)
```
but this is confusing. You may find better ways to simplify than just removing returns, if you think more about your logic as a whole.
|
I have lock on particular bytes in file using fcntl with some values of fl.1_start and f1.1_len. while program is running, i tried to write into that file from other program on those bytes. when both programs running simultaneously, second program is writing into those locked bytes despite lock present from first program. can anyone explain why it is behaving like that?
|
fcntlis kind of voluntary implementation in Unix like systems. Both processes have to use it in order to work correctly.
Operations likeread()andwrite()simply ignore locks. The other process is blocked only when explicitly callingfcntl()on the area which is already locked by other process
|
I am reading something and I don't understand the meaning of the bit shift that stated below but I think it is basically programming question. I am reading a file and see this#define PIN_GEN (((uint32_t)1)<<31), but I don't quite understand the meaning of(((uint32_t)1)<<31). Could somebody tell me what is the meaning of this?
|
((uint32_t)1)<<31--> Make constant 1 of typeuint32_t(32-bit unsigned with no padding) then shift left 31 places. Same as
```
((uint32_t) 2147483648u)
```
The value is likely used as some sort of bit mask to indicate which bit to set.
|
TheGNU libc manualmentions that there are historical reasons that the data structure representing "streams" is called FILE.
After getting curious i've googled around and tried to look into it but I can't seem to find this fabulous tale.
Any ideas?
|
While I don't have a citation for this, it's likely that the historical reasonfor the creation of the term "stream"is standardization of the C language.FILEis the type that was always used withFILE *handles for stdio in C, but in order to express the specification for the stdio interfaces, it's necessary to be able to distinguish between afile(the actual storage object) and the handle for an open file, and "stream" seems to have been the word that was chosen.
|
I'm trying to code simple push function and everything is fine until run time, executed code crashes. Anyone can clarify the reason, please ?
```
#include<stdio.h>
#include<stdlib.h>
typedef struct list{
int order;
struct list *next;
}list;
void push(struct list **arg,int i);
int main()
{
struct list **ptr=NULL;
for(int i=0;i<10;++i){
push(ptr,i);
}
return 0;
}
void push(struct list **arg,int i){
struct list *temp;
temp= malloc(sizeof(list));
temp->order=i;
temp->next=*arg;
*arg=temp;
}
```
|
Write
```
list *ptr=NULL;
^^^
for(int i=0;i<10;++i){
push( &ptr,i);
^^^^
}
```
Otherwise if to declare like this
```
struct list **ptr=NULL;
```
then this dereferencing
```
*ptr
```
results in undefined behavior.
|
How to decide if two ip are on the same subnet or not?
The only input is the ip address and the subnet mask!
What is the optimal way, usingC/C++, to compute if two ip have the same subnet?
|
```
bool checkForSubnetEquality(in_addr_t ipA, in_addr_t ipB, uint32_t subnetMask) {
return (ipA & subnetMask) == (ipB & subnetMask);
}
```
|
I have searched on the Internet but most of the answers suggest using library conio.h which is not available. Can anyone give me answer for this question. Thanks in advance.
|
If you are on Windows
system("cls");
If you are on Linux/unix
system("clear");
|
I'm trying to code simple push function and everything is fine until run time, executed code crashes. Anyone can clarify the reason, please ?
```
#include<stdio.h>
#include<stdlib.h>
typedef struct list{
int order;
struct list *next;
}list;
void push(struct list **arg,int i);
int main()
{
struct list **ptr=NULL;
for(int i=0;i<10;++i){
push(ptr,i);
}
return 0;
}
void push(struct list **arg,int i){
struct list *temp;
temp= malloc(sizeof(list));
temp->order=i;
temp->next=*arg;
*arg=temp;
}
```
|
Write
```
list *ptr=NULL;
^^^
for(int i=0;i<10;++i){
push( &ptr,i);
^^^^
}
```
Otherwise if to declare like this
```
struct list **ptr=NULL;
```
then this dereferencing
```
*ptr
```
results in undefined behavior.
|
How to decide if two ip are on the same subnet or not?
The only input is the ip address and the subnet mask!
What is the optimal way, usingC/C++, to compute if two ip have the same subnet?
|
```
bool checkForSubnetEquality(in_addr_t ipA, in_addr_t ipB, uint32_t subnetMask) {
return (ipA & subnetMask) == (ipB & subnetMask);
}
```
|
I have searched on the Internet but most of the answers suggest using library conio.h which is not available. Can anyone give me answer for this question. Thanks in advance.
|
If you are on Windows
system("cls");
If you are on Linux/unix
system("clear");
|
I have a problem,
```
1U << 0 = 1
1U << 1 = 2
1U << 2 = 4
```
etc... okey..
for example ;
```
1u<<1<<2
```
Can you tell me this mean ?
|
As<<1is left associative2this is1U<<1<<2 = 2<<2 = 8U
1: Biwise shift left2:associativityindicates in what order operators of equal precedence in an expression are applied.Note: The result of a bit shift operation on a signed argument gives implementation-defined results, so in theory1U<<xis more portable than1<<x
|
How to cast "ptr" to assign directly a zend_long into it without writing two lines?
```
zend_long *val = *ptr;
*val = *(ISC_LONG*)var->sqldata;
```
|
Assuming that your original code is correct, the corresponding assignment looks like this:
```
*((zend_long*)*ptr) = *(ISC_LONG*)var->sqldata;
```
|
```
#include <stdio.h>
int x,y;
y = 999;
int main()
{
printf("\nEnter a whole number: ");
scanf("%d ", &x);
y = ((x >= 1) && (x <= 20)) ? x : y;
printf("%d ", y);
return 0;
}
```
I can not get this program to do what I want. I'm asking a user to enter a whole number. If that number is between 1-20 I want it to spit that number back out. If not I want it to spit out value for "y". I do not want to use an "if" statement.
|
You need to change
```
scanf("%d ", &x);
```
to
```
scanf("%d", &x); // remove trailing whitespace
^^
```
Because, the input needs to be anexactmatch for the suppliedformat string.
Otherwise, to match the trailing newline (whitespace), you need to provide a whitespace explicitlyanda terminating condition, too. (example: pressENTER, then input any other non-whitespace and pressENTERagain).
|
How can I write in a buffer (unsigned char*) with MagickWand?
Currently I generate an image and save it to file, but I need it in memory:
```
MagickNewImage( wand, 640, 480, p_wand );
MagickWriteImage( wand, "test.jpg" );
```
|
According to the documentation there is a functionMagickGetImageBlobthat returnsunsigned char *which is seemingly what you are looking for. Its exact documentation is
MagickGetImageBlob()implements direct to memory image formats. It returns the image as a blob (a formatted "file" in memory) and its length, starting from the current position in the image sequence. UseMagickSetImageFormat()to set the format to write to the blob (GIF, JPEG, PNG, etc.).
Note that this does require you to set the format usingMagickSetImageFormat, but on the whole this seems to be the closest thing to what you are looking for.
|
I'm trying to have precision of 12 decimals in C. I don't know if there's an easier solution. But at least that code works. Now I'm just trying to save the result in a "long double" but "strtold()" is not working
```
char* multiply12Decimals(float n1, float n2)
{
long n1Digits;
sscanf(doubleToVoidPointerInNewMemoryLocation(n1*1000000), "%ld", &n1Digits);
printf("n1Digits: %ld\n", n1Digits);
long n2Digits;
sscanf(doubleToVoidPointerInNewMemoryLocation(n2*1000000), "%ld", &n2Digits);
printf("n2Digits: %ld\n", n2Digits);
long long mult = (long long) n1Digits*n2Digits;
printf("mult: %lld\n", mult);
char *charNum = malloc(30*sizeof(char));
sprintf (charNum, "0.%012lld\n", mult);
printf("result: %s\n", charNum);
return charNum;
}
```
|
printf("%.12lf",num);solves the problem.
Multiply two double and print it like this. No need to uselong.
|
I've got moderately stuck, googling the right words can't got me to the right answer. Even worse, I've already done that but my own code example lost somewhere in the source code.
```
#include <stdio.h>
int main()
{
short x = 0xABCD;
char y[2] = { 0xAB, 0xCD };
printf("%x %x\n", y[0], y[1]);
printf("%x %x\n", (char *)&x[0], (char *)&x[1]);
}
```
Basically I need to access individual variable bytes via array by pointer arithmetic, without any calculations, just by type casting.
|
Put parentheses around your cast:
```
printf("%x %x\n", ((char *)&x)[0], ((char *)&x)[1]);
```
Note that endian-ness may change your expected result.
In the future, compile with-Wallto see what the warnings or errors are.
|
```
int f(int n)
{
if (n <= 1)
{
return 1;
}
return f(n - 1) + f(n - 1);
}
```
I know that the time complexity isO(2^n)and I understand why.
But I don't understand why the space complexity isO(n).
I was told that it's because at any given time there are onlynnodes, but it doesn't make sense to me.
|
Because the secondf(n-1)can't run until the first one completes (or vice versa -- it's the same either way). The first call will recursentimes, then all those will return, so that will push a total ofnstack frames. Then the second call will do the same thing.
So it never gets more thannlevels deep in the recursion, and that's the only contributor to space complexity.
|
I don't understand how pointers to chars differ from pointers to ints for example:
```
int a = 10;
int *b = &a;
printf("%d\n", *b); // print 10
char* d = "Hello";
printf("%d\n", (int) *d); // print 72, ASCII of H
```
Here what is "Hello"? Is every character an address to an int and thus "Hello" an array of addresses?
|
C is not strictly type-safe, especially theprintffunction which accepts anything as input (the...syntax), how it's interpreted is handled by the format string:%dsays "treat the Nth argument as a decimal integer".
Achar*is a different type toint*. Another way they differ is how they behave when you increment achar*compared to anint*:
```
char* c1 = "foo";
char* c2 = c1 + 1;
// c2 is c1 + 1, as sizeof(char) == 1
int* i1 = &123;
int* i2 = i1 + 1;
// i2 is i1 + 4 as sizeof(int) == 4, assuming your system uses 4-byte integers
```
|
Here is a simple code , trying to clear spaces from character array, but output is not like I did expect "YasserMohamed".
```
#include<stdio.h>
int main()
{
char x[]="Yasser Mohamed";
char ch;
int i=0;
while (x[i]!='\n')
{
if(x[i]!=' ')
putchar(x[i]);
i++;
}
system("pause");
return 0 ;
}
```
|
There's nonewline('\n') inx. So, the condition is wrong and it should be:
```
while (x[i]) /* until the null byte is found */
{
if (x[i] != ' ')
putchar(x[i]);
i++;
}
```
|
This question already has answers here:Printing hexadecimal characters in C(8 answers)Closed6 years ago.
```
#include <stdio.h>
int main()
{
int x = 255;
char hex[4] = {0};
hex[0] = 0x02;
hex[1] = 0x20;
hex[2] = 0xef;
hex[3] = x;
for(int i = 0; i < 4; i++)
printf("%X ", hex[i]);
}
```
This outputs " 2 20 FFFFFFEF FFFFFFFF". What should be changed so that it would output "02 20 EF FF"?
|
The question is the data overflowed.charis -128 ~ 127, when 0xef = 239.
So you can use typeintorshortor justunsigned char, like that:
```
#include <stdio.h>
int main()
{
int x = 255;
unsigned char hex[4] = {0};
hex[0] = 0x02;
hex[1] = 0x20;
hex[2] = 0xef;
hex[3] = x;
for(int i = 0; i < 4; i++)
printf("%02X ", hex[i]);
}
```
|
newbie here:
the following program to generate all prime numbers under 100 using the "Sieve of Eratosthenes algorithm" works fine, but crashes after displaying theCORRECToutput!
the error in windows: primenumber.exe has stopped working!
```
#include<stdio.h>
int main()
{
int P[100] = {0}, i, j;
for(i = 2; i < 100; ++i)
{
if(P[i] == 0)
printf("%d\n", i);
for(j = 1; i * j <= 100; ++j)
P[i * j] = 1;
}
return 0;
}
```
|
i*j<=100array index out of bound -- UB...(Undefined Behavior)
It should bei*j<100.
|
This question already has answers here:Is there any way to loop through a struct with elements of different types in C?(5 answers)Closed6 years ago.
I am writing program in C. I would like to print out values of each element in struct, so that I can print out according value for each bitmap header member. Hence, is it possible to iterate trough each element of struct?
Also is it possible to get number of elements in struct if each element is different size?
Regards
|
No, you cannot do this in C. There is no iterator over data types. You have to print each field in your struct separately in your function.
Addition:
One way to do this on your own would be to use X-Macros as suggested by coderredoc. But it might get a bit nast for different data types to print.
|
I have a project, written in C which I want to use in Xamarin Forms. What is the best way to use this code? Generate libraries for each platform?
What I'd prefer is to have one wrapper that I can use in shared code that doesn't have to be implemented for each platform.
|
Unfortunately, the way binding works is different for Android and iOS, so you would need to generate libraries for each platform.
You can read more about how that is doneherefor iOS andherefor Android. For iOS, you can consider usingObjective Sharpiewhich will do the most of the work for you.
Afterwards, you can simply useDependecyServiceto access the native platform features.
|
newbie here:
the following program to generate all prime numbers under 100 using the "Sieve of Eratosthenes algorithm" works fine, but crashes after displaying theCORRECToutput!
the error in windows: primenumber.exe has stopped working!
```
#include<stdio.h>
int main()
{
int P[100] = {0}, i, j;
for(i = 2; i < 100; ++i)
{
if(P[i] == 0)
printf("%d\n", i);
for(j = 1; i * j <= 100; ++j)
P[i * j] = 1;
}
return 0;
}
```
|
i*j<=100array index out of bound -- UB...(Undefined Behavior)
It should bei*j<100.
|
This question already has answers here:Is there any way to loop through a struct with elements of different types in C?(5 answers)Closed6 years ago.
I am writing program in C. I would like to print out values of each element in struct, so that I can print out according value for each bitmap header member. Hence, is it possible to iterate trough each element of struct?
Also is it possible to get number of elements in struct if each element is different size?
Regards
|
No, you cannot do this in C. There is no iterator over data types. You have to print each field in your struct separately in your function.
Addition:
One way to do this on your own would be to use X-Macros as suggested by coderredoc. But it might get a bit nast for different data types to print.
|
I have a project, written in C which I want to use in Xamarin Forms. What is the best way to use this code? Generate libraries for each platform?
What I'd prefer is to have one wrapper that I can use in shared code that doesn't have to be implemented for each platform.
|
Unfortunately, the way binding works is different for Android and iOS, so you would need to generate libraries for each platform.
You can read more about how that is doneherefor iOS andherefor Android. For iOS, you can consider usingObjective Sharpiewhich will do the most of the work for you.
Afterwards, you can simply useDependecyServiceto access the native platform features.
|
I have a project, written in C which I want to use in Xamarin Forms. What is the best way to use this code? Generate libraries for each platform?
What I'd prefer is to have one wrapper that I can use in shared code that doesn't have to be implemented for each platform.
|
Unfortunately, the way binding works is different for Android and iOS, so you would need to generate libraries for each platform.
You can read more about how that is doneherefor iOS andherefor Android. For iOS, you can consider usingObjective Sharpiewhich will do the most of the work for you.
Afterwards, you can simply useDependecyServiceto access the native platform features.
|
I'm trying to detect if there is a menu opened for the main window,
something like:
```
GUITHREADINFO gtinf = { sizeof(GUITHREADINFO) };
GetGUIThreadInfo(0, >inf);
if (gtinf.flags & GUI_INMENUMODE || gtinf.flags & GUI_POPUPMENUMODE)
{
//...
}
```
butgtinf.flagsis always zero, even if menu is obviously opened.
OnlyhwndActiveandhwndFocusare correctly set.
What's the problem ?
|
It turned out that app uses non-standard mechanism for displaying menus, and therefore gui thread is not aware of. – olpchk
|
I have a file descriptor, now I want to write n bytes to that file replacing n bytes of original data (so the total file size won't change), like in replace mode of a word processor. Any convenient way to achieve this?
|
Justwriteto the fd. You might need toreadup to the right position before orlseekorlseek64directly to the right position.
You must be sure that the fd is writable. You need to checkopenfor that.openmust have been called withO_WRONLYorO_RDWRbut withoutO_TRUNCwhich would have truncated the file to zero length.
Note:writeto a file only changes (increases) the file size if you are writing over the end of the file. If you are writing right into the file it's size does not change.
|
I am trying to understand what is the purpose of the kernel symbolinet_addr_lstas defined inhttp://lxr.free-electrons.com/source/net/ipv4/devinet.c#L108Does it contain a list of all the ip addresses on the system or something else?
|
The hashtable is an array of struct hlist_head pointers, where each one points to a different list, and each one of those lists holds all elements that are hashed to the same bucket. So every element is essentially part of a hlist and the hashtable only holds the head of these lists.
inet_addr_lst is a array of struct hlist_head type. so you can use this strcut to store and checking the ip address/ broadcast address . Example "you register all local registered broadcast addresses in inet_addr_lst"
|
Is it possible to dereference a void pointer without a cast knowing(during execution) the size of the item located in memory ? Or, if not possible with a void pointer, how can I access a specific memory address(located in the heap) and read an only-known during execution specific number of bytes ?
|
With achar *which basically points to a byte size of memory you can access all the bytes of any datatype.
And you can also cast avoid *to necessary type and deference it to get the correct dereferenced value.
|
I am trying to initiate a TCP Three-Way-Handshake in C. However, it occurred to me thatconnectmay already be establishing such a connection or in some way interfering. Doesconnectautomatically establish a TCP connection whenever the socket it's called on has theIPPROTO_TCPoption set?
|
Yes,IPPROTO_TCPcreates TCP socket. To use raw socket, you need to pass SOCK_RAW as second argument to thesocketfunction.
|
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed6 years ago.
testing some code when studying C language,
```
#include <stdio.h>
#include <math.h>
#define hypotenusa(x, y) sqrt((x) * (x) + (y) * (y))
int main(void) {
int a, x;
x = 2;
a = hypotenusa(++x, ++x);
printf("%d\n", a);
}
```
And I am getting the answer
6in one program(dosbox gcc compiler)7in codelight gcc compiler and8on codeChef online compiler
can anyone explain this behaviour?
my logic says it should be6(sqrt(42)) but...
|
It'sundefined behaviour.
After the macro replacement
```
a = hypotenusa(++x, ++x);
```
becomes:
```
a = sqrt((++x) * (++x) + (++x) * (++x));
```
As you can seexis modified multiple times without any intervening sequence point(s). SeeWhat Every C Programmer Should Know About Undefined Behavior.
|
How would I go to cast/convert literalchar '0'toint 0?
i.e.:
```
char string[] = "0101";
char ch = string[0];
x = magic(ch);
if (x)
printf("int zero")
```
|
```
ch = 0;
```
Now, if you want to convertanydigit-character to its numeric equivalent, you'd need something like:
```
ch = ch - '0';
```
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed6 years ago.Improve this question
How exactly does Ncurses capture input into the console? I would like to implement it myself instead of using ncurses due to the overhead that ncurses is causing.
Thanks!
|
Very short and basically: It might usethe TTYioctlcallsto get and set flags needed for the different modes. Then it could simply usereadto read characters in a blocking or non-blocking manner.
Special keys (like the function keys for example) are read using multiple characters which are parsed.
|
I am trying to initiate a TCP Three-Way-Handshake in C. However, it occurred to me thatconnectmay already be establishing such a connection or in some way interfering. Doesconnectautomatically establish a TCP connection whenever the socket it's called on has theIPPROTO_TCPoption set?
|
Yes,IPPROTO_TCPcreates TCP socket. To use raw socket, you need to pass SOCK_RAW as second argument to thesocketfunction.
|
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed6 years ago.
testing some code when studying C language,
```
#include <stdio.h>
#include <math.h>
#define hypotenusa(x, y) sqrt((x) * (x) + (y) * (y))
int main(void) {
int a, x;
x = 2;
a = hypotenusa(++x, ++x);
printf("%d\n", a);
}
```
And I am getting the answer
6in one program(dosbox gcc compiler)7in codelight gcc compiler and8on codeChef online compiler
can anyone explain this behaviour?
my logic says it should be6(sqrt(42)) but...
|
It'sundefined behaviour.
After the macro replacement
```
a = hypotenusa(++x, ++x);
```
becomes:
```
a = sqrt((++x) * (++x) + (++x) * (++x));
```
As you can seexis modified multiple times without any intervening sequence point(s). SeeWhat Every C Programmer Should Know About Undefined Behavior.
|
How would I go to cast/convert literalchar '0'toint 0?
i.e.:
```
char string[] = "0101";
char ch = string[0];
x = magic(ch);
if (x)
printf("int zero")
```
|
```
ch = 0;
```
Now, if you want to convertanydigit-character to its numeric equivalent, you'd need something like:
```
ch = ch - '0';
```
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed6 years ago.Improve this question
How exactly does Ncurses capture input into the console? I would like to implement it myself instead of using ncurses due to the overhead that ncurses is causing.
Thanks!
|
Very short and basically: It might usethe TTYioctlcallsto get and set flags needed for the different modes. Then it could simply usereadto read characters in a blocking or non-blocking manner.
Special keys (like the function keys for example) are read using multiple characters which are parsed.
|
I am trying to programmatically delete a user profile (the right way) using theDeleteProfile()API. Unfortunately, it wants an account SID as the first parameter.
There has to be some magical API that takes a username and spits out an SID, correct? I can't seem to find anything online that is uses native code (I am not using .NET managed code and don't want to use WMI queries or powershell or cmdline tools, etc)
I know you can use the Net32Api to delete an account, but that still leaves artifacts like profile directory, etc. I just want a way to cleanly delete a profile (obviously from elevated code).
Thank you!
|
You can use the buddy functionLookupAccountName().
Seehttps://msdn.microsoft.com/en-us/library/windows/desktop/aa379159(v=vs.85).aspx
|
```
#include <stdio.h>
int add(int, int);
int main(int argc, char const *argv[])
{
int a = 2, b = 3;
printf("%d %d %d\n", a, b, add(a, b));
return 0;
}
int add(int a, int b) {
int c = a + b;
return;
}
```
The output of the above program is 2 3 5 how can the add function return c without explicitly returning it
|
It'sundefined behaviour.
When a function that's supposed to return a value doesn't do soandthe caller uses the return value, it'sundefined. Anything you might observe is purely accidental/platform specific behaviour and not be relied upon. The C standard certainly makes no guarantees.
From C11 draft,6.9.1 Function definitions/12:
If the } that terminates a function is reached, and the value of the
function call is used by the caller, the behavior is undefined.
|
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int cases, num1, num2, var, *ptr2, count, i;
scanf("%d", &cases);
ptr2 = (int*)malloc(sizeof(int) * cases);
memset(ptr2, 0, sizeof(int) * cases);
if (ptr2) {
for (count = 0; count < cases; count++) {
scanf("%d", &num1);
scanf("%d", &num2);
for (i = 0; i < num1; i++) {
scanf("%d", &var);
ptr2[count] += var / num2;
}
}
for (i = 0; i < cases; i++) {
printf("%d\n", ptr2[i]);
}
}
return 0;
}
```
Here's the description of the problemhttps://a2oj.com/p?ID=17It runs on VS IDE very well, but for some reason when I submit it their environment gives me an runtime error.
|
it's solved after switching 'if (ptr2){' with 'memset(ptr2,0...);' – Andrew Naguib
|
It is undefined behavior to do this?
```
char *a = "hello";
char b[] = "abcd";
a = b;
```
My compiler throws no warning, with the maximum warning level.
|
There is no UB here. You are simply re-assigning a pointer to point at the address of the start of the array instead.
Note that you are not actually modifying the value thatais pointing at, onlyaitself, andais a normalchar *.
|
How to convert rgb to hexadecimal using GTK?
I can convert from hex to rgb usinggdk_rgba_parse (GdkRGBA *rgba, const gchar *spec);, but not the reverse.
|
You can do this manually:
```
sprintf(spec, "#%02X%02X%02X", (int)(rgba.red*255), (int)(rgba.green*255), (int)(rgba.blue*255));
```
Be sure to provide a buffer large enough to hold the string or use g_strdup_printf instead.
|
How to convert rgb to hexadecimal using GTK?
I can convert from hex to rgb usinggdk_rgba_parse (GdkRGBA *rgba, const gchar *spec);, but not the reverse.
|
You can do this manually:
```
sprintf(spec, "#%02X%02X%02X", (int)(rgba.red*255), (int)(rgba.green*255), (int)(rgba.blue*255));
```
Be sure to provide a buffer large enough to hold the string or use g_strdup_printf instead.
|
I tried this code.
```
char *env[]={"first=one","second=two","third=three",NULL};
execle("/bin/echo","echo","$first","$second","$third",(char *)0,env);
```
It gives output
```
$first $second $third
```
Clearly this is not what I am expecting. Is their any way to print environment variables using echo?
I gets the variables using printenv. If it relates.
```
execle("/usr/bin/printenv","printenv","first","second","third",(char *)0,env);
```
Output:
```
one
two
three
```
|
Command line expansions are provided by shell before the command is called. To get the expansion as expected you can exec shell with "-c" option and whole command line to be executed.
```
execle("/bin/bash","bash", "-c", "echo $first $second $third",(char *)0,env);
```
|
I'd like to make 2 stage for loop statment from 1 stage in the c.
```
//gray rgb
for (unsigned int i = 0; i < x * y; i++)
{
*(buff2 + i * 3 + 0) = data_[i];
*(buff2 + i * 3 + 1) = data_[i];
*(buff2 + i * 3 + 2) = data_[i];
}
```
But actually I can't get think how do I can make 2 stage.
Can you give a any hint?
|
Hope it would help you:-
```
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
*(buff2 + i*y + j) = data_[i*y+j]
}
}
```
|
I've been learning C recently.
I have difficulty understanding the result of the code below.
Why isb255 at last?
```
unsigned char a=1;
int b=0;
do
{
b++;
a++;
}while(a!=0);
```
|
Anunsigned charcan only take values between 0 and 255. In your code, at each iteration of the loop,aandbboth get incremented by 1 untilareaches 255. Whenais 255 and should be incremented by 1 more, it would have been 256 but since anunsigned charcan only take values between 0 and 255,atakes the value 0 instead of 256. Then, the loop stops because ofwhile(a!=0)andbwill equal 256 - 1 = 255.
|
For the purpose of my school, I am learning how to do a raycast in C.
Based on this tutorial I foundhttp://permadi.com/1996/05/ray-casting-tutorial-7/, the author explains his method to find deltaX and deltaY to check whenever there is a wall at a position based on deltaX or deltaY.
However he's getting deltaX and deltaY via the tangent of an angle a, and it wont work with 0, pi/2, pi and 3pi/2.
How can it work with such solution ? Am I missing something ?
|
At 0 and pi, there's no point in searching for horizontal intersections as the ray is horizontal. You'll need to explicitly check for that case.
At pi/2 and 3pi/2, the tangent is infinite so 1/tan() should give you zero with floating point math. It will work even if it looks ugly.
For vertical intersections, shift the angles by pi/2 and the same reasoning applies.
|
What is a recommended methodology / library for accurate benchmarking of C / C++ code? Something that would overcome the inaccuracies of simply measuring execution time, i.e. that CPU frequency and system load may change across execution times. Not sure if counting executed instructions is the correct approach, because the bottleneck in my code will (probably) be memory access.
|
GNU profiler, gprof, is a traditional way of doing performance measurements for a signle-threaded code. You do not have to instrument the code manually, just add an option to gcc during build.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.