question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
This question already has answers here:What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?(3 answers)Closed6 years ago.
I'm working with a piece of code and I come across with something similar to this:
```
struct {
int a : 1;
int b : 1;
};
```
I don't know what is the function of: 1her... |
This is used to assign value to abit. You can read about bitfieldshere.
|
In the C programming language, a string such as"2147483649"overflows as an int since the largest unsigned int is2147483647. When I want to convert strings of integers toints, how do I go about checking for these overflow cases?
I can't just check if it is>=-(2^32-1)and<= (2^32-1)since the process of converting this s... |
You can convert the resulting integer back to string and compare it to the source string. Although it doesn't look elegant to me. :-)
|
So i'm trying to extracts bits from a 32=bit binary integer using bit shifting and masking, but i'm sightly off by one.
```
#include <stdio.h>
int main (){
int number = 87; //0000 000 0000 0000 0000 0000 0101 0111
int i;
int bit;
int g = 0;
for(i = 32; i > 0; i--){
if(g%4==0 && g!=0){
printf(" ... |
There is logic missing in your code..
Use
```
for(i **= 31**; i **>=** 0; i--)
```
instead of
```
for(i **= 32**; i **>** 0; i--)
```
Comment if it works for you
|
My Source Code
```
for(i=0;str[i]!='\0';i++)
{
if(str[i]!=' '){
str2[j]=str[i];
flag=1;
}
if(flag==1 && str2[j]!=' ')
{
printf("\n");
printf("%c",str2[j]);
flag=0;
}
}
```
My Output:
```
I am joe
I
a
m
j... |
I found it easier to just replace the space characters by new lines
```
#include <stdio.h>
int main() {
char str[] = "I am joe";
for(int i = 0; str[i] != '\0'; i++) {
if(str[i] == ' ')
str[i] = '\n';
}
printf("%s\n", str);
return 0;
}
```
All you have to figure out is how to trim those extra s... |
The arrayoptionscontains elements of this form: "-option=value".
The argumentneeded_optioncontains for example "option"
```
char *function(char *options[], char *needed_option){
for(//go over all possible options){
if(fnmatch("-???=*", options[i], 0) == 0){ //<--- look here
char *ret = extract_... |
prepare it withsprintf()
```
char current[256];
sprintf(current, "-%s=*", needed_option);
//...
if(fnmatch(current, options[i], 0) == 0){ //...
```
|
When we're defining a 2D array as in:
```
int *a[5];
```
Which dimension does the "5" define? The first or the second?
|
It's not a "2D" array. It's a 1-dimensional array of pointers toint. As such the array size designates that it has space for 5 pointers. Each individual pointer can point to the first element of a buffer with different size.
A "true 2D array" is the colloquial "array of arrays"int a[M][N]. Here the expressiona[i]eval... |
Everytime I compile and run c file, I have to type:
gcc filename.c
a.out
I don't want to do this in two lines, How to compile and run in one line on linux terminal?
|
Try
```
gcc filename.c && a.out
```
It only runs the second command if the first was successful. Seehttps://askubuntu.com/questions/334994/which-one-is-better-using-or-to-execute-multiple-commands-in-one-line
|
I'm just trying to make some kind of pointer to "Nall" struct so I wrote this code
```
Nall **headall;
headall = malloc (30000 * sizeof (Nall));
for (i = 0; i < 30000; i++) {
*(headall+i) = newNall;
}
```
and now I get this error
"warning: incompatible pointer types assigning toNall *(akastruct ... |
From the compiler warning I'm assuming thatnewNallis actually a function that allocates a newstruct nodealland returns a pointer to it. In that case, your code should look like this:
```
Nall **headall;
headall = malloc(30000 * sizeof *headall);
for (i = 0; i < 30000; i++)
headall[i] = newNall();
```
Note the argu... |
This is my C code:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node * ptr;
typedef struct node {
int data;
ptr next;
} item;
void printList(ptr p);
int main() {
ptr h = NULL;
}
void printList(ptr p) {
while(p) {
printf("%d -> \n", ptr -> data);
ptr = ptr -> next;
}
}
```
I get 2 ... |
You're referring to the type of the structure member not the structure member.
```
printf("%d -> \n", ptr -> data);
ptr = ptr -> next;
```
should be
```
printf("%d -> \n", p->data);
p = p->next;
```
|
The .txt file will have the matrix we need to input into our program, it may have more than one matrices.
I am using VIM editor on Linux.
Is there any specific escape sequence to copy the .txt file while compiling?
|
To redirect standard output to a file, the>character is used like this:
ls > file_list.txt
And To take input from the file , the<character is used like this:
./a.out < input.txt
|
I created a file with this content:abcand I would like to read (only with theread()function, please don't suggest another one) it and display it on the console with this program:
```
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int fd;
char buf[3];
int size;
fd = open("tes... |
Each call toreadputs the character at the start ofbuf, but you don't always print that part ofbuf.
|
In the following code,2is printed.
```
int x = 1;
int f(int y)
{
return x;
}
int main() {
x = 2;
printf("%d", f(0));
}
```
How is it happening if we have static scoping in C? Why isn't1printed?
Printing2in this case isn't a dynamic scoping, is it?
I thought that in static scoping it should take the ne... |
It does take the nearestx, but since you only have onexit doesn't really matter.
If you change the code to
```
int x = 1;
int f(int y)
{
return x ;
}
int main() {
int x=2;
printf("%d", f(0));
}
```
so you have 2x, the global one and the local one inmainyou will see1getting printed.
|
I have a similar code.
```
#include <stdio.h>
int main() {
FILE* file = fopen("file.txt", "w+");
fputc('A', file);
fflush(file);
char buff;
fscanf(file, "%s", &buff);
printf("read data: %s", &buff);
fclose(file);
return 0;
}
```
I want without close file read written data. But in buff not exist data... |
You should userewind(file)to set the position indicator associated with the file stream to the beginning of the file.
Your example, working fine:
```
#include <stdio.h>
int main() {
FILE* file = fopen("file.txt", "w+");
fputc('A', file);
fflush(file);
rewind (file);
char buff [80];
fscanf(file, "%s", bu... |
I am a newbie in Eclipse and STM32. So I would like to ask you for an advice with a problem which I have been solving. I have got a software for STM32. This software is written in C language and has an existing Makefile. The software is now placed on the SVN server. I need to build the project in Eclipse Neon 4.6.2 ID... |
sedis a unix utility. Maybe executed as a part of your makefile.
The error message is hidden by the second widnow. If it suggests, try to install it on your machine. I use GNU/Linux where it is essential part of the distribution. On Windows you can find a binary after some search.
|
I asked this onTaking an index out of const char* argumentalong with another question, but debate got only to the first question, so I splitted it to a different thread.
Question:
Is there any reason anyone would ever want to represent a C string asconst char*and not asconst unsigned char*?
On one hand, I see the c... |
Yes, of course a general read-only string should beconst char *, sincechar(with unspecified implementation-specified signedness) is the default type for a character.
In other words, a literal like"foo"consists ofchar, notunsigned char, elements.
Of course you can interpret the characters as unsigned if you feel like... |
I have to recode these 3 functions in C and the goal is that the recoded functions have to replace the system functions in different programs or system calls.
I don't really understand what is the behaviour of these functions since I've read the mans, I just know I'm allowed to usebrk()andsbrk().
|
mallocbasically pre allocates memory pages (Cfgetpagesize(2)), and returns pointer to usable parts of those pre allocated areas when called.mallocthen have to "remember" which part of those pre allocated memory segments are being used, and which one are free.
Reading this article:https://www.cocoawithlove.com/2010/05/... |
```
int main(){
char s[]="hi ";
char t[55];
fgets(t,55,stdin);
strcat(s,t);
puts(s);
}
```
I want to concatenate the stringssand the entered stringt, but I'm not getting any output. I have tried usinggetsto read thestringbut the compiler says "use of gets can be dangerous". What should I do?
|
strcat(s,t);is overrunning the destination memory buffers, as it is only large enough for 4 characters (and one of those is occupied by the NUL-terminator).
The behaviour of your program is thereforeundefined.
Make the size ofslarge enough to accommodate its initial contentsplusthe largest string possible int.
|
So I know that
```
struct bit
{
unsigned char a : 1;
}
```
will still take up a byte because of padding, my question is this:
```
struct bit
{
unsigned char a : 1;
...
unsigned char h : 1;
}
```
Will this struct take up the same size as a char? And if so, am I better off just using acharinstead? I'... |
There is no guarantees of anything when using bit-fields. That struct can have any size and any bit order. In factunsigned chartype for bit-fields is not even supported by the standard! Your code is already relying on non-standard extensions.
Forget about bit-fields, forget aboutchar. You should useuint8_tand bitwise... |
We are developing a software on Hi3536 processor based board. TheSDKprovided byHiSiliconcomes with samples for developing user interface using frame buffer API - which is too low level. i.e., to design Combo Box, Text box, we have to write code from Scratch.
We are now trying to use QT. Not sure what other vendors do... |
We referred the sample code given in the following link and we would bring up the GUI successfully in Hi3536 using QT 5.6 -http://bbs.ebaina.com/thread-8217-1-1.html.
Please note that you need to use Google translator to translate the text in chinese.
|
I am experiencing a problem with C language while I am trying to adapt a callback written in C to C++. Compiler shows the following error:
```
error C2664: 'fread' : cannot convert parameter 4 from 'void *' to 'FILE*'
1>Conversion from 'void*' to pointer to non-'void' requires an explicit cast
```
I found that thiss... |
```
fread(ptr, size, nmemb, static_cast<FILE*>(stream))
```
|
How to print the formatting characters such as:%pout? A backslash doesn't do any good as it does with quotations(""). I tried it in a simple toy program and I suppose the value returned by it was garbage :
What I was trying to print was the statement :
```
With the formatting character %p and '&'
```
|
Using double percentage i.e.%%will print single%for you:
```
printf("With the formatting character %%p and '&'\n");
```
|
If I usefork()to spawn a child process, then will the child process automatically terminate once the parent process terminates? Or must this be programmed?
|
This isn't really a c question, it's an O/S question.
In Windows, a process will continue until either it callsExitProcessor when it has performed enough CPU RETs that there's nothing left in the call stack.
In Unix, the process will continue and run as a subprocess ofinit.
On both O/S's, a user with enough permiss... |
I have a char array composed of hex values that looks similar to this:
```
char str[] =
"\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b"
"\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd"
"\x80\xe8\xdc\xff\xff\xff";
```
After manipulating this string, I want ... |
What you need is this:
```
for (size_t i = 0; i != sizeof str - 1; ++i)
fprintf(fp, "\\x%02x", (unsigned char)str[i]);
```
|
In the following code,2is printed.
```
int x = 1;
int f(int y)
{
return x;
}
int main() {
x = 2;
printf("%d", f(0));
}
```
How is it happening if we have static scoping in C? Why isn't1printed?
Printing2in this case isn't a dynamic scoping, is it?
I thought that in static scoping it should take the ne... |
It does take the nearestx, but since you only have onexit doesn't really matter.
If you change the code to
```
int x = 1;
int f(int y)
{
return x ;
}
int main() {
int x=2;
printf("%d", f(0));
}
```
so you have 2x, the global one and the local one inmainyou will see1getting printed.
|
I have a similar code.
```
#include <stdio.h>
int main() {
FILE* file = fopen("file.txt", "w+");
fputc('A', file);
fflush(file);
char buff;
fscanf(file, "%s", &buff);
printf("read data: %s", &buff);
fclose(file);
return 0;
}
```
I want without close file read written data. But in buff not exist data... |
You should userewind(file)to set the position indicator associated with the file stream to the beginning of the file.
Your example, working fine:
```
#include <stdio.h>
int main() {
FILE* file = fopen("file.txt", "w+");
fputc('A', file);
fflush(file);
rewind (file);
char buff [80];
fscanf(file, "%s", bu... |
I am a newbie in Eclipse and STM32. So I would like to ask you for an advice with a problem which I have been solving. I have got a software for STM32. This software is written in C language and has an existing Makefile. The software is now placed on the SVN server. I need to build the project in Eclipse Neon 4.6.2 ID... |
sedis a unix utility. Maybe executed as a part of your makefile.
The error message is hidden by the second widnow. If it suggests, try to install it on your machine. I use GNU/Linux where it is essential part of the distribution. On Windows you can find a binary after some search.
|
I asked this onTaking an index out of const char* argumentalong with another question, but debate got only to the first question, so I splitted it to a different thread.
Question:
Is there any reason anyone would ever want to represent a C string asconst char*and not asconst unsigned char*?
On one hand, I see the c... |
Yes, of course a general read-only string should beconst char *, sincechar(with unspecified implementation-specified signedness) is the default type for a character.
In other words, a literal like"foo"consists ofchar, notunsigned char, elements.
Of course you can interpret the characters as unsigned if you feel like... |
I have to recode these 3 functions in C and the goal is that the recoded functions have to replace the system functions in different programs or system calls.
I don't really understand what is the behaviour of these functions since I've read the mans, I just know I'm allowed to usebrk()andsbrk().
|
mallocbasically pre allocates memory pages (Cfgetpagesize(2)), and returns pointer to usable parts of those pre allocated areas when called.mallocthen have to "remember" which part of those pre allocated memory segments are being used, and which one are free.
Reading this article:https://www.cocoawithlove.com/2010/05/... |
```
int main(){
char s[]="hi ";
char t[55];
fgets(t,55,stdin);
strcat(s,t);
puts(s);
}
```
I want to concatenate the stringssand the entered stringt, but I'm not getting any output. I have tried usinggetsto read thestringbut the compiler says "use of gets can be dangerous". What should I do?
|
strcat(s,t);is overrunning the destination memory buffers, as it is only large enough for 4 characters (and one of those is occupied by the NUL-terminator).
The behaviour of your program is thereforeundefined.
Make the size ofslarge enough to accommodate its initial contentsplusthe largest string possible int.
|
So I know that
```
struct bit
{
unsigned char a : 1;
}
```
will still take up a byte because of padding, my question is this:
```
struct bit
{
unsigned char a : 1;
...
unsigned char h : 1;
}
```
Will this struct take up the same size as a char? And if so, am I better off just using acharinstead? I'... |
There is no guarantees of anything when using bit-fields. That struct can have any size and any bit order. In factunsigned chartype for bit-fields is not even supported by the standard! Your code is already relying on non-standard extensions.
Forget about bit-fields, forget aboutchar. You should useuint8_tand bitwise... |
We are developing a software on Hi3536 processor based board. TheSDKprovided byHiSiliconcomes with samples for developing user interface using frame buffer API - which is too low level. i.e., to design Combo Box, Text box, we have to write code from Scratch.
We are now trying to use QT. Not sure what other vendors do... |
We referred the sample code given in the following link and we would bring up the GUI successfully in Hi3536 using QT 5.6 -http://bbs.ebaina.com/thread-8217-1-1.html.
Please note that you need to use Google translator to translate the text in chinese.
|
I am experiencing a problem with C language while I am trying to adapt a callback written in C to C++. Compiler shows the following error:
```
error C2664: 'fread' : cannot convert parameter 4 from 'void *' to 'FILE*'
1>Conversion from 'void*' to pointer to non-'void' requires an explicit cast
```
I found that thiss... |
```
fread(ptr, size, nmemb, static_cast<FILE*>(stream))
```
|
How to print the formatting characters such as:%pout? A backslash doesn't do any good as it does with quotations(""). I tried it in a simple toy program and I suppose the value returned by it was garbage :
What I was trying to print was the statement :
```
With the formatting character %p and '&'
```
|
Using double percentage i.e.%%will print single%for you:
```
printf("With the formatting character %%p and '&'\n");
```
|
If I usefork()to spawn a child process, then will the child process automatically terminate once the parent process terminates? Or must this be programmed?
|
This isn't really a c question, it's an O/S question.
In Windows, a process will continue until either it callsExitProcessor when it has performed enough CPU RETs that there's nothing left in the call stack.
In Unix, the process will continue and run as a subprocess ofinit.
On both O/S's, a user with enough permiss... |
I have a char array composed of hex values that looks similar to this:
```
char str[] =
"\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b"
"\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd"
"\x80\xe8\xdc\xff\xff\xff";
```
After manipulating this string, I want ... |
What you need is this:
```
for (size_t i = 0; i != sizeof str - 1; ++i)
fprintf(fp, "\\x%02x", (unsigned char)str[i]);
```
|
If I have this little C code (that I compile with:gcc -m32 -o code code.c):
```
int main(){
char tab[3];
tab[0]='a';
tab[1]='b';
tab[2]='c';
return 0;
}
```
How can I use GDB (or another program) to get a general overview of the stack like:
```
ADRESSES VALUES
0xbffff260 0x61
0xbffff261... |
To show the variables of the local stack try using the gdb command:
```
where
```
If you want the variables of each frame that exists in the program then try using:
```
where full
```
Then if you want to select a specific frame use:
```
frame <frame#>
```
EDIT:
Also, try compiling with -g flag.
```
gcc -g co... |
I'm facing a piece of code that I don't understand:
```
read(fileno(stdin),&i,1);
switch(i)
{
case '\n':
printf("\a");
break;
....
```
I know thatfilenoreturn the file descriptor associated with thesdtinhere, thenreadput this value inivariable.
So, what should be the value ofstdinto allowito mat... |
But what should be the value of stdin to match with the first "case", i.e \n ?
The case statement doesn't look at the "value" of stdin.
```
read(fileno(stdin),&i,1);
```
reads in a single byte intoi(assumingread()call is successful) and if that byte is\n(newline character) then it'll match the case. You probably ne... |
I am reading a excerpt from -Charles Petzold's book on C++ Windows
It states
The virtual key codes you use most often have names beginning with VK_
defined in the WINUSER.H header file.
I have looked inside the WINUSER.H file, and from what I have seen all Virtual Key codes begin win VK_.
If this is not the case... |
You misinterpreted the English grammar. The sentence in itself is ambiguous, but in a larger context it becomes clear.
The author wanted to say:
You usually use the virtual key codes, instead of the scan codes of the keys.The virtual key codes have names starting withVK_.The scan codes have names starting withSC_.
... |
I'm facing a piece of code that I don't understand:
```
read(fileno(stdin),&i,1);
switch(i)
{
case '\n':
printf("\a");
break;
....
```
I know thatfilenoreturn the file descriptor associated with thesdtinhere, thenreadput this value inivariable.
So, what should be the value ofstdinto allowito mat... |
But what should be the value of stdin to match with the first "case", i.e \n ?
The case statement doesn't look at the "value" of stdin.
```
read(fileno(stdin),&i,1);
```
reads in a single byte intoi(assumingread()call is successful) and if that byte is\n(newline character) then it'll match the case. You probably ne... |
I am reading a excerpt from -Charles Petzold's book on C++ Windows
It states
The virtual key codes you use most often have names beginning with VK_
defined in the WINUSER.H header file.
I have looked inside the WINUSER.H file, and from what I have seen all Virtual Key codes begin win VK_.
If this is not the case... |
You misinterpreted the English grammar. The sentence in itself is ambiguous, but in a larger context it becomes clear.
The author wanted to say:
You usually use the virtual key codes, instead of the scan codes of the keys.The virtual key codes have names starting withVK_.The scan codes have names starting withSC_.
... |
This question already has answers here:What is the rationale for one past the last element of an array object?(2 answers)Closed6 years ago.
The standard states:
Unless both pointers point to elements of the same array object or one past the last element of the array object, the behavior is undefined.
Why is it vali... |
It's okay to compute that pointer and compare to it only. The reason being that it can be used to pass and iterate over and array using a pair of pointers.
If it was not allowed by the standard, the following loop would have exhibited undefined behavior by the mere existence ofpend
```
int arr[100] = {0};
for (int ... |
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed6 years ago.
For this code
```
int j=2;
int c=(j++)*(j++);
printf("%d\n",c);
```
I get the value of c as 6
While for below code
```
int j=2;
int c=(++j)*(++j);
printf("%d\n",c);
```
I... |
You are simultaneously modifying the value of a variable, and using that variable in an expression. As such, your code is exhibitingundefined behavior. Undefined behavior is exactly that; anything can happen. There is no logical way to predict what values will result from the code you have written.
|
I have this code in C
```
int main(){
int t = 1;
while(t != 0)
t = t + 1;
return 0;
}
```
What would be the equivalent in Python?
In C, although it appears as such, it's not an infinite loop. Would it be similar in Python?
|
Python integers are not limited in constant number of bytes, only in your RAM limits. This loop would go forever, until your computer runs out of memory.
Usesys.getsizeof(int())andsys.getsizeof(int(2**128))to test this behaviour.
Anyway, the equivalent that terminates is
```
t = 1
while t < 2**32:
t += 1
```
... |
My application starts with different resolutions depending on whether I build it in Debug or Release configuration. This behavior is unwanted and unexpected.
Window is created this way:
```
screen->window = SDL_CreateWindow(WINDOW_TITLE, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screen->width, screen->height... |
The problem was that the application had "Disable display scaling on high DPI settings" option enabled in application properties. When I disabled it, the issue went away.
|
My task is going like this:
Write a recursive functionint calculate(node *root, int lvl, int defaultlvl)that will calculate the sum of all nodes at the default lvl and all progenys of those nodes.
I got in my task this information.
```
typedef struct node {
int value;
struct node *left, *right;
} node;
```
|
You will not get a answer for homework without showing some effort at trying to solve the problem...
Here is a simple function that sums the whole tree. Modify it to handle the level limitation is the assignment:
```
int calculate(node *root) {
if (root) {
return root->value + calculate(root->left) + cal... |
I want the program to print the wordhelloto the text file by means of strings.
```
#include <stdio.h>
void main ()
{
char word[10] = {"hello"};
FILE*fp;
fp = fopen("C:\\temp\\Dictionary.txt", "w+");
fprintf(fp, word[0]);
}
```
|
You're printing first char instead of the string. And it might not be a valid format either. Correct call will befprintf(fp, "%s", word). And don't forget to close file too.
|
I need to create a function that recursively adds up each digit in a large number.
For example, if the user inputs the number143, the function should return1+4+3which is8.
How can I do this?
|
The idea is that given a number, you can sum its digits by recursively summing the number without its last digit sum, and add the last digit. Calculating the last digit is simplex%10, and getting the number without the last digit isx/10. The base case when you hit 0 (you removed all digits) - return 0.
```
int sum_di... |
Could someone explain why I can move through the memory locations for the char * but not for the int * using the following code:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
int * a = malloc(48);
char * s = malloc(27);
for (int i = 0;i<26;i++) s[i] = i+65;
int intSize = sizeof(... |
when you declare a variable e.g.
```
int* a;
char* b;
```
all offsets are in the end calculated as byte offsets, the size of the offset depends on the type.
soa + 1is in realitya + sizeof(int)andb + 1is in realityb + sizeof(char)
the compiler handles this, it makes it easier to read the code otherwise you would al... |
I have to show an error when I access an item outside of an array (without creating my own function for it). So I just thought it was necessary to access the value out of the array to trigger a segfault but this code does not crash at all:
```
int main(){
int tab[4];
printf("%d", tab[7]);
}
```
Why I can't ... |
When you invokeundefined behavior, anything can happen. You program may crash, it may display strange results, or it may appear to work properly.
Also, making a seemingly unrelated change such as adding an unused local variable or a simple call toprintfcan change the way in which undefined behavior manifests itself.... |
I'm on a linux box and/proc/self/exedoes seem to be supported:
ls -l /proc/self/exeshows that it's linked to/usr/bin/lsat the moment I run the commandrealpath /proc/self/exeprints out/usr/bin/realpathas expectedboth commands exit with status0
But:
```
if (NULL == realpath("/proc/self/exe", NULL))
{
printf("this p... |
This behavior would occur onglibcversions below 2.3 as stated inman realpath:
ERRORS............EINVAL -pathisNULL. (In glibc versions before 2.3, this error is
also returned ifresolved_pathisNULL.)
|
I try to split any number of two digits and get result in two different variables. I had a problem with a specific number:23.
```
int root = 23;
float div = (float)root/10.0; // div = 23.0/10.0 = 2.3
int left = (int)div; // left = 2
int right = ((float)div - (float)left) * 10.0; // right = (2.3 - 2) * 10.0 = 0.3 * 1... |
Since 0.3 may not be represented exactly in binary, you end up with 2.9999… that became2when converted to anint.
Instead:
```
int root = 23;
int left = root / 10;
int right = root % 10;
```
|
Is it possible to multiply usingi**in C?
For example, I can incrementiusingi++. Why doesn'ti**work in C?
```
#include <stdio.h>
int main(void)
{
int result;
for (int i = 2; i < 100; i**){
result = i + 1;
printf("%i\n", result);
}
return 0;
}
```
|
No, it's not possible. There is no operator like**in C unlike unary increment (++) and decrement (--) operators. You should have tryi *= i.
|
In atom, when I write any code incorrectly I can view the errors immediately because the file is being scanned by a plugin.
I have the vs code plugin for c/c++ but I do not see this option to display errors. Is this available and I am just failing with my google skills? Or is this not an option with vs code?
|
The VSCode plugin for C++ doesnotsupport "intellisense" at the moment.
It supports debugging and some basic symbol parsing (with code completion) but it doesn't parse your code using a compiler.
For more info:https://code.visualstudio.com/docs/languages/cpp
|
Why is the following legal:
```
typedef struct a aType;
struct a
{
int x;
aType *b;
};
```
and the following illegal:
```
void main()
{
typedef struct a aType;
aType someVariable;
struct a
{
int x;
aType *b;
};
}
```
I'm just curious as in each case it is forward referencing a... |
You are allowed to create pointers to incomplete types, because the size of the pointer object does not depend on the size of the pointed-to type. Pointers to differentstructtypes have the same size and representation, regardless of the size of thestructtype itself.
You are not allowed to createinstancesof incomplet... |
Is it possible to multiply usingi**in C?
For example, I can incrementiusingi++. Why doesn'ti**work in C?
```
#include <stdio.h>
int main(void)
{
int result;
for (int i = 2; i < 100; i**){
result = i + 1;
printf("%i\n", result);
}
return 0;
}
```
|
No, it's not possible. There is no operator like**in C unlike unary increment (++) and decrement (--) operators. You should have tryi *= i.
|
In atom, when I write any code incorrectly I can view the errors immediately because the file is being scanned by a plugin.
I have the vs code plugin for c/c++ but I do not see this option to display errors. Is this available and I am just failing with my google skills? Or is this not an option with vs code?
|
The VSCode plugin for C++ doesnotsupport "intellisense" at the moment.
It supports debugging and some basic symbol parsing (with code completion) but it doesn't parse your code using a compiler.
For more info:https://code.visualstudio.com/docs/languages/cpp
|
Why is the following legal:
```
typedef struct a aType;
struct a
{
int x;
aType *b;
};
```
and the following illegal:
```
void main()
{
typedef struct a aType;
aType someVariable;
struct a
{
int x;
aType *b;
};
}
```
I'm just curious as in each case it is forward referencing a... |
You are allowed to create pointers to incomplete types, because the size of the pointer object does not depend on the size of the pointed-to type. Pointers to differentstructtypes have the same size and representation, regardless of the size of thestructtype itself.
You are not allowed to createinstancesof incomplet... |
I wrote a small program to check if my number is a prime number or not.
I think the code works fine, but I want the code to give me a single output: if it's a prime number or not.
I tried to find it on Google, but can't find an answer.
```
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main()
{
int... |
use a boolean value and set it totrue.
when you find a number that devides the input, put the value tofalseandbreakthe loop.
at the end test your boolean:true -> printf("Ja\n"); false -> printf("Nein\n");
|
In atom, when I write any code incorrectly I can view the errors immediately because the file is being scanned by a plugin.
I have the vs code plugin for c/c++ but I do not see this option to display errors. Is this available and I am just failing with my google skills? Or is this not an option with vs code?
|
The VSCode plugin for C++ doesnotsupport "intellisense" at the moment.
It supports debugging and some basic symbol parsing (with code completion) but it doesn't parse your code using a compiler.
For more info:https://code.visualstudio.com/docs/languages/cpp
|
Why is the following legal:
```
typedef struct a aType;
struct a
{
int x;
aType *b;
};
```
and the following illegal:
```
void main()
{
typedef struct a aType;
aType someVariable;
struct a
{
int x;
aType *b;
};
}
```
I'm just curious as in each case it is forward referencing a... |
You are allowed to create pointers to incomplete types, because the size of the pointer object does not depend on the size of the pointed-to type. Pointers to differentstructtypes have the same size and representation, regardless of the size of thestructtype itself.
You are not allowed to createinstancesof incomplet... |
I wrote a small program to check if my number is a prime number or not.
I think the code works fine, but I want the code to give me a single output: if it's a prime number or not.
I tried to find it on Google, but can't find an answer.
```
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main()
{
int... |
use a boolean value and set it totrue.
when you find a number that devides the input, put the value tofalseandbreakthe loop.
at the end test your boolean:true -> printf("Ja\n"); false -> printf("Nein\n");
|
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
I've got multiple float numbers to print:
```
{3.00, 3.20, 2.23, 5.00, 3.40 }
```
They ... |
There is no way todirectly(i.e. using only the format specifier) print either two decimals or zero for a number ending in e.g.3.20.
You need to check if the number ends with.00beforehand; for example:
```
if((int)round(num * 100) % 100 == 0) // if decimals are `.00`
printf("%.0f", num);
else // not `.00`
pri... |
```
for (minus == false ? i = 0 : i = 1; string[i] >= '0' && string[i] <= '9'; ++i)
{
intValue = string[i] - '0';
minus == false ? result = result * 10 + intValue :
result = result * 10 - intValue;
}
```
error: expression is not assignable
screenshot -http://share.pho.to/AarcJ... |
minus == false ? i = 0 : i = 1will be parsed as(minus == false ? i = 0 : i) = 1because of operator precedence rule. After evaluation ofminus == false ? i = 0 : i, left side of operator=will become an rvalue, but assignment operator must have an lvalue as its left operand.Change it tominus == false ? (i = 0) : (i = 1)
|
Let's say we have the following C code:
```
#include<stdio.h>
int main(){
char *a = "askakasd";
return 0;
}
```
I tried to find my local variable "a", but I don't know how to recognize it looking in this output, where p is the C code compiled:
|
It's not there. Since the code can't tell at execution time whether it's there or not, the linker removed it to save space.
|
How to convert char array to its equivalent ascii decimal array ? I tried in QT using QString and QbyteArray. But it is not working.
i/p: "1,9,10,2"
o/p: "4944574449484450" (1's ascii decimal value is 49,
, ascii decimal value is 44,
9's ascii decimal value... |
How to convert char array to its equivalent ascii decimal array ?
You do not, it is already stored that way. If you want to print your array as decimal numbers for ASCII just output it accordingly (as integers):
```
char str[] = "1,9,10,2";
for( const char *s = str; *s; ++s ) std::cout << static_cast<int>( *s ) << "... |
Probably really trivial question, but:
Recently started working an open-source system -janus-gatewayand i am in a need to run a method every 1 second(checking if all users muted).
What are the options to do this in C?
Should i spawn a new thread?
Answer with an example would much appreciated!
|
Ended up spawning a new thread and doing stuff that way.
|
Let's say we have the following C code:
```
#include<stdio.h>
int main(){
char *a = "askakasd";
return 0;
}
```
I tried to find my local variable "a", but I don't know how to recognize it looking in this output, where p is the C code compiled:
|
It's not there. Since the code can't tell at execution time whether it's there or not, the linker removed it to save space.
|
How to convert char array to its equivalent ascii decimal array ? I tried in QT using QString and QbyteArray. But it is not working.
i/p: "1,9,10,2"
o/p: "4944574449484450" (1's ascii decimal value is 49,
, ascii decimal value is 44,
9's ascii decimal value... |
How to convert char array to its equivalent ascii decimal array ?
You do not, it is already stored that way. If you want to print your array as decimal numbers for ASCII just output it accordingly (as integers):
```
char str[] = "1,9,10,2";
for( const char *s = str; *s; ++s ) std::cout << static_cast<int>( *s ) << "... |
Probably really trivial question, but:
Recently started working an open-source system -janus-gatewayand i am in a need to run a method every 1 second(checking if all users muted).
What are the options to do this in C?
Should i spawn a new thread?
Answer with an example would much appreciated!
|
Ended up spawning a new thread and doing stuff that way.
|
Probably really trivial question, but:
Recently started working an open-source system -janus-gatewayand i am in a need to run a method every 1 second(checking if all users muted).
What are the options to do this in C?
Should i spawn a new thread?
Answer with an example would much appreciated!
|
Ended up spawning a new thread and doing stuff that way.
|
What is wrong with this code?
I'm trying to compare string and white space.
```
void main()
{
char d;
int i;
char* mystring="Vikram Natarajan";
char c=mystring[0];
printf("%c\n",c);
for(i=0;i<100; i++)
{
if(mystring[i]==" ")
{
d=mystring[i+1];
}
}
... |
Replace
if(mystring[i]==" ")
With
if(mystring[i]==' ')
Use a single quote for char comparison.
|
char[i] stands for declaration of a variable both a char array and a string. I know that C adds a null character to the end of the array if it is a string. However, how does C know when to add the null character, in other words, in what stage?
|
it doesn't, C "strings" are just an assumption about arrays ( that they have a 0 somewhere indicating the end of the string)
There is no type "string" in C, just libraries which deal with char arrays with the above assumption. It is completely up to the library functions to manage the arrays and work out when to t... |
I would like to specify the name of a C include file at compile time as a C flag.
e.g.
```
#include MY_INCLUDE_FILE
int main(int argc, const char * argv[]) {...}
```
Would be expaned by the pre-processor to
```
#include "some_incfile.h"
int main(int argc, const char * argv[]) {...}
```
Doing something like this
... |
You have to escape the ":
```
gcc -DMY_INCLUDE_FILE=\"some_incfile.h\" main.c
```
|
In shell sort,3h+1sequence is recommended to h-sort a list using insertion sort
//1, 4, 13, 40, ...
Optimal formula to compute start value ofhis one-third oflistsize, as shown below,
```
int h = 1;
while(h < listSize/3){ // why N/3?
h = 3*h + 1
}
while(h >= 1){
//h-sort the array
// perform insertionSort
... |
If we continue to increasehafter condition(h < listSize/3),hbecomes larger thanlistSize, and there is no sense in h-sorting - we cannot compare itemsA[i]andA[i+h]because the second index is beyond list range.
|
I'm trying to figure out how theAttachedInterruptworks on the NodeMCU. Everything I found tells me that this code is OK?!
```
void setup() {
Serial.begin(9600);
pinMode(D4, INPUT);
attachInterrupt(D4, doSth(), CHANGE);
}
void loop() {
Serial.println(digitalRead(D4));
delay(100);
}
void doSth() {
Serial.... |
Problem solved — Thanks again!
I just usedattachInterrupt(D4, doSth, CHANGE);
instead ofattachInterrupt(D4, doSth(), CHANGE);
|
Is the behavior of writing a non-printing character undefined or implementation-defined, if the character is written viaprintf/fprintf? I am confused because the words in the C standard N1570/5.2.2 only talks about the display semantics for printing characters and alphabetic escape sequences.
In addition, what if the... |
The output of ASCII non-printable (control) characters is implementation defined.
Specifically, interpretation is the responsibility of the output device.
Edit 1:When the output device is opened as a file, it can be opened asbinary. When opened asbinarythe output is not translated (e.g. line endings).
|
This question already has answers here:How to find the size of an array (from a pointer pointing to the first element array)?(17 answers)Closed6 years ago.
Lets be the following code:
```
int x;
int *p = &x;
int t[3];
```
Then sizeof returns:
```
sizeof(x) -> 4
sizeof(p) -> 8
sizeof(t) -> 12
```
I suppose thatsiz... |
tis anint[3]type,nota pointer type.
So its size is3 * sizeof(int).
In certain instances,tdecaysto a pointer, but this is not one of those instances.
|
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
I want to use DB2 10.5 on Linux for XA transactions. Does DB2 include a XA transaction ma... |
DB2 LUW 10.5 supports XA transaction managers, but does not include one. If you want to work with one,programming in C is supported.
|
I am loging error messages using
```
#define LOG_INFO(...) do{ fprintf(fpLogFile, __VA_ARGS__ ); } while( FALSE )
#else
#define LOG_INFO(...) do{ } while ( FALSE )
```
and thefpLogFileis opened usingfopen.fopencreates0KBfile even if there are no errors.
If a0KBfile is created, a job is triggered. Hence I want to cr... |
SetfpLogFiletoNULL, and before eachfprintf, check if it is stillNULL. If so, open the file.
|
I'm trying to reverse unsigned int of 32 bit, want to turn zeros to ones, and ones to zeros, but seems there is something wrong.
input: 3
output: 4294967292
expected output: 2147483648
```
int main() {
unsigned int n;
scanf("%u",&n);
n^=4294967295;
printf("%u",n);
return 0;
}
```
|
Your expectation is wrong.
Let's do everything in hexadecimal:
```
0x00000003 ^ 0xffffffff = 0xfffffffc
```
The correct output in hexadecimal is therefore0xfffffffcwhich is4294967292in (unsigned) decimal.
Or in binary:
```
00000000000000000000000000000011 0x00000003
^ 11111111111111111111111111111111 0xffff... |
As far as I know there is no such thing as a layout in ncurses however I am wondering if there isn't a third party extension which allows that.
I'm looking for support for the typical layouts such as horizontal, vertical and grid. Of course being able to automatically resize the "children" of a layout is a plus.
|
no - the space available for characters is usually small enough that no one bothers with more than a few choices in fixed-layouts. Some applications resize, but use simple schemes for layout, e.g., all of the screen, half, etc.
|
I have to read a binary file in my webserver and send it to client via TCP. I decided to read it by chunks. How can I do it?
My code with fgets works only with text files (code, that checks return values is omitted):
```
char buf[2048];
fgets(buf, sizeof(buf), fp);
while (!feof(fp))
{
Server_TCP_Send(socket, bu... |
Usefread()instead offgets(), and pay attention to the return value:
```
char buf[2048];
size_t buflen;
while (1) {
buflen = fread(buf, 1, sizeof(buf), fp);
if (buflen < 1) {
if (!feof(fp)) {
// a read error occured...
}
break;
}
Server_TCP_Send(socket, buf, buflen... |
I have this:
```
typedef struct{
field_1;
field 2;
.....
}student;
typedef struct{
student record[100];
int counter;
}List;
```
Then I want to add the information for each 'student', for example:
```
List *p;
gets(p->list[index]->field_1);
```
but when I compiled the code it threw this:
```
[... |
Adding code snippet that may help you to read/write the values to the records.
Free the pointer to a struct when you're done.
```
typedef struct{
int age;
int marks;
}student;
typedef struct{
student record[100];
int counter;
}List;
int main()
{
List *p = (List*)malloc(sizeof(List));
p->record[0].age = ... |
I want to receive ethernet packets from socket in Linux, but only those, which have one of two custom Ethtype values.
As I know, if only 1 ethtype should be received, it's possible to specify this value while creating socket like this
```
int socket = socket(PF_PACKET, SOCK_RAW, htons(ETHERTYPE_CUSTOM_1);
```
But wh... |
Create two sockets, one for each ethertype. Then you can useselect()orepoll()to wait for packets on either socket at the same time.
|
I have this:
```
typedef struct{
field_1;
field 2;
.....
}student;
typedef struct{
student record[100];
int counter;
}List;
```
Then I want to add the information for each 'student', for example:
```
List *p;
gets(p->list[index]->field_1);
```
but when I compiled the code it threw this:
```
[... |
Adding code snippet that may help you to read/write the values to the records.
Free the pointer to a struct when you're done.
```
typedef struct{
int age;
int marks;
}student;
typedef struct{
student record[100];
int counter;
}List;
int main()
{
List *p = (List*)malloc(sizeof(List));
p->record[0].age = ... |
I want to receive ethernet packets from socket in Linux, but only those, which have one of two custom Ethtype values.
As I know, if only 1 ethtype should be received, it's possible to specify this value while creating socket like this
```
int socket = socket(PF_PACKET, SOCK_RAW, htons(ETHERTYPE_CUSTOM_1);
```
But wh... |
Create two sockets, one for each ethertype. Then you can useselect()orepoll()to wait for packets on either socket at the same time.
|
I'd like to measure the time that each thread spends doing a chunk of code. I'd like to see if my load balancing strategy equally divides chunks among workers.
Typically, my code looks like the following:
```
#pragma omp parallel for schedule(dynamic,chunk) private(i)
for(i=0;i<n;i++){
//loop code here
}
```
UPDATE
... |
You can just print the per-thread time this way (not tested, not even compiled):
```
#pragma omp parallel
{
double wtime = omp_get_wtime();
#pragma omp for schedule( dynamic, 1 ) nowait
for ( int i=0; i<n; i++ ) {
// whatever
}
wtime = omp_get_wtime() - wtime;
printf( "Time taken by th... |
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed6 years ago.Improve this question
When I clicked on so... |
Here is your answer :https://msdn.microsoft.com/en-us/library/ms173740.aspx
In short, just repair/reinstall it.
|
I was writing a program and had to handle buffers. But when I employed some loops I realized that the buffer was not being flushed after each iteration and withheld its last input value. I searched on the internet and found this code line. It works but I don't know what this means.fseek(stdin,0,SEEK_END);
|
It moves the read/write pointer to the end of the file/stream and so it needs to be flushed.
seeTutorialspoint
```
int fseek(FILE *stream, long int offset, int whence)
```
Parameters
stream− This is the pointer to a FILE object that identifies the stream.
offset− This is the number of bytes to offset from whence.... |
I have encountered this question while I was studying for a test. Given answers were:
a)'a'b)'\n'c)'012'd)'\0'
I tried to find the general rule but I failed.
|
Only'\n', of the listed 4, is certainly affected by writing to a file in a text mode instead of binary mode.
With atext file, thenew-line character'\n'is commonly translated to/from'\n'(no change),"\r\n", or rarely\r'.
'012'is a multi-character constant with an implementation defined value, unlikely to be affected b... |
I try to free structure pointer using function and then check for NULL. It doesn't work!
```
typedef struct{
int * num;
} D;
void freeD(D * a){
free(a->num);
free(a);
a=NULL;
}
int main(){
D * smth = malloc(sizeof(D));
smth->num = malloc(sizeof(int)*2);
freeD(smth);
if(smth==NULL){
... |
You have to pass the pointer by reference that is by using pointer to the pointer.
For example
```
void freeD(D ** a){
free( ( *a )->num);
free(*a);
*a=NULL;
}
//...
freeD( &smth );
```
|
!I had written this simple program on a different Ubuntu PC using Gedit]1
|
You do not have execute permissions for your executable.
Use
```
chmod +x ./secondo
```
first to correct this.
Thisquestion gives more detail.
|
!I had written this simple program on a different Ubuntu PC using Gedit]1
|
You do not have execute permissions for your executable.
Use
```
chmod +x ./secondo
```
first to correct this.
Thisquestion gives more detail.
|
I am reading data from a serial port (in an Arduino) and framing it (syncing on a few bytes). To do that, I am reading the data into a big buffer.
Once I got the frame, I extract data and I want to send it to a different serial port usingserial.write(Serial.write(buf, len)) which accepts a byte array and its size.
Si... |
Since the data size can be random, I need something like a dynamic array
In C you rarely need a dynamic array, because arrays passed to functions do not carry their size with them. That is why all functions that take an array also take length.
Let's say you have your data insidebigBufferat positionstartPos, and you ... |
How to define a variable using another variable.Actually I want a whole string but that string should contain data from another variable.
```
#include <stdio.h>
char *Data1 = "23";
char *Data2 = "267";
char *Data = ("www.mywebsite.com?c=%s&v=%s", Data1, Data2);
int main() {
printf(Data);
return 0;
}
```
|
You can define an array and make use ofsprintf()/snprintf()to generate the final string.
Something like
```
char final[128] = {0}; //128 is arbitrary value
int data1 = 23; //no need to be string for integer value
int data2 = 267;
snprintf(final, 128, "www.mywebsite.com?c=%d&v=%d", data1, data2);
```
That sai... |
Considering this code:
```
limit = sizeof(str1)-strlen(str1)-1;
strncat(str1,str2,limit);
```
Ifstr2length is greater thanlimit, doesstrncatNul terminatesstr1or I have to add this code, like in the case ofstrncpy?
```
str1[sizeof(str1)-1] = '\0'
```
|
It always null-terminate.
QuotingC11, chapter §7.24.3.2, (emphasis mine)
Thestrncatfunction appendsnot more thanncharacters(a null character and
characters that follow it are not appended) from the array pointed to bys2to the end of
the string pointed to bys1. The initial character ofs2overwrites the null charac... |
I'm usingtypedefto definesetas aboolarray:
```
typedef struct set{
bool Arr[128];
}set;
```
the problem is that every time I try to assign a t/f value, e.g.
```
temp[itemp]=true;
```
(tempis asetas defined anditempis anint),
I get the error:
```
subscripted value is neither array nor pointer nor vector
```
I ... |
what you've done is an alias calledsetto a struct containing an array of bools with the size of 128. This means, that to access the memberArr, you need to use the member access operator.like so:
```
temp.Arr[itemp] = true;
```
If you don't want to do that, you can typedef the array like so:
```
typedef bool set[128... |
I have a text file that contains Persian text like this:
یک
(U+06CC, U+06A9).
and I want to read this file into a string then store it in an output file.
I'm using this code:
```
char *locale = setlocale(LC_ALL, "en_US.UTF-8");
FILE *in = fopen("test.txt", "r");
FILE *out = fopen("out.txt", "w");
wint_t c;
while ... |
It's only a minor error; for wide characters you need:
```
fprintf(out, "%lc ", c);
-
```
or
```
fwprintf(out, L"%lc ", c);
- - -
```
Then, itworks for me. (Also the file gets space-separated characters.)
|
How can I make a check if there is a space inside the array string?
Could you help me? Thanks in advance ;)
```
for ( i = 0; string[i] != '\0'; ++i )
if ( string[i]) != ' ' )
```
error: expected expression
|
You can use standard functionstrchr(string, ' ')- return a non-NULL pointer ifstringhas space inside:
```
if(strchr(string, ' '))
{
// printf( "string contain space" );
}
```
Refer tostrchrfunction:
7.24.5.2 The strchr function
```
#include <string.h>
char *strchr(const char *s, int c);
```
3 The strchr ... |
I want to build a function which gets equation (string) likeax^2+bx+c=0(ex:"3x^2+8=0") and geta,b,cparameters.
Here is my code:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STR_LEN 25
void getABC(char str[]);
int a=0, b=0, c=0;
int main(void)
{
char equation[STR_LEN]={0};
printf... |
You can Do this instead
```
int a ;
int b ;
int c ;
printf("Enter Equation : ");
scanf("%dx^2+%dx+%d" , &a , &b , &c);
printf("%d %d %d" , a ,b , c);
```
For Example If you enter3x^2+4x+10, then3will be stored ina, it will ignorex^2and+and then store4inband then it will ignorexand+and store10inc.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.