question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
Is there a possibility to use the C90 compiler in Viual Studio 2015 (so new features are not available) ?
Background: In study we have to learn C using the C90 standard.
|
No, there is no such facility in VS to disable certain C99 features, these are inherent part of "C mode". The Update 3 introduced/stdswitch, but it is only suited for C++.
You could validate the code against C90 after writing it in VS. For instance, you could usegcc.godboltonline compiler passing following options:
```
-x c -std=c90 -pedantic -Wall
```
|
I saw this sample code in a previous question I asked. I was confused by how the paramaters ofint add(int a, int b)were automatically in esi and edi? Is this a default calling convention? Where can I find more of this information.
```
.globl _add // make it global so that others can find this symbol
....
_add: // int add(int a, int b)
movl %esi, %eax
addl %edi, %eax
ret
```
|
The calling convention of the System V AMD64 ABI is followed on Solaris, Linux, FreeBSD, OS X,[16] and is the de facto standard among Unix and Unix-like operating systems. The first six integer or pointer arguments are passed in registers RDI, RSI, RDX, RCX (R10 in the Linux kernel interface[17]:124), R8, and R9, while XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6 and XMM7 are used for certain floating point arguments.
Source:https://en.wikipedia.org/wiki/X86_calling_conventions
|
I'm trying to read the characters of a character array by number in c. I've stripped the program down to isolate the problem. I know this is about my misunderstanding of how arrays and memory works and I am ready to be called clueless but I would like to know what I am misunderstanding here. Here is what I have:
```
#include <stdio.h>
int main(int argc, char **argv) {
char buffer[] = "stuff";
printf("buffer is %s\n", buffer);
printf("first character of buffer is %s", (char)buffer[0]);
return 0;
}
```
|
You have to write the correct format specifier. Now you used%s...what happens?
It looks for an string which is null terminated. But it doesn't find one. So it simply cant put anything in the output . That's it.
Use%cinstead.
|
I useclang,gcc, andtcc, and I'd like to be able to differentiate between the three in a common header.
Judging by their macro dumps, I expect that the presence of the__clang__macro will uniquely identify clang.
I'm unable to get a macro dump withtcc($compiler -x c -E -dM /dev/nulldoesn't work in its case ).
What is the macro(s) (if any) that will uniquely identify gcc (and possibly tcc)?
|
Use __TINYC__ to detect tcc1.
Detection of gcc and clang is explained in this StackOverflow question:Detect gcc as opposed to msvc / clang with macro
1(Quoted from:http://bellard.org/tcc/tcc-doc.html#SEC9)__TINYC__ is a predefined macro to 1 to indicate that you use TCC.
|
This question already has answers here:Sizeof arrays and pointers(5 answers)Closed7 years ago.
```
#include<stdio.h>
#include<stdlib.h>
int main (int argc, char *argv[]) {
int* arr1 = (int*)malloc(sizeof(int)*4);
int arr2[4];
printf("%d \n", sizeof(arr1));
printf("%d \n", sizeof(arr2));
free(arr1);
return 0;
}
```
Output
```
8
16
```
Why?
|
Arrays are not pointers.
In your code,arr1is a pointer,arr2is an array.
Type ofarr1isint *, whereas,arr2is of typeint [4]. Sosizeofproduces different results. Your code is equivalent to
```
sizeof (int *);
sizeof (int [4]);
```
That said,sizeofyields the result of typesize_t, so you should be using%zuto print the result.
|
I want to create a socket connected directly to the gpu.
I would like to send data from a server to the gpu without spending a copy/moving time from host to device.
Is it possible?
|
If you have suitable network hardware and are willing to write your own device driver for your network adaptor, thenmaybe.SeveralInfiniband and iWARP adapter vendors can have engineered such support for their products.
But realistically, no.
|
I need to have a 3 byte unsigned integer type. When I look into clang's include path /usr/include/clang/3.5/include the stdint provides a uint24_t data type. But when I want to use it, clang compiler raise an error (error: unknown type name 'uint24_t';)!
```
#include "stdint.h"
int main()
{
uint24_t a = 12;
return 0;
}
```
Would you please help on how to compile and utilize 24 bit integers in clang?
|
You could always just mask a larger integer type with the right bit pattern to 24 bits if you need only 24 bits, something like this
```
int main(int argv, char** argc) {
uint32_t i = 42 & 0xFFFFFF;
return 0;
}
```
or you could use the Cunion typewith 24 bits you can only have 24 bits.
|
Say I am given avoid* dataarray, and asked to populate it with info of 2 different datatypes: an array of int's and a string.
```
void* data;
int numbers[9];
char* title;
```
I understand that to input the numbers into the data array, I need to typecast it like this:
```
memcpy((int*)data, numbers, sizeof(numbers));
```
But what do I do if I want to puttitlein the address after numbers gets copied into data?
Thanks in advance.
|
No, there's no need to type cast, sincememcpy()works withvoid *:
```
memcpy(data, numbers, sizeof numbers);
```
Also no need for()s withsizeofwhen applied to anything that is not a type name.
For the second part, you need to compute the address:
```
memcpy((char *) data + sizeof numbers, title, 1 + strlen(title));
```
Here I assume thattitleis a 0-terminated string. The cast ofdatatochar *is necessary since you can't do pointer arithmetic withvoid *.
|
I have one question.
What are "." and ".." directory?What are they doing?Why are they searched?I don't have . and .. directory in that folder which I wanted to search.
I wonder. tell me please ...Here, it's the findfile code:
```
GetWindowsDirectory(Path,MAX_PATH);
lstrcat(Path,"\\*.*");
hSrch=FindFirstFile(Path,&wfd);
if (hSrch==INVALID_HANDLE_VALUE) return;
while (bResult) {
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
wsprintf(fname,"[ %s ]",wfd.cFileName);
} else {
wsprintf(fname,"%s",wfd.cFileName);
}
SendMessage(hList,LB_ADDSTRING,0,(LPARAM)fname);
bResult=FindNextFile(hSrch,&wfd);
}
FindClose(hSrch);
```
|
I don't have.and..directory in that folder which I wanted to search.
You always have these intrinsic directories at any POSIX compliant file system.
.denotes the current working directory.
..denotes the parent directory.
|
I would like to have a genericon_connectioncallback that works with any type of server stream (pipe or tcp), but to accept the connection, you should provide an initialized client...
Howeveruv_stream_tis an abstract struct.
Is there an official way to do that ?
Else, can I do a switch relying on the private and undocumenteduv_hundle_t.typemember ?
Or should I use my own way of knowing the type using the.datapointer ?
|
You can use uv_handle_t.type, it's not "private". I just realized we haven't documented it, so I createdan issue.
|
Say I am given avoid* dataarray, and asked to populate it with info of 2 different datatypes: an array of int's and a string.
```
void* data;
int numbers[9];
char* title;
```
I understand that to input the numbers into the data array, I need to typecast it like this:
```
memcpy((int*)data, numbers, sizeof(numbers));
```
But what do I do if I want to puttitlein the address after numbers gets copied into data?
Thanks in advance.
|
No, there's no need to type cast, sincememcpy()works withvoid *:
```
memcpy(data, numbers, sizeof numbers);
```
Also no need for()s withsizeofwhen applied to anything that is not a type name.
For the second part, you need to compute the address:
```
memcpy((char *) data + sizeof numbers, title, 1 + strlen(title));
```
Here I assume thattitleis a 0-terminated string. The cast ofdatatochar *is necessary since you can't do pointer arithmetic withvoid *.
|
I have one question.
What are "." and ".." directory?What are they doing?Why are they searched?I don't have . and .. directory in that folder which I wanted to search.
I wonder. tell me please ...Here, it's the findfile code:
```
GetWindowsDirectory(Path,MAX_PATH);
lstrcat(Path,"\\*.*");
hSrch=FindFirstFile(Path,&wfd);
if (hSrch==INVALID_HANDLE_VALUE) return;
while (bResult) {
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
wsprintf(fname,"[ %s ]",wfd.cFileName);
} else {
wsprintf(fname,"%s",wfd.cFileName);
}
SendMessage(hList,LB_ADDSTRING,0,(LPARAM)fname);
bResult=FindNextFile(hSrch,&wfd);
}
FindClose(hSrch);
```
|
I don't have.and..directory in that folder which I wanted to search.
You always have these intrinsic directories at any POSIX compliant file system.
.denotes the current working directory.
..denotes the parent directory.
|
I would like to have a genericon_connectioncallback that works with any type of server stream (pipe or tcp), but to accept the connection, you should provide an initialized client...
Howeveruv_stream_tis an abstract struct.
Is there an official way to do that ?
Else, can I do a switch relying on the private and undocumenteduv_hundle_t.typemember ?
Or should I use my own way of knowing the type using the.datapointer ?
|
You can use uv_handle_t.type, it's not "private". I just realized we haven't documented it, so I createdan issue.
|
```
void random(int M,int a,int c,int *seq,int start,int size)
{
int i = start;
seq[0] = 1;
seq[i] = (a * seq[i - size] + c) % M;
i += size;
}
for(int iter = 0;iter < ceil((double)(n/size));iter++)
{
random(M,a,c,seq,1,1);
}
```
The loop compiled with-fopenmpandgccgives "invalid controlling predicate" error.
How to solve it?
|
There are no OpenMP constructs in the code shown, therefore compiling with or without-fopenmpshould not affect it. But if there was a[parallel] forconstruct, then it will fail as the type ofceil()isdoubleand OpenMP only allows integer types in loops.
You have to coerce the result fromceil()to an integer:
```
#pragma omp parallel for
for(int iter = 0; iter < (int)ceil((double)n/size); iter++)
{
random(M,a,c,seq,1,1);
}
```
|
I would like to have a genericon_connectioncallback that works with any type of server stream (pipe or tcp), but to accept the connection, you should provide an initialized client...
Howeveruv_stream_tis an abstract struct.
Is there an official way to do that ?
Else, can I do a switch relying on the private and undocumenteduv_hundle_t.typemember ?
Or should I use my own way of knowing the type using the.datapointer ?
|
You can use uv_handle_t.type, it's not "private". I just realized we haven't documented it, so I createdan issue.
|
```
void random(int M,int a,int c,int *seq,int start,int size)
{
int i = start;
seq[0] = 1;
seq[i] = (a * seq[i - size] + c) % M;
i += size;
}
for(int iter = 0;iter < ceil((double)(n/size));iter++)
{
random(M,a,c,seq,1,1);
}
```
The loop compiled with-fopenmpandgccgives "invalid controlling predicate" error.
How to solve it?
|
There are no OpenMP constructs in the code shown, therefore compiling with or without-fopenmpshould not affect it. But if there was a[parallel] forconstruct, then it will fail as the type ofceil()isdoubleand OpenMP only allows integer types in loops.
You have to coerce the result fromceil()to an integer:
```
#pragma omp parallel for
for(int iter = 0; iter < (int)ceil((double)n/size); iter++)
{
random(M,a,c,seq,1,1);
}
```
|
I'd like to check the system's C compiler in Python so that I can add library links accordingly to compile my Cython code.
I understanddistutils.ccompiler.get_default_compiler()or something likecompiler.compiler_typewould return a compiler name. But it is too coarse just like "unix", etc.
What I need is more specific information such as "gcc", "icc", "clang", etc., which are all shown as "unix" using the methods above.
One possible way to get the information is to check the system's environment variableCCviaos.environ["CC"], but it is not guaranteed that every system hasCCdefined so it is not a universal solution.
So, what should I do then? Thanks in advance!
|
Generally you should be able to use theplatformmodule to get the info:
```
>>> import platform
>>> platform.python_compiler()
'GCC 4.8.5 20150623 (Red Hat 4.8.5-4)'
```
|
I want to create an array of typedoubleand initialized it by0.0. I did the following:
```
double sum[3];
sum = {0.0};
for (int i = 0; i < 3; ++i) {
printf("%f ", sum[i]);
}
```
However, the compiler says it is wrongerror: expected expression! Why? and how to fix it?
|
You're not initializing, you'reassigningthe value. Moreover, you cannotassignanything to anarraytype, at all.
The LHS operand of an assignment operator should be a modifiable lvalue, and an array (array name) is not a modifiable lvaule. So you cannotassignanything to an array.
Try something like
```
double sum[3] = {0.0};
```
|
In this program I created a array(node[3]) of structure(struct eg) and made them as linked lists while trying to print the elements of the list I am getting only 1 output that is 3
```
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct eg
{
struct eg *next;
int age;
}node[3];
main()
{
struct eg *head,*temp;
int i;
head=temp=node;
for(i=1;i<3;i++)
{
temp->age=i;
temp->next=temp+i;
}
temp->next=0;
temp->age=3;
while(head!=0)
{
printf("%d",head->age);
head=head->next;
}
}
```
|
```
temp->next=temp++;
```
You're reading and modifyingtempin a single expression with no sequence point. This invokesundefined behavior.
You need to separate the increment from the assignment:
```
temp->next=temp+1;
temp++;
```
|
I have a dynamic array of integers:
```
int *array = malloc(1000 * sizeof(int));
for (int i = 0; i < 1000; ++i) {
array[i] = i;
}
```
How can I effectively delete elements between 555-565 without creating new array and copying elements there?
|
Could this be accounted as a deletion?
```
#include <stdio.h>
#include <malloc.h>
#include <string.h>
int main(void) {
int* array = malloc(sizeof(int)*110);
for(int i=0; i<100; i++)
array[i]=i;
for (int r=56; r<100; r++)
array[r]=array[r+6];
//memset(array+94, 0, 5);
memset(array+94, 0, 5 * sizeof(int));
}
```
|
I want to create an array of typedoubleand initialized it by0.0. I did the following:
```
double sum[3];
sum = {0.0};
for (int i = 0; i < 3; ++i) {
printf("%f ", sum[i]);
}
```
However, the compiler says it is wrongerror: expected expression! Why? and how to fix it?
|
You're not initializing, you'reassigningthe value. Moreover, you cannotassignanything to anarraytype, at all.
The LHS operand of an assignment operator should be a modifiable lvalue, and an array (array name) is not a modifiable lvaule. So you cannotassignanything to an array.
Try something like
```
double sum[3] = {0.0};
```
|
In this program I created a array(node[3]) of structure(struct eg) and made them as linked lists while trying to print the elements of the list I am getting only 1 output that is 3
```
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct eg
{
struct eg *next;
int age;
}node[3];
main()
{
struct eg *head,*temp;
int i;
head=temp=node;
for(i=1;i<3;i++)
{
temp->age=i;
temp->next=temp+i;
}
temp->next=0;
temp->age=3;
while(head!=0)
{
printf("%d",head->age);
head=head->next;
}
}
```
|
```
temp->next=temp++;
```
You're reading and modifyingtempin a single expression with no sequence point. This invokesundefined behavior.
You need to separate the increment from the assignment:
```
temp->next=temp+1;
temp++;
```
|
I have a dynamic array of integers:
```
int *array = malloc(1000 * sizeof(int));
for (int i = 0; i < 1000; ++i) {
array[i] = i;
}
```
How can I effectively delete elements between 555-565 without creating new array and copying elements there?
|
Could this be accounted as a deletion?
```
#include <stdio.h>
#include <malloc.h>
#include <string.h>
int main(void) {
int* array = malloc(sizeof(int)*110);
for(int i=0; i<100; i++)
array[i]=i;
for (int r=56; r<100; r++)
array[r]=array[r+6];
//memset(array+94, 0, 5);
memset(array+94, 0, 5 * sizeof(int));
}
```
|
to make my question precise i would like to create a macro that accepts as variable ++ and pastes it with another variable. In code:
```
#define MYMACRO(A, OP) /* .... */
```
and then if i write in the source file
```
MYMACRO(this->var, ++)
```
the preprocessor should paste in the code
```
this->var++;
```
When i am trying to define the macro as A##OP , it provides the following error:
pasting "++" and "var" does not give a valid preprocessing token
Is it possible to do what i am trying?
thanks in advance for the answer
|
You don't need the##token pasting operator, because you're not trying to combine the parameters into a single token. Just use:
```
#define MYMACRO(a, op) (a)op;
```
|
This question already has answers here:What is the origin of magic number 42, indispensable in coding? [closed](6 answers)Closed7 years ago.
Why do we use 42 as an argument of exit while exiting the process? I am wondering is it some macro value (like 1 is value of EXIT_FAILURE macro) or it has some deeper meaning?
```
if(pid == 0) {
printf("something\n");
exit(42);
}
```
It is kind of clear that it doesn't matter if I use exit(1) or exit(42), but why just 42?
|
Any number except for 0 would have done. But 42 is theAnswer to the Ultimate Question of Life, the Universe, and Everything.
Very popular among IT people...
But why did Douglas Adams pick 42?
I sat at my desk, stared into the garden and thought '42 will do'. I
typed it out. End of story
|
How can I stop the execution of a thread until a file is created ?I would like to avoid doing it in a busy loop, and use something with a behavior similar to select(). Is something like this possible?I only found ways to check if a file exists at a given time.
|
You are probably looking forinotify(7). At the botton of the man page linked, there's example showing how to monitor for various events.
|
I wish to define a C macro by passing it as an argument tomake, which is called from the command-line.
Background: I want the directive#define ENABLE_OPT 1to be included in my C source code when a certain build option is chosen. Thus, I want this to be done via themakecommand-line instead of modifying the source codeorthe makefile.
How can this be achieved? I find thatmake -DENABLE_OPT=1 -f Makefilethrows errors that 'E', 'N' etc. are invalid arguments to make.
|
You can use--eval, which will evaluate the string as a makefile statement:
```
make --eval="FLAGS+= -D ENABLE_OPT=1"
```
The make variable FLAGS is then used as a compiler argument to compile the code.
|
Is there any limit as to how many elements a2D integer arraycan contain inC?PS : I was expecting there would be some space limitations in declaring an array but could not find any such reference in the internet.
|
It depends on yourRAMor the memory available for you.
i:e:My program used to crash when I declared a global arraya[100000][10000], but this declaration is fine with the system now I have.
|
to make my question precise i would like to create a macro that accepts as variable ++ and pastes it with another variable. In code:
```
#define MYMACRO(A, OP) /* .... */
```
and then if i write in the source file
```
MYMACRO(this->var, ++)
```
the preprocessor should paste in the code
```
this->var++;
```
When i am trying to define the macro as A##OP , it provides the following error:
pasting "++" and "var" does not give a valid preprocessing token
Is it possible to do what i am trying?
thanks in advance for the answer
|
You don't need the##token pasting operator, because you're not trying to combine the parameters into a single token. Just use:
```
#define MYMACRO(a, op) (a)op;
```
|
This question already has answers here:What is the origin of magic number 42, indispensable in coding? [closed](6 answers)Closed7 years ago.
Why do we use 42 as an argument of exit while exiting the process? I am wondering is it some macro value (like 1 is value of EXIT_FAILURE macro) or it has some deeper meaning?
```
if(pid == 0) {
printf("something\n");
exit(42);
}
```
It is kind of clear that it doesn't matter if I use exit(1) or exit(42), but why just 42?
|
Any number except for 0 would have done. But 42 is theAnswer to the Ultimate Question of Life, the Universe, and Everything.
Very popular among IT people...
But why did Douglas Adams pick 42?
I sat at my desk, stared into the garden and thought '42 will do'. I
typed it out. End of story
|
How can I stop the execution of a thread until a file is created ?I would like to avoid doing it in a busy loop, and use something with a behavior similar to select(). Is something like this possible?I only found ways to check if a file exists at a given time.
|
You are probably looking forinotify(7). At the botton of the man page linked, there's example showing how to monitor for various events.
|
I wish to define a C macro by passing it as an argument tomake, which is called from the command-line.
Background: I want the directive#define ENABLE_OPT 1to be included in my C source code when a certain build option is chosen. Thus, I want this to be done via themakecommand-line instead of modifying the source codeorthe makefile.
How can this be achieved? I find thatmake -DENABLE_OPT=1 -f Makefilethrows errors that 'E', 'N' etc. are invalid arguments to make.
|
You can use--eval, which will evaluate the string as a makefile statement:
```
make --eval="FLAGS+= -D ENABLE_OPT=1"
```
The make variable FLAGS is then used as a compiler argument to compile the code.
|
Is there any limit as to how many elements a2D integer arraycan contain inC?PS : I was expecting there would be some space limitations in declaring an array but could not find any such reference in the internet.
|
It depends on yourRAMor the memory available for you.
i:e:My program used to crash when I declared a global arraya[100000][10000], but this declaration is fine with the system now I have.
|
In following program I usedunsignedkeyword.
```
#include <stdio.h>
int main()
{
unsigned char i = 'A';
unsigned j = 'B';
printf(" i = %c j = %c", i, j);
}
```
Output:
```
i = A j = B
```
Isunsigned char iequivalent tounsigned j?
|
Isunsigned char iequivalent tounsigned j?
No, when the type specifier is omitted and any of thesigned,unsigned,shortorlongspecifiers are used,intis assumed.
This means that the following declarations are equivalent:
```
long a;
long int a;
unsigned short b;
unsigned short int b;
```
The issue with the signedness ofcharis that whensignedorunsignedis omitted, the signedness is up to the implementation:
```
char x; // signedness depends on the implementation
unsigned char y; // definitely unsigned
signed char z; // definitely signed
```
|
I've been working on a piece of code that had an overlooked derp in it:
```
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
#define MAX_N_LENGTH
/*function prototypes*/
int main(){
...
}
```
It should be easy to spot with the context removed:#define MAX_N_LENGTHshould have read#define MAX_N_LENGTH 9. I have no idea where that trailing constant went.
Since that macro was only used in one place in the form ofchar buf[ MAX_N_LENGTH + 1], it was extremely difficult to track down and debug the program.
Is there a way to catch errors like this one using the gcc compiler?
|
You can usechar buf[1 + MAX_N_LENGTH], becausechar buf[1 +]should not compile with the error messageerror: expected expression before ']' token:
http://ideone.com/5m2LYw
|
Can someone explain me what king of specifier is in the below code? and give me an example.
printf("\r\x1b[32mConverting: \x1b[36m%d\x1b[0m",(Convert));
|
These ascii special codes are used to color debug messages.
\x1b[32m gives green color to "convering"
\x1b[36m%d gives cyan color to the Convert integer
and \x1b[0m%d finally resets the color values.
\r is carriage return
%d is nothing but the format specifier for integershttps://www.quora.com/What-does-d-mean-in-the-C-programming-language
|
IBM offer an installable MQSeries Client software that allows you to access queue managers on remote hosts. They also offer some C-callable libraries that let you do messaging from a C application.
My problem is that I don't have admin access on the hosts I plan to test-deploy on, and getting an application installed comes with bigtime Enterprise hassle. IBM, meanwhile, acts as if there's no alternative to installing their whole client package. Assuming I'm willing to forgo their support, can I get around this? i.e. is there some set of objects/libraries I can link with to produce a standalone client?
|
From v8.0.0.4 onwards, IBM provides set of libraries as a zip/tar and you don't need to install whole client package. See here:http://www.ibm.com/support/knowledgecenter/SSFKSJ_8.0.0/com.ibm.mq.ins.doc/q122882_.htm.
But you still need queue manager running somewhere to test your application.
|
I'm learning C basics and I'm trying to understand why the output of this example is1 2 1 1:
```
int main()
{
int a, b, c, d;
a = b = c = d = 1;
a = ++b > 1 || ++c > 1 && ++d > 1;
printf("%d%d%d%d", a, b, c, d);
}
```
As far as I understand, only the left operand before Logical OR||is getting evaluated because it is True and there is no need to evaluate the right one. The right operand is not evaluated. Is this right?The left operand is true because++b > 1equals1(2 is larger than 1) anda = 1. Right?
|
Yes, you are right on both accounts.
The important to note is that this behaviour is guaranteed by the C standard and is commonly known asshort circuting.
Relevant:Is short-circuiting logical operators mandated? And evaluation order?
|
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.Closed7 years ago.Improve this question
I declared a two dimensional array as row and col and I left the value empty, but when I check the value in each array position, some of the indexes contain some weird number.
|
You are looking at uninitilized memory. It can have whatever which value to it. You should never trust the value of a variable you haven't initialized.
|
I need read justone linewhich contains integers numbers delimited with whitespace
Input: 1 41 2 15 6 7 87 4 2 1 9 0
My code can read each number using
```
int number;
while(scanf("%d", &number) == 1) {
printf("%d", number);
}
```
The while-loop ends when I send some character, how I can I do to while-loop ends when user press enter?
What my program doesInput line 1:1 2 3 4 5 6--Here I press enterInput line 2:b-Send some bizarre character to finish
What I wantInput line 1:1 2 3 4 5 6--Here I press enter and finish
|
Your integers are normally separated by whitespace, except when you read the last one. In that case it is followed by a newline character:
```
char next_char;
int number;
while (scanf("%d%c", &number, &next_char) == 2) {
/* some stuff */
if (next_char == '\n') break;
}
```
|
I need read justone linewhich contains integers numbers delimited with whitespace
Input: 1 41 2 15 6 7 87 4 2 1 9 0
My code can read each number using
```
int number;
while(scanf("%d", &number) == 1) {
printf("%d", number);
}
```
The while-loop ends when I send some character, how I can I do to while-loop ends when user press enter?
What my program doesInput line 1:1 2 3 4 5 6--Here I press enterInput line 2:b-Send some bizarre character to finish
What I wantInput line 1:1 2 3 4 5 6--Here I press enter and finish
|
Your integers are normally separated by whitespace, except when you read the last one. In that case it is followed by a newline character:
```
char next_char;
int number;
while (scanf("%d%c", &number, &next_char) == 2) {
/* some stuff */
if (next_char == '\n') break;
}
```
|
I can't find help about this. Most issues i found are related to not closing the array with a '\0' , but this is not the case.
```
void main() {
char text[1000];
int index=0;
loadText(text,&index);
printf("\nThe text is:\n %s",text);
getch();
}
void loadText(char* text,int* index){
printf("Insert the text: \n");
while((*index<1000) && (text[*index]=getchar())!=EOF) {
*index++;
}
text[*index]='\0';
}
```
When i print the array it shows random chars.
On a side note, this is a test and we are forced to write the function as:
```
void loadText(char*, int*)
```
|
In
```
*index++;
```
doesn't increment the the value in the pointer. Instead it gets the value ie(*index)and then increment the pointer itself(index=index+1).
Do
```
(*index)++;
```
|
Consider the following code in C:
```
typedef struct {
union {
struct {
int x:16;
int y:16;
};
int combi_xy;
};
} T_MY_STRUCT;
```
Now with GDB I want to look at the setup of this struct. I do so with ptype:
```
(gdb) ptype T_MY_STRUCT
type = struct {
union {
struct {...};
int combi_xy;
};
}
```
But that result is not very satisfying for me, since all the content of the inner struct (x and y) has been hidden/replaced with {...}. Is it in anyway possible to see the contents of the inner struct? Is there some option to set the nesting depth for ptype? Or even an option to just expand the whole structure, no matter the the amount of nested structures?
As a note I would be good if I could just expand a nesting level equal to the one in the example.
|
You can use Python and gdb.lookup_type(), gdb.Type.fields() etc.
|
I have code that I want to have two modes,debugandverbose. I define them in my header file as,
```
#define verbose TRUE
#define debug TRUE
```
In my code so far, I have just been using
```
#if(debug)
//code
#endif
```
but is it more proper to use?
```
#ifdef debug
// code
#endif
```
I read something about preprocessor macros but it didn't make sense at the time. So, I have a question: Is#if defined MACROequivalent to#ifdef MACRO? and which one is better for enabling/disabling a particular section of code?
|
```
#ifdef MACRO
#if defined (MACRO)
```
will do the exact same thing. However, the defined (MACRO) is just an expression that evaluates to 0 or 1 inside the #if, and it can be combined with other expressions. For example
```
#if defined (MACRO) && ! defined (MACRO2)
// Do this
#else
// Do that
#endif
```
Try doing that with #ifdef - you can't unless your code gets really clumsy.
|
I came across this line of code written in C that confuses me coming from a JavaScript background.
```
short s;
if ((s = data[q]))
return s;
```
Is this assigningstodata[q], and if it equals true/1, return s?
|
Yes, an assignment...well assigns...but it's also an expression. Any value not equalling zero will be evaluated as true and zero as false.
it would be the same as
```
if ((s = data[q]) != 0) return s;
```
|
This is the code:
```
char binarySearch(unsigned int target, int* primes, unsigned int size){
int* ptrToArray = primes;
unsigned int first = 0;
unsigned int last = size;
while (first <= last){
unsigned int middle = first + (last - first) / 2;
printf("first: %d, last: %d, middle: %d\n", first, last , middle);
if (ptrToArray[middle] == target){
return 1;
}
if (ptrToArray[middle] < target){
first = middle + 1;
}else{
last = middle - 1;
}
}
return 0;
}
```
This is the output:
I've been staring at that peace of code for more than one should and still can't figure out where is the flaw.
|
Ifmiddleis0, as near the end of your debug output, the statement
```
last = middle - 1
```
causes an integer overflow; the conditions have to be reworked a bit.
|
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.Closed7 years ago.Improve this question
I know that endianess little or big is inherent to the system. Then, how is it possible to change using c code, as I have seen a code, which says it can change the endianess.
|
Endianess depends on the CPU hardware. So normally you can't do anything about it.
The code you have seen was most likely just tossing bytes around from one endianess to the other. Though some CPUs (for example some PowerPC) do have the possibility to configure endianess by writes to a hardware register.
|
This question is really arbitrary so I'll try to explain it as best as I can. I'm looping through two strings of unknown size.
```
bool check(char *str1, char *str2)
{
char special = 'k';
for (int size_t i = 0; ; i++)
{
}
}
```
I want the terminating condition of the for loop to be the following:
Leave the loop only if either str1[i] == special OR str2[i] == special,but not both.
For this question, ignore the fact that I might segment fault since I know neither the size nor am I checking for0x00.
I know how to write this but it's always really messy and involves using ternary conditional operators. What is a better way to write it?
|
You could use(str1[i] == special) != (str2[i] == special), as suggestedhere.
This works because inc,==can only return one of theintvalues0or1(reference).
|
I have a hard time formulating this question. The reason I'm asking is that I want to convert some C++ code with emscripten to java script code, but I don't think I need to convert the whole code base.
Is it possible in C++ to find all the code that a particular function could reach into when executed? Then I would know which part of the code I need to convert and which one I can just ignore.
|
It is called "call hierarchy" as Eugene said. You can use automatic documentation tools to get this information.
I strongly recommend you to try doxygen because it is really easy to use:http://www.doxygen.nl/
|
TheLinux kernel's list.hprovides a number of macros for iterating over a its own linked list implementation. For example:
```
/**
* list_for_each - iterate over a list
* @pos: the &struct list_head to use as a loop cursor.
* @head: the head for your list.
*/
#define list_for_each(pos, head) \
for (pos = (head)->next; pos != (head); pos = pos->next)
```
What is the name of theposparameter attempting to abbreviate? (What doesposstand for / mean?)
|
It means "position", as in the current position in the list.
|
Trying to compile gcc on an armhf embedded device but it halts when trying to compile libgcc with xgcc saying it can't find sys/cdefs.h
libc6 and libc6-dev are already installed and cdefs.h can be found at /usr/arm-linux-gnueabihf/sys/
how do i add /usr/arm-linux-gnueabihf to the xgcc include path?
|
Needed to add--with-float=hardto the configure line.
This is because MULTIARCH_DIRNAME is defined based on the with-float configuration option
MULTIARCH_DIRNAME = $(call if_multiarch,arm$(ARM_EB)-linux-gnueabi$(if $(filter hard,$(with_float)),hf))
As pointed out by the kind fellows atgcc
|
i want to implementlayer_get_unobstructed_bounds()but it doesn't work for me.When i run the app it prints every second-50and QuickView doesn't change that. What am i doing wrong?
In conclusion:layer_get_unobstructed_bounds()doesn't change at all.
Here is my code:https://github.com/WuerfelDev/LIFT/tree/testTheprintfis at line 33Thank you!
|
My fault was that i usedorigin.yinsteadsize.h.I thought it would return the QuickViews bounds, but instead it actually represents the bounds of the part of the screenwhere the QuickView is not shown.
Big thanks to @PebbleDev on twitter:
https://twitter.com/PebbleDev/status/771372057590390784
|
I have a hard time formulating this question. The reason I'm asking is that I want to convert some C++ code with emscripten to java script code, but I don't think I need to convert the whole code base.
Is it possible in C++ to find all the code that a particular function could reach into when executed? Then I would know which part of the code I need to convert and which one I can just ignore.
|
It is called "call hierarchy" as Eugene said. You can use automatic documentation tools to get this information.
I strongly recommend you to try doxygen because it is really easy to use:http://www.doxygen.nl/
|
TheLinux kernel's list.hprovides a number of macros for iterating over a its own linked list implementation. For example:
```
/**
* list_for_each - iterate over a list
* @pos: the &struct list_head to use as a loop cursor.
* @head: the head for your list.
*/
#define list_for_each(pos, head) \
for (pos = (head)->next; pos != (head); pos = pos->next)
```
What is the name of theposparameter attempting to abbreviate? (What doesposstand for / mean?)
|
It means "position", as in the current position in the list.
|
Trying to compile gcc on an armhf embedded device but it halts when trying to compile libgcc with xgcc saying it can't find sys/cdefs.h
libc6 and libc6-dev are already installed and cdefs.h can be found at /usr/arm-linux-gnueabihf/sys/
how do i add /usr/arm-linux-gnueabihf to the xgcc include path?
|
Needed to add--with-float=hardto the configure line.
This is because MULTIARCH_DIRNAME is defined based on the with-float configuration option
MULTIARCH_DIRNAME = $(call if_multiarch,arm$(ARM_EB)-linux-gnueabi$(if $(filter hard,$(with_float)),hf))
As pointed out by the kind fellows atgcc
|
i want to implementlayer_get_unobstructed_bounds()but it doesn't work for me.When i run the app it prints every second-50and QuickView doesn't change that. What am i doing wrong?
In conclusion:layer_get_unobstructed_bounds()doesn't change at all.
Here is my code:https://github.com/WuerfelDev/LIFT/tree/testTheprintfis at line 33Thank you!
|
My fault was that i usedorigin.yinsteadsize.h.I thought it would return the QuickViews bounds, but instead it actually represents the bounds of the part of the screenwhere the QuickView is not shown.
Big thanks to @PebbleDev on twitter:
https://twitter.com/PebbleDev/status/771372057590390784
|
I know how to get the stdout into a file using dup/dup2 system calls, but how do I get the entire output that would be normally shown on my terminal(including the prompt that says my username along with the$symbol and the current working directory) to a file?
|
Yes you can, but this may be difficult in many details (depending on your expert level). For the shell to behavenormally(I would mean exactly as in a terminal), then it needs to interact with a terminal (special system object). So you need to create a program that behave like a terminal, this what pseudo-terminals devices (/dev) are intended for. Read documentation about this to implement it but roughly, your application should behave like the user so should be connected to the slave side of the pseudo-terminal, and the shell to the master side of the pseudo-terminal. Then you can easily log real inputs made by the user and catch outputs made by the shell.
|
I am not sure if that is feasible, but I need to cast a function pointer to long in order to map C level code back to java code.
|
A pointer's value is an integer, you just need to know what exactly you are doing, and allocate enough storage to store the pointer's value. (In a 32bit OS, a pointer occupies 32bit storage, in a 64bit OS, pointer occupies 64bit storage).
A C example:
```
#include <stdio.h>
void fun()
{
printf("fun\n");
return;
}
typedef void (*fun_type)();
int main()
{
long long int a = (long long int)fun;
fun_type func_point = (fun_type)a;
func_point();
return 0;
}
```
|
I have some C code being called from C++.The header resembles the following:
```
#ifndef CLibH
#define CLibH
#ifdef __cplusplus
extern "C" {
#endif
//C API
void foo(void);
// ...
#ifdef __cplusplus
}
#endif
#endif
```
Since I'm already usingextern C,is there any benefit to adding thenothrowcompiler attribute?
```
#ifndef CLibH
#define CLibH
#ifdef __cplusplus
extern "C" {
#endif
//C API
void foo(void) __attribute__((nothrow));
// ...
#ifdef __cplusplus
}
#endif
#endif
```
Doesextern Cmake this redundant?Are there still advantages to applying it under these circumstances?
|
Yes, it does. From gcc documentation:
For example, most functions in the standard C library can be
guaranteed not to throw an exception with the notable exceptions of
qsort and bsearch that take function pointer arguments.
|
This question already has answers here:How do function pointers in C work?(12 answers)Closed7 years ago.
I came across the following code:
```
int H3I_hook(int (*progress_fn)(int*), int *id)
{
...
}
```
I don't understand the purpose of(int*)at the end of the first argument?
|
Demystifying:
```
int (*progress_fn)(int*)
```
it can be interpreted like below:
```
int (*progress_fn)(int*)
^ ^ ^
| | |___________ pointer to integer as argument
| |
| pointer to any function that has V and takes ^
|
|__________________________return type an integer
```
|
I am learning C and came acrossccin the bash shell i.e. whenever Imakemy source files I see this command.
Hence started to understand it,started withgcc --helpbut couldn't findccoption in the help. So started surfing the net, and came across thispost. In the second answer it saysccis an environment variable and often points to/usr/bin/gccon Linux systems.
I am using Linux distro and when I print return value fromgetenv("cc"), I am gettingNULL. Why is this happening?
|
ccis usually not an environment variable. There is commonly a symbolic link/usr/bin/ccwhich points atgcc.
|
As far as I know, standard allows redefinition only if the new definition duplicates the old one. So for example,
If,
```
#define X 100
```
Then,
```
#define X 200 // Not allowed
#define X 100 // Allowed
```
But what confuses me is when the header file includes redefintion which doesn't duplicate the old defintion. For example,
There is a header file,header.hsuch that
```
#ifndef X
#define X 100
#endif
```
and source codemain.csuch that
```
#define X 10
#include "header.h"
```
Since#define X 100is below#define X 10in themainfile, I thought this would occur error. But surprisingly, the compiler does not complain! Why is such behaviour allowed in C?
|
Of course it doesn't, because#define X 100is never reached.
Think about this, what does#ifndefdo?
Put the#define X 10below the#include, what happens now?
|
I am looking at this code passed onto me to resolve an issue but I have trouble understanding one of the function's definition.
void DESC_API ApplDesc(DescMsg* pMsg)
I can see that the function isnt returning anything so thevoidholds good. But what is theDESC_APIdoing in here? This is how it is defined in the header file
```
#if defined(DESC_API)
#else
/* No paging used. */
#define DESC_API
#endif
```
|
Looks likeDESC_APIa is visibility macro. It might be defined to__declspec(dllexport)or to__declspec(dllimport)for MSVC or to__attribute__ ((visibility ("default")))for gcc or clang.
Of course, it might be defined to something else (as said bellow), but the most popular use case is just symbols visibility attributes.
Since gcc and clang export all symbols by default, no attributes is needed andDESC_APIis blank. As for MSVC, your build system might set it via/DDESC_API=__declspec(dllimport)externally.
|
The size of a C union(sizeof()) is the size of its largest element.
However, is there any trick to find out what might be the smallest size of the union programmably?
I meant something along the line of how offsetof MACRO is implemented...
|
I see 2 ways to answer this question:
Each union has only one size, so that would be the smallest size of it as well.If what youreallywanted was the smallest size of the elements that make up the union, then compute the size of each element in isolation and take the minimum of those.
|
Hi I just started C as my first programming language.
I was playing around a bit withscanf()and found something strange.
```
#include <stdio.h>
#include <Windows.h>
int main()
{
int x;
printf( " Type any number : " );
scanf( "%d", &x );
printf( "You entered %d.\n", &x );
system("pause");
return 0;
}
```
It always shows me a result of 7 or 8 digit number.
How is it possible?
|
Youprintfx's address instead of value. Fix like this:
```
printf("You entered %d.\n", x);
```
scanfwants the address where to store the result,printfcan take the value itself.
|
SpecificallyContent-Length. When i send the HEAD request to my local server, i don't always receive the size of the requested file.For example, when it's 159 bytes index.php:
```
HTTP/1.1 200 OK
Date: Wed, 31 Aug 2016 11:34:16 GMT
Server: Apache/2.4.17 (Win32) OpenSSL/1.0.2d PHP/5.6.20
X-Powered-By: PHP/5.6.20
Content-Type: text/html; charset=UTF-8
```
And 40-something MB random .pdf file:
```
HTTP/1.1 200 OK
Date: Wed, 31 Aug 2016 11:34:23 GMT
Server: Apache/2.4.17 (Win32) OpenSSL/1.0.2d PHP/5.6.20
Last-Modified: Thu, 25 Aug 2016 11:19:59 GMT
ETag: "2807fb2-53ae39413d130"
Accept-Ranges: bytes
Content-Length: 41975730
Content-Type: application/pdf
```
Can i force it or not?
|
No, you can't. Either the size is available – or it is not.
Especially, in the case of php scripts, the content is generated dynamically, and the size is not known beforehand.
Essentially,HEADdoes the same asGET, but omits the payload.
|
I have a problem with arguments in thesystem()call in C.
Code:
```
char macaddr[13];
uint8_t mac[6];
memset(macaddr, '\0', 13);
mac_get_ascii_from_file("/sys/class/net/eth0/address", macaddr);
system("rm /var/tuxbox/config/cxx.bin");
system("wget -P /var/tuxbox/config http://xxxxxxx/xx/cxx_%s.bin\n", macaddr);
```
Error message:
too many arguments to function 'system'
|
system()doesn't handleprintfstyle arguments. You need to build the command string up first and then pass it to system.
e.g.
```
char cmd[512];
sprintf(cmd, "wget -P /var/tuxbox/config http://xxxxxxx/xx/cxx_%s.bin\n", macaddr);
// or snprintf(cmd, sizeof(cmd), "wget...
system(cmd);
```
(note, no error handling etc included.)
|
I have a problem with arguments in thesystem()call in C.
Code:
```
char macaddr[13];
uint8_t mac[6];
memset(macaddr, '\0', 13);
mac_get_ascii_from_file("/sys/class/net/eth0/address", macaddr);
system("rm /var/tuxbox/config/cxx.bin");
system("wget -P /var/tuxbox/config http://xxxxxxx/xx/cxx_%s.bin\n", macaddr);
```
Error message:
too many arguments to function 'system'
|
system()doesn't handleprintfstyle arguments. You need to build the command string up first and then pass it to system.
e.g.
```
char cmd[512];
sprintf(cmd, "wget -P /var/tuxbox/config http://xxxxxxx/xx/cxx_%s.bin\n", macaddr);
// or snprintf(cmd, sizeof(cmd), "wget...
system(cmd);
```
(note, no error handling etc included.)
|
This question already has answers here:C best practices, stack vs heap allocation(4 answers)Closed7 years ago.
I have a struct like this:
```
typedef struct {
int hi;
} my_struct;
```
Is there an advantage in using this:
```
my_struct *test = malloc(sizeof(my_struct));
test->hi = 1;
```
Instead of this:
```
my_struct test;
test.hi = 1;
```
|
No, usually it's quite the opposite. If youcanuse the format to satisfy your requrement
```
my_struct test;
test.hi = 1;
```
then it's always better, less overhead in runtime. There's no advantage in general of using memory allocator functions, when you can do without them.
|
I had aboutaccess linksfrom wikipedia but I could not get a clear picture of what access links are and how they are different from return address of any function. Can someone explain in brief what an access link is and why its necessary on a call stack ?
|
You would actually meet such paradigm inPascalorJava, for example, not inC.
For example, in Java, you could declare:
```
void func1() {
int outer = 2;
int func2() {
int inner = 3;
return inner+outer;
}
int result = func2();
}
```
At the end offunc1execution, theresultvariable would contain 5 that is a sum of locally defined variablesouterandinner.
Theaccess linkserves exactly this purpose - to pass the 'pointer' to the actual outer scope into the inner function.
Thegcccompiler hasNested Functions extensionthat is not a part of theCstandard as n.m mentioned
|
Working in little endian, which is excatly (including eof if there is) the bit representation of a C vector like this?
```
unsigned char vet[] = {0x0f, 0x05};
```
|
Bit representation of a vector ofunsigned chars is not dependent on endianness, becausechartypes are single-byte, while endianness tells you how multiple bytes are arranged in memory.
Therefore,0x0fwould be found at an earlier address in memory than0x05, producing
```
0000111100000101
```
including eof if there is [one]
Unlike C strings and arrays initialized with C strings, arrays initialized with curly brace initializers do not have an end mark.
|
I'm a begginer and have been reading books on C, I have a question about pointers of structures.
Below I tried to initialize members of the structure using a "*p" pointer
```
#include <stdio.h>
struct part{
int num;
char *name;
};
int main()
{
struct part *p; //creating a pointer with 'struct part' type
p->num= 5; //initializing
p->name= "Jose";
printf("%d\n",p->num);
printf("%s",p->name);
return 0;
}
```
Probably a dumb question but I'm interest to know why is it wrong? The program is crashing obviously.
|
You declared a pointer but it doesnt point to anything.
You'd have to do e.g.p = malloc(sizeof(struct part))or maybestruct part q; p = &q;or otherwise set it to point to something first.
Check out the C version ofthis old classic.
|
Is there a way of compiling C/C++ with Visual Studio 2015 without using any runtime library?
I need to compile without a runtime library because I'm creating my own runtime library (for my OS).
There are options on C/C++->Code Generation->Runtime Librarybut I want an option that says "none".
I'm aware of loosing a lot of features that are in the CRT.
|
To compile your app without C-Runtime Library (CRT) use/MT,/NODEFAULTLIBlinker options and redefine entry point atLinker -> Advanced -> Entry Pointto function defined in your code, e.g.rawMain. The signature is:
```
DWORD CALLBACK rawMain();
```
Without C-runtime library you are not allowed to use it's functions, likemalloc,free,memset, etc. You should implement all the used CRT functions by yourself. E.g. you can replace usage ofmallocbyVirtualAlloc()andfreebyVirtualFree().
To check that C-runtime is not linked to your application useDependency Walker.
|
I am taking in a string from the stdinput via readline() a la:
```
char * cmdLine = readline();
```
Then I want to see if the first character of the string produced via readline() is an exclamation point. But the code
```
if(cmdLine[0]=="!")
```
doesn't do that for me like I would have thought. I thought that if the string snagged from stdin was "!1" for instance then it would be true that
```
cmdLine[0]=="!"
```
If cmdLine is a pointer to a string then can't I look at each character in the string with array brackets? I know this is a stupid basic c / pointer question but this is really tripping me up...
|
Change"!"to'!'. You are comparing a single char to another single char.
In C you specify a char with single quotes
|
I need anextern "C"FFI function in Rust and want to accept an array of fixed size. The C code passes something like:
```
// C code
extern int(*)[4] call_rust_funct(unsigned char (*)[3]);
....
unsigned char a[] = { 11, 255, 212 };
int(*p)[4] = call_rust_funct(&a);
```
How do I write my Rust function for it ?
```
// Pseudo code - DOESN'T COMPILE
pub unsafe extern "C" fn call_rust_funct(_p: *mut u8[3]) -> *mut i32[4] {
Box::into_raw(Box::new([99i32; 4]))
}
```
|
You need to use Rust's syntax for fixed size arrays:
```
pub unsafe extern "C" fn call_rust_funct(_p: *mut [u8; 3]) -> *mut [i32; 4] {
Box::into_raw(Box::new([99i32; 4]))
}
```
You can also always use*mut std::os::raw::c_voidand transmute it to the correct type.
|
This question already has answers here:Handling command line flags in C/C++(7 answers)Closed7 years ago.
In command line argument like./a.out echo *the*will be changed by the terminal so that all the files in the directory can be printed. What I want is that standard input do the same thing.
Is there any way of doing this in C++? Any help will be thanked.
|
Please have a look athttp://en.cppreference.com/w/cpp/language/main_function
you could write:
```
int main(int argc, char** argv)
{
for(int i=0; i<argc; i++)
printf("Element %d : '%s'\n", i, argv[i]);
return 0;
}
```
Note: If you want to do this steps in C please have a look hereSimple glob in C++ on unix system?
|
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.Closed7 years ago.Improve this question
I am trying to code a project which will track on heap area of c program, something like in memory profiler, on windows os, using dev cpp compiler,
what would be the steps for it?
thanks.
|
You should take a look at MemProf or massif.
|
So I want to allocate memory for a struct but I am new to C and have no clue on how to allocate it. The struct of have consists of 2 ints, 1 char, 1 bool(could be changed to int), and 2 doubles. I am to read or input a file and store the information from that file into the struct but the amount of information from the file may change. So what would be the best way to create the necessary space for it?
|
Usemallocandsizeof.
```
#include <stdlib.h>
...
struct your_struct *s = malloc(sizeof(*s));
```
|
I made my code as a standalone .c file and read that, in order to debug, the file must be in a project. So I made an empty project and added my file to it, set some breakpoints and, when i run the debugger, I get this on console:
```
Setting breakpoints
Debugger name and version: GNU gdb (GDB) 7.6.1
Child process PID: 13112
Error in re-setting breakpoint 2: PC register is not available
Error in re-setting breakpoint -3: PC register is not available
In ()
```
Tried some tutorials and whatched some videos without success. Does somebody knows a fix for that? Is there a simpler way to debug a .c file?
|
For linux system you could use gdb as debugger in this way:
```
$ vim hello.c
# include <stdio.h>
int main()
{
printf("hello \n");
}
$ gcc -o hello hello.c
$ ./hello
$ gdb hello
(gdb) break main
(gdb) run
```
and then you can use:
c or continue
n or next
s or step
For more details seethis.
|
So I want to allocate memory for a struct but I am new to C and have no clue on how to allocate it. The struct of have consists of 2 ints, 1 char, 1 bool(could be changed to int), and 2 doubles. I am to read or input a file and store the information from that file into the struct but the amount of information from the file may change. So what would be the best way to create the necessary space for it?
|
Usemallocandsizeof.
```
#include <stdlib.h>
...
struct your_struct *s = malloc(sizeof(*s));
```
|
I made my code as a standalone .c file and read that, in order to debug, the file must be in a project. So I made an empty project and added my file to it, set some breakpoints and, when i run the debugger, I get this on console:
```
Setting breakpoints
Debugger name and version: GNU gdb (GDB) 7.6.1
Child process PID: 13112
Error in re-setting breakpoint 2: PC register is not available
Error in re-setting breakpoint -3: PC register is not available
In ()
```
Tried some tutorials and whatched some videos without success. Does somebody knows a fix for that? Is there a simpler way to debug a .c file?
|
For linux system you could use gdb as debugger in this way:
```
$ vim hello.c
# include <stdio.h>
int main()
{
printf("hello \n");
}
$ gcc -o hello hello.c
$ ./hello
$ gdb hello
(gdb) break main
(gdb) run
```
and then you can use:
c or continue
n or next
s or step
For more details seethis.
|
I am trying to create a list like:
```
[(0, 100), (1, 200), (2, 300), (3, 400), (4, 450), (5, 500), (6, 550), (7, 560), (8, 570)]
```
I made it in python by simply zipping two list;
```
x = [0,1,2,3,4,5,6,7,8]
y = [100,200,300,400,450,500,550,560,570]
zipit = zip(x,y)
```
What is the best way to do the same in Arduino C?
|
Use struct that holds 2ints and make an array out of it:
```
struct pair {int a; int b;} arr[100];
void setup() {
//creating simple [(5,6), (1,2)]
arr[0].a = 5;
arr[0].b = 6;
arr[1].a = 1;
arr[1].b = 2;
}
void loop() {
// put your main code here, to run repeatedly:
}
```
|
Why does this program producepandqas outputs? What is the difference between passing an array as a pointer or as an array.
```
#include<stdio.h>
void fun(char i[]){
printf("%c,%c", i[1],i[2]);
}
void fun2(char *i){
printf("\n%c,%c", i,i+1);
}
int main(){
char ar[] = {"Aba"};
fun(ar);
fun2(ar);
return 0;
}
```
Output:
```
b,a
p,q
```
|
You are printing the ASCII conversion of a pointer address in the second function. You must dereference the pointer via*iand*(i+1).
|
I'm learning C for fun and I'm trying to make a program that creates a array of strings. I'm trying this right now:
```
char str[2][10];
strcpy(str[0], "foo");
strcpy(str[1], "bar");
printf("%d \n",str[0]);
printf("%d \n",str[1]);
```
But myprintfreturns only some numbers, and I would like it to displayfooandbar. I've been reading about and I think that it is displaying a pointer to my strings. What am I doing wrong?
|
You are printing using the format%d, which is used to print anint. Modify your code to :
```
printf("%s\n", str[0]);
printf("%s\n", str[1]);
```
Seethis linkfor more information on the specifiers' format forprintf.
|
How do I define three dimensional array of complex numbers dynamically in C so that I can access in[i] [j] [k]notations which is handy in accessing arrays?
|
ExtendingBob__'sexampleto have the array allocated on the heap instead of on the stack:
```
#include <stdlib.h>
#include <stdio.h>
#include <complex.h>
int main(void)
{
size_t n = 2, m = 3, o = 4;
double complex (*pa)[n][m][o] = malloc(sizeof *pa);
if (NULL == pa)
{
perror("malloc() failed");
exit(EXIT_FAILURE);
}
(*pa)[1][2][3] = 1.0 + 0.5*I;
printf("%f + %fi\n", creal((*pa)[1][2][3]), cimag((*pa)[1][2][3]));
free(pa);
return EXIT_SUCCESS;
}
```
|
How do I time my C program in Clion? Is there an option I can use to to tell me how long long my program took to run?
something like
>finished in .003 seconds
here is what I am referring to when I say debugger/console:
|
You can measure the time of your code from inside your C program.
```
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main() {
clock_t start = clock();
int n = 100;
int i=0;
while(i<100*n)
i++;
clock_t stop = clock();
double elapsed = (double) (stop - start) / CLOCKS_PER_SEC;
printf("\nTime elapsed: %.5f\n", elapsed);
return 0;
}
```
|
I'm trying to get the function name of C function that was hidden, aka not exposed in the symbol table of an image.
I'm doing this on OS X and using dladdr and when dladdr returns success I check thedli_snamefield, but its NULL.
Is there no way to get back the C function name? As I understand it, the C functions that are unexported end up being inlined?
|
There is no way.
Inline or not, if it isnt in the symbol table, there isn't anywhere else names are stored short of if it was built with debug info, and even then if it were optimized it is still sometimes difficult or impossible to recover.
You can dump the symbol table with e.g. objdump if you are curious, anything that isn't there isn't available to you through dladdr.
|
Following is my code, when I enter "carol chen", I expect it will print out 9 characters, but it print out 10.
The name you enter is: carol chen
The number of characters in the user's name is 10
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char *name;
int i;
int n = 0;
name= (char *)calloc(80, sizeof(char));
if(name == NULL) {
printf("\nOut of memory!\n");
return 1;
}
else {
printf("The name you enter is: ");
scanf("%79[0-9a-zA-Z ]", name);
for(i=0; i<80; i++){
if(name[i] != 0){
n += 1;
}
}
printf("\nThe number of characters in the user's name is %d\n", n);
}
free(name);
}
```
|
Just don't count the spaces by adding anandclause that excludes spaces inside yourifcondition:
Try this:
```
if (name[i] != 0 && name[i] != ' ')
{
n += 1;
}
```
|
What I want to do is something on lines of...
```
pthread_create(&producer_thread, &to_join, producer_routine, &queue);
pthread_detach(producer_thread);
...
...
pthread_join(producer_thread, NULL);
```
Is this possible in some way, on running the above code, it is unable to join the thread.
|
Once detached, it's not possible to join anymore.
FromNotesonpthread_detach()'s man page:
Once a thread has been detached, it can't be joined withpthread_join(3)or be made joinable again.
|
I am writing a C program in Eclipse editor. My C program requires me to write a multi-line macro. I want to write a code like:
```
#define my_Macro() \
struct my_Struct \
{ \
int a; \
float b; \
}; \
```
But as the macro is large so I have to make sure that I insert a\at end of each line (for compiler to know that macro is continued). So my question is: Does eclipse/CDT provides any way such that\is automatically inserted till the point the code is part of macro?
|
No, there is no such built-in functionality from Eclipse.
|
If I have Rust code like:
```
let x: u8;
let y = match x {
0 => "0",
1 => "1",
// ...
255 => "255",
_ => unreachable!(),
};
```
will it be as fast (or faster) than the C code:
```
byte x;
char* y;
switch(x) {
case 0: y = "0"; break;
case 1: y = "1"; break;
...
case 255: y = "255"; break;
}
```
I am wondering if Rust implements anything like a jump table in the assembly.
|
LLVM does what it thinks is fastest with match. Sometimes that's a jump table, sometimes it's not. It depends on the exact match, including how many features of match you're using. (Like @, if, and anything else.)
|
Does the python implementation of flock work transparently along with standard C libraries? If I have two programs, one in Python and the other in C, trying acquire a lock on a single file will it work?
Quick links:
Python flock:https://docs.python.org/2/library/fcntl.htmlLinux flock:http://linux.die.net/man/2/flock
|
Python'sfcntllibrary is built directly on top of the standard C libraries; so on Linuxfcntl.flock()uses theflockC functiondirectly.
See thesource code for thefcntlmodule:
```
#ifdef HAVE_FLOCK
Py_BEGIN_ALLOW_THREADS
ret = flock(fd, code);
Py_END_ALLOW_THREADS
```
This is clearly stated in thefcntl.flock()documentationas well:
fcntl.flock(fd, op)Perform the lock operation op on file descriptorfd(file objects providing afileno()method are accepted as well). See the Unix manualflock(2)for details. (On some systems, this function is emulated usingfcntl().)
So yes, it'll work.
|
I would like to know the function show_int() below actually do...
This code is in the page 28 of Computer Systems A Programmer's Perspective.
```
#include <stdio.h>
typedef unsigned char *byte_pointer;
void show_bytes(byte_pointer start, int len) {
int i;
for (i = 0; i < len; i++) {
printf("%.2x", start[i]);
}
printf("\n");
}
void show_int(int x) {
show_bytes((byte_pointer) &x, sizeof(int));
}
void main() {
show_int(20);
getchar();
}
```
|
The most important thing to understand is the cast to*byte_pointer(a.k.a.unsigned char):
```
(byte_pointer) &x
```
You may think of it as converting pointer toint(in your case: 20) to a series of bytes (that can be 4 or 8 or even more bytes, depending on the architecture).
What theshow_bytes()function is then doing is just iterating over a byte array to show its subsequent bytes, formatting it tohexadecimal format.
|
Consider inline assembly like this:
```
uint64_t flags;
asm ("pushf\n\tpop %0" : "=rm"(flags) : : /* ??? */);
```
Nonwithstanding the fact that there is probably some kind of intrinsic to get the contents of RFLAGS, how do I indicate to the compiler that my inline assembly clobbers one quadword of memory at the top of stack?
|
As far as I am concerned, this is currently not possible.
|
I have a question about socket programming. I want to clear the socket buffer.
I tried the following code:
```
int ret_read = read(return_events[index].data.fd, recv_buffer, sizeof(recv_buffer));
if(-1 == ret_read)
{
if(EAGAIN != errno)
{
printf("read data from %d error occured, errno=%d, %s.\n", return_events[index].data.fd, errno, strerror(errno));
/**
Tag-position, I know buffer is not empty. I wonder clear buffer in code position.The buffer is socket recv buffer, is not recv_buffer.
*/
}
continue;
}
```
I don't want to useread()again in Tag-position, becase I want to set the buffer to empty. Though usingread()in Tag-position, I think it may fail.
Is there anyone who can tell me another way exceptread()in Tag-position?
|
It's not different from any other buffer
```
bzero(recv_buffer, sizeof(recv_buffer));
```
|
Isstrcmpslower thanstrncmpas one can give pre-calculated string length to it, butstrcmpdoes not receive such information ?
I am writing an interpreter. I am aware that these functions are both optimized. I wonder what will be the better approach (in terms of performance), as I will do scan anyway and I will know offset positions hence lengths.
|
They do different things, so comparing them directly does not make sense.strncmpcompares the firstn(or fewer, if the string ends sooner) characters of a string.strcmpcompares whole strings. Ifnis sufficiently large thatstrncmpwill compare the whole strings (so that the behavior becomes effectively the same asstrcmp) thenstrncmpis likely to be moderately slower because it also has to keep track of a counter, but the difference might or might not be measurable or even present in a given implementation. For example an implementation ofstrcmpcould just passSIZE_MAXas the value forntostrncmp.
|
I have a question about socket programming. I want to clear the socket buffer.
I tried the following code:
```
int ret_read = read(return_events[index].data.fd, recv_buffer, sizeof(recv_buffer));
if(-1 == ret_read)
{
if(EAGAIN != errno)
{
printf("read data from %d error occured, errno=%d, %s.\n", return_events[index].data.fd, errno, strerror(errno));
/**
Tag-position, I know buffer is not empty. I wonder clear buffer in code position.The buffer is socket recv buffer, is not recv_buffer.
*/
}
continue;
}
```
I don't want to useread()again in Tag-position, becase I want to set the buffer to empty. Though usingread()in Tag-position, I think it may fail.
Is there anyone who can tell me another way exceptread()in Tag-position?
|
It's not different from any other buffer
```
bzero(recv_buffer, sizeof(recv_buffer));
```
|
Isstrcmpslower thanstrncmpas one can give pre-calculated string length to it, butstrcmpdoes not receive such information ?
I am writing an interpreter. I am aware that these functions are both optimized. I wonder what will be the better approach (in terms of performance), as I will do scan anyway and I will know offset positions hence lengths.
|
They do different things, so comparing them directly does not make sense.strncmpcompares the firstn(or fewer, if the string ends sooner) characters of a string.strcmpcompares whole strings. Ifnis sufficiently large thatstrncmpwill compare the whole strings (so that the behavior becomes effectively the same asstrcmp) thenstrncmpis likely to be moderately slower because it also has to keep track of a counter, but the difference might or might not be measurable or even present in a given implementation. For example an implementation ofstrcmpcould just passSIZE_MAXas the value forntostrncmp.
|
This question already has answers here:Shorthand for checking for equality to multiple possibilities [duplicate](3 answers)Closed7 years ago.
Justinsteadof:
```
if ( ch == 'A' || ch == 'B' || ch == 'C' || .....
```
For example, to do itlike:
```
if ( ch == 'A', 'B', 'C', ...
```
is there even ashorterway to summarize conditions?
|
strchr()can be used to see if the character is in a list.
```
const char* list = "ABCXZ";
if (strchr(list, ch)) {
// 'ch' is 'A', 'B', 'C', 'X', or 'Z'
}
```
|
I have this signature of a function:
```
void* cloneInt(const void* i);
```
Thisintrepresents a key for a hash function. I need to have this clone function as it is in my API for a generic implementation of a hash table (this function is a part of the int implementation, this function will be forwarded as a pointer to a function that my generic implementation will use).
But I am having a problem understanding: how can you clone anint? I need to return a pointer that will point on the same value ofint, but a different place in the memory. This got me very much confused.
|
This will work:
```
#include <stdio.h>
#include <stdlib.h>
void* cloneInt(const void* i)
{
int *myInt = malloc(sizeof(int));
*myInt = *(int*)i;
return myInt;
}
int main(int argc, char** argv)
{
int i=10;
int *j;
j = cloneInt(&i);
printf("j: %d i: %d\n", *j, i);
free(j);
}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.