question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
```
int count0=0,count1=0,cnt=0;
char str[200];
char ch;
ch= getchar();
while(ch!='\0')
{
str[cnt]=ch;
cnt++;
}
str[cnt]='\0';
printf("%s",str);
```
output expected :
```
shubham
```
output:
```
Your code didn't print anything.
```
input:
```
shubham
... |
You are just accepting one character, you should replacewhile()withdo-while().
```
int ch;
do
{
ch= getchar();
if(ch == EOF)
{
str[cnt] = '\0';
break;
}
else
str[cnt] = ch;
cnt++;
}while(ch != '\0');
```
The above loop should fix the issue that you are facing. You need to enter NULL term... |
This question already has answers here:Is there a standard function in C that would return the length of an array?(7 answers)Closed5 years ago.
Is there something like this available in the C standard library:
```
#define sizeofarr(a) ( sizeof(a) / sizeof(a[0]) )
```
|
No there is not such a thing!
For better Macro definition check this link directly:
is-there-a-standard-function-in-c-that-would-return-the-length-of-an-array
orcommon-array-length-macro-for-c
|
When we create temporary files using tmpfile, in most cases we cannot easily predict the name. Coverity scan also complains about its vulnerability.
So is there any function to create a temporary file which cannot be guessed easily?
|
If you using Linux, thenmkstemp
Or usetmpnam
|
```
int count0=0,count1=0,cnt=0;
char str[200];
char ch;
ch= getchar();
while(ch!='\0')
{
str[cnt]=ch;
cnt++;
}
str[cnt]='\0';
printf("%s",str);
```
output expected :
```
shubham
```
output:
```
Your code didn't print anything.
```
input:
```
shubham
... |
You are just accepting one character, you should replacewhile()withdo-while().
```
int ch;
do
{
ch= getchar();
if(ch == EOF)
{
str[cnt] = '\0';
break;
}
else
str[cnt] = ch;
cnt++;
}while(ch != '\0');
```
The above loop should fix the issue that you are facing. You need to enter NULL term... |
This question already has answers here:Is there a standard function in C that would return the length of an array?(7 answers)Closed5 years ago.
Is there something like this available in the C standard library:
```
#define sizeofarr(a) ( sizeof(a) / sizeof(a[0]) )
```
|
No there is not such a thing!
For better Macro definition check this link directly:
is-there-a-standard-function-in-c-that-would-return-the-length-of-an-array
orcommon-array-length-macro-for-c
|
From what I understood, I am passing the address of the variableato the functionint ffx1.
After that, what exactly does this linep = (int[2]){*p};mean?
```
int ffx1(int * p)
{
p = (int[2]){*p};
return(p[1]);
}
int main()
{
int a = 1;
a = ffx1(&a);
printf("%d", a);
return 0;
}
```
|
Withint ffx1(int * p),pis a pointer to anint.
(int[2]){*p}is acompound literaldefining anintarray of 2.@BLUEPIXYThis unnamed array we will callX[2]. Its first element have the value of*p, and the next element, being anintwill be initialized to zero (§6.7.9 21 & 10 ) as it is not explicitly listed.
p = ....assigned t... |
This question already has answers here:In a C function declaration, what does "..." as the last parameter do?(7 answers)Closed5 years ago.
I was going through the logger code and came across a function
```
bool LogMessage(const char *szFor, ...)
```
What does...indicates here?
|
This is called anellipsis notation. This means, the function is avariadic function.
It canlegallyaccept any number and type of incoming arguments.
|
My OpenMP (C) parallel code is slower than the serial bitonic sort code and although I have done all the possible combinations I could think of, I can't find the problem.
Here is part of the code:
```
void recBitonicSortOpenMP( int lo, int cnt, int dir ) {
if ( cnt > 1 ) {
int k = cnt / 2;
#pr... |
For recursive problems like this use OpenMP tasks, not nested parallelism and sections.http://cs.umw.edu/~finlayson/class/fall16/cpsc425/notes/24-sorting.htmlgives you a good example to follow...
|
This question already has answers here:In a C function declaration, what does "..." as the last parameter do?(7 answers)Closed5 years ago.
I was going through the logger code and came across a function
```
bool LogMessage(const char *szFor, ...)
```
What does...indicates here?
|
This is called anellipsis notation. This means, the function is avariadic function.
It canlegallyaccept any number and type of incoming arguments.
|
My OpenMP (C) parallel code is slower than the serial bitonic sort code and although I have done all the possible combinations I could think of, I can't find the problem.
Here is part of the code:
```
void recBitonicSortOpenMP( int lo, int cnt, int dir ) {
if ( cnt > 1 ) {
int k = cnt / 2;
#pr... |
For recursive problems like this use OpenMP tasks, not nested parallelism and sections.http://cs.umw.edu/~finlayson/class/fall16/cpsc425/notes/24-sorting.htmlgives you a good example to follow...
|
I can do
```
memcpy(buffer, "\0", 1);
```
but I can't do
```
memcpy(buffer, 0x0, 1);
```
It causes segmentation fault.
Is there a way I can use hex values with memcpy without their string representation?
|
memcpyaccepts two pointers."\0"is a pointer to a string.0x0interpreted as a pointer isNULL, which is illegal to read and write from on most platforms.
The correct way to rewrite the second example would be to use a pointer:
```
int x = 0x0;
memcpy(buffer, &x, 1);
```
|
I'm trying to print the a number stored in floating point in C and I'm struggling how to print it out.
I'm doing this right now which prints the number in IEEE format. I want it printed in reverse straight from memory.
How can I fix it?
Thanks
```
void printbits(size_t n, void *c) {
unsigned char *t = c;
if ... |
Use a union:
```
union u {
float f;
unsigned char p[4];
}
```
Thenu.f = myfloat;and iterate onu.p
|
```
#include<stdio.h>
int main ()
{
int n,a=0,b=24;
do
{
scanf("%d",n); //ask the user to enter a value of n less than 24
// but greater than 0.
} while(/*boolean expression logic*/)
if(a<n<b)
{
printf("%d\n",n);
}
return 0;
}
```
I need to evaluate:
If the value ofnis g... |
You want the program to keep asking for values untiln>=0 && n<24; in other words, you want to keep asking for values while!(n>=0 && n<24), which usingDe Morgan's lawwe can write as!(n>=0) || !(n<24), which can be reduced ton<0 || n>=24
```
do
{
scanf("%d",n);
}
while(n<0 || n>=24)
```
|
This question already has answers here:How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC(23 answers)Closed5 years ago.
```
#include <stdio.h>
#define IsLowerCase(c) (((c)>='a') && ((c)<='z'))
#define ToUpperCase(s) (IsLowerCase(s)? (s)-'a' + 'A': (s))
int main(void){
char... |
Yourchar *stringshould beconst char *string(but it is immutable); or betterchar string[] = .... and then declare another variablechar *s = string;, and loop and stepsinstead ofstring
|
Maybe I'm still tired, but I can't seem to figure out why this keeps crashing after the second input. No point in sorting it if it keeps breaking before the values are entered.
```
#include <stdio.h>
#define MAX 5
int main(){
int input[MAX], output[MAX], i, j, high;
printf("Please enter 5 exam scores.\n");
... |
The problem is occurring because you forgot to put '&' before input[i]:
```
scanf("%d\n", input[i]);
/// ^ missing &
```
|
This question already has answers here:Getting base name of the source file at compile time(12 answers)Closed5 years ago.
I use__FILE__during logging and debug my program. And when I use it, I get full source file path. So, I wanna write my own macro similar the macro__FILE__.
I looked for a solution, but I found no... |
Just remove the path from__FILE__.
Possible solution:
```
#include <libgen.h>
#include <stdio.h>
#define LOG(message) \
do { \
char* filename = basename(__FILE__); \
printf("In %s: %s", filename, message); \
} while(false);
```
Example has to be extended by check of log level. And instead of a fixed messag... |
Consider the following empty C program (the standard guarantees that the compiler does an implicitreturn 0):
```
int main(int argc, char* argv[]) {}
```
You can add any logic into this function that manipulatesargcandargv. Yet, whenmainfinishes, its assembly code will just do a simpleretinstead ofret 4. I am expecti... |
Most compilers choose to have the caller clean the arguments from the stack; a tradition that dates from early C compilers and handling number of arguments. At the call-site, the compiler knows how many it pushed, so it is trivial for it to adjust the stack.
Also, note that historically main can be specified with 0-... |
I'm trying to input data from filesample.txtinto my c program on netbeans. How can I do that from command line? I know I should go toFile -> Project Properties -> Run -> Run Command.But what would I enter for Run Command?
|
If you have set theOUTPUT_PATHproperly it will be"${OUTPUT_PATH}" "ARG"
|
This question already has answers here:Getting base name of the source file at compile time(12 answers)Closed5 years ago.
I use__FILE__during logging and debug my program. And when I use it, I get full source file path. So, I wanna write my own macro similar the macro__FILE__.
I looked for a solution, but I found no... |
Just remove the path from__FILE__.
Possible solution:
```
#include <libgen.h>
#include <stdio.h>
#define LOG(message) \
do { \
char* filename = basename(__FILE__); \
printf("In %s: %s", filename, message); \
} while(false);
```
Example has to be extended by check of log level. And instead of a fixed messag... |
Consider the following empty C program (the standard guarantees that the compiler does an implicitreturn 0):
```
int main(int argc, char* argv[]) {}
```
You can add any logic into this function that manipulatesargcandargv. Yet, whenmainfinishes, its assembly code will just do a simpleretinstead ofret 4. I am expecti... |
Most compilers choose to have the caller clean the arguments from the stack; a tradition that dates from early C compilers and handling number of arguments. At the call-site, the compiler knows how many it pushed, so it is trivial for it to adjust the stack.
Also, note that historically main can be specified with 0-... |
I'm trying to input data from filesample.txtinto my c program on netbeans. How can I do that from command line? I know I should go toFile -> Project Properties -> Run -> Run Command.But what would I enter for Run Command?
|
If you have set theOUTPUT_PATHproperly it will be"${OUTPUT_PATH}" "ARG"
|
I'm trying to input data from filesample.txtinto my c program on netbeans. How can I do that from command line? I know I should go toFile -> Project Properties -> Run -> Run Command.But what would I enter for Run Command?
|
If you have set theOUTPUT_PATHproperly it will be"${OUTPUT_PATH}" "ARG"
|
I've just came up with this code on minute 1:06 ofa coursera lecture. What does it do?
```
int (*cmp)(char*, char*);
```
|
This is a pointer to a function where the function returns an int and takes as argument two character pointers.
The basic rule boils down to few things:-
There are three simple steps to follow:
Starting with the unknown element, move in a spiral/clockwise direction; when ecountering the following elements replace... |
```
#include <stdio.h>
int c=0;
int check (int c)
{
c=c+1;
if (c<6)
return check(c);
printf("%d\n", c);
}
int main()
{
printf("%d\n",check(c));
}
```
The above code gives me
```
6
2
```
as the output. 6 is from the printf function inside the check function but I did'nt get why 2. If I rem... |
You are invokingundefined behavior. So it behaves oddly.
You must have a proper return statement in thecheckfunction as you are supposed to return anint.
Also havingprintfor not having it - doesn't change anything- it's still UB.(in this case)
|
Whenever I try to debug and/or run in VS2015, a 'save file as' dialogue opens up. not knowing what to do my first thought is to exit and reopen, but when I try to save the project first, again the dialogue appears! when I try to cooperate and save it under that file name a message appears saying this file already exis... |
Problem solved by closing Google drive.
|
This question already has answers here:What should main() return in C and C++?(19 answers)Closed5 years ago.
What will happen if we don't use it? will the compiler automatically add it like it does in C++?
|
It will return0automatically in C99-compliant compilers (and later). In pre-C99 compilers the return value is undefined in such cases.
In other words, inmodernC you don't need an explicitreturn 0at the end ofmain.
|
I am trying to create akeystream generatorin C in order to encrypt some data with the generated key. This is for educational purposes.
In cryptography, a keystream is a stream of random or pseudorandom
characters that are combined with a plaintext message to produce an
encrypted message
There is a little or no i... |
NIST has described a key stream generator based on AES (in counter/CTR) inNIST SP 800-38A.
Writing good key stream generators is hard, and pure stream ciphers have fallen into disuse because they do not sufficiently protect message integrity.
|
I'm trying to read through some C source code and I've come across a structure assignment that I don't understand:
```
static struct sym_table *sym_array = (struct sym_table *) 0;
```
I understand that the left-hand-side is trying to initialize a pointer to a structure of type 'sym_table' (which is defined elsewhere... |
```
static struct sym_table *sym_array = (struct sym_table *) 0;
```
is a slightly cumbersome way to set a pointer toNULL,NULLbeing defined instdio.has((void *)0). You'd be better off with:
```
static struct sym_table *sym_array = NULL;
```
|
I am trying to create akeystream generatorin C in order to encrypt some data with the generated key. This is for educational purposes.
In cryptography, a keystream is a stream of random or pseudorandom
characters that are combined with a plaintext message to produce an
encrypted message
There is a little or no i... |
NIST has described a key stream generator based on AES (in counter/CTR) inNIST SP 800-38A.
Writing good key stream generators is hard, and pure stream ciphers have fallen into disuse because they do not sufficiently protect message integrity.
|
I'm trying to read through some C source code and I've come across a structure assignment that I don't understand:
```
static struct sym_table *sym_array = (struct sym_table *) 0;
```
I understand that the left-hand-side is trying to initialize a pointer to a structure of type 'sym_table' (which is defined elsewhere... |
```
static struct sym_table *sym_array = (struct sym_table *) 0;
```
is a slightly cumbersome way to set a pointer toNULL,NULLbeing defined instdio.has((void *)0). You'd be better off with:
```
static struct sym_table *sym_array = NULL;
```
|
Initializing a pointer to integer is done using the following code:
```
int a[] = {1,2,3};
int * p= a;
```
My Question is why a one-liner below doesn't work and if there is another way.
```
int *p = &{1,2,3};
```
Note: This question isnotabout the best performing or best readable version of the code. This is just ... |
There is absolutely no reason why you can't do this in 2 lines of code like you already do. It is clear and readable.
If youmustcomplicate things for the sake of it, you can write acompound literal:
```
int* p = (int[]){1,2,3};
```
This will yield exactly the same machine code as the code you already have, so no ve... |
```
#include<stdio.h>
int main()
{
unsigned char c =292;
printf("%d\n",c);
return 0;
}
```
The following code gives the output "36".
I wanted to know why this happens?
|
Because 292 does not fit in a variable of typeunsigned char.
I suggest you to compile this program:
```
#include <stdio.h>
#include <limits.h>
int main()
{
unsigned char c =292;
printf("%d %d\n", c, UCHAR_MAX);
return 0;
}
```
and check the output:
```
prog.c: In function 'main':
prog.c:5:21: warning: uns... |
```
char stringConcatenate (char y[], char z[])
{
unsigned short int a = 0, len;
len = stringLength(y);
while (z[a] != '\0')
{
y[len + a] = z[a];
a++;
}
printf("%s\n", y);
return y;
}
```
Thereturn y;is not returning the value stored in it to the function call.
|
I'd strongly suggest that you first read about the basics of pointers and arrays. Check outthis article.
An array likechar y[]is organised as a contiguous set ofcharelements, and a pointer calledypoints to the first element of the array. Since this pointer points to achartype, the type of the pointer itself ischar *.... |
Given achar *str = "something %s something2 %d", how can I format it and produce a new string without printing out? I know of "printf" which prints out a result, but I don't need a result to be printed out.
|
The answer issprintf: it's exactlyprintfto a buffer.
|
I opened"stdint.h"file fromvisual studio 2015and as shown in below image, I noticed theINT_FAST16_MAXis defined toINT32_MAX. And same with unsigned too. Why is it so?
But the least ones are defined as expected. (below)
```
#define INT_LEAST16_MAX INT16_MAX
#define UINT_LEAST16_MAX UINT16_MAX
```
|
INT_FAST16_MAXis the largest value that can be stored in anint_fast16_tvariable.
int_fast16_tis guaranteed to be the fastest int with a size ofat least16 bits.
Because MSVC is targeting machines that have 32-bit general purpose registers which are faster to access than 16-bit,int_fast16_tis actually a 32-bit integer... |
I have a struct that I want to statically allocate at compile time but I'm not sure how to return a pointer to the inner structure.
```
typedef struct
{
int d;
} innerStruct;
typedef struct
{
int a;
int b;
int c;
innerStruct inner;
} myStruct;
static myStruct m1;
innerStruct * getMyStructPtr()
{
myStr... |
Check the data types!!
Your function promised to return ainnerStruct *, whereas your code attempts to returns ainnerStruct. They are neither same nor compatible. Fix either and use it appropriately.
Following the function call, it appears that you may want to write
```
return &(ptr->inner); // return type innerStr... |
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer... |
Does LibVLC work in C++ ?
Yes, you can use it like any other c-API in c++.
|
This question already has answers here:strlen function using recursion in c(4 answers)Closed5 years ago.
I've made it in iterative way:
```
#include<stdio.h>
#include<conio.h>
void lol(char *s1,int *i) {
while(*s1!='\0') {
s1 = (s1 + 1);
*i=*i+1;
}
}
void main(void) {
char s1[] =... |
A recursive strlen:
```
int mylen(char *s)
{
if (!*s) return 0;
return (mylen(s+1) + 1);
}
```
|
If I have an int function, with areturn;
```
int f(int val, int *hasResult) {
if (val) {
*hasResult = 0;
return;
}
*hasResult = 1;
return 2;
}
```
and use it as
```
int hasResult;
int unwrapped = f(val, &hasResult);
if (hasResult) {
printf("%d", unwrapped);
}
```
Is this valid C89? I know it's no... |
InC89 draft paragraph 3.6.6.4we find:
If a return statement without an expression is executed, and the value of the function call is used by the caller,the behavior is undefined. Reaching the } that terminates a function is equivalent to executing a return statement without an expression.
In short, to be avoided, wh... |
I'm trying to learn RDMA.
My question is, when doingibv_post_send, I should get a completion event on a completion queue. But how does theibv_post_sendknow to which completion queue? From what I see here, I could have createdmany.
|
Turns outwhen initiating a QP, it can be assigned to a send CQ and recv CQ in its init attributes.
|
I am new to scientific computing and trying to contribute toscipybut I can't get it to build.
Igit clone'd the source then ranpython setup.py build. I get a break saying:
scipy/special/cephes/bdtr.c: In function ‘cephes_bdtrc’:
scipy/special/cephes/bdtr.c:157:5: error: non-floating-point argument in call to functi... |
This appears to be a bug in this particular scipy/numpy combination.nandkare integer variables, so they cannot be NaNs, introduced incommit ede5590b12dbeecd244fdafa4443b6c3a9d9ef40 (BUG: special: fix ufunc results fornanarguments).
You could change the reported line locally to
```
if (npy_isnan(p)) {
```
until the ... |
So my program runs the numElements method but than crashes, am I declaring my variables wrong or is my pointer variable wrong?
Header.h
```
typedef struct Node {
int number;
struct Node *pNext;
}Node;
```
Other.h
```
void LinkedList(Node *pNode){
int i,j,c,numElem;
time_t t;
srand((unsigned) time(&t));
numElem = ... |
I needed thispNode = malloc(numElem * sizeof(Node));
|
Lets say I have a char array of len = 2.
```
char* array = malloc(2);
memset(array, 0, 2);
```
This is 2 bytes = 0000000000000000. How could I turn this into 11111111111111111?
I can do it with a for loop and a pointer, but I don't think this is the cleanest way of doing it.
|
Let's say that your length,2, is just in your example, and you want to have something work no matter the length of the char array. You still need a loop, but you can invert the binary values of up to 64 bits at once (on a 64 bit CPU, disregarding SIMD capabilities). If you are REALLY looking for THE BEST performance, ... |
A runtime I'ld like to to know if an stack defined struct sockaddr_storage was assigned to any IP address (IPv4 or IPv6)
Any idea?
|
Check thess_familyfield. It will beAF_INETfor an IPv4 address, orAF_INET6for an IPv6 address. You can then type-cast thesockaddr_storageaccordingly to eithersockaddr_inorsockaddr_in6in order to access thesockaddr_in::sin_addrorsockaddr_in6::sin6_addrfield, respectively, to make sure it is not set to zeros.
|
I'm working on how to pass the entire char array including its values to another function. here's the code:
```
#define STACK_SIZE 100
void Prefix_Conversion(char Infix_Postfix_Expression[STACK_SIZE]);
int main(){
//some process code here
Prefix_Conversion(Infix_Postfix_Expression[STACK_SIZE]);
}
void Pref... |
WithPrefix_Conversion(Infix_Postfix_Expression[STACK_SIZE]);you're passing one character to a function that needschar *, hence the error message.
Simply passPrefix_Conversion(Infix_Postfix_Expression);
|
I am reading a file that looks like this
00 READ 09
01 READ 10
and so on (the line in between represents a newline) but I can only get the first line for some reason. What am I doing wrong? It just prints 00 READ 09
Here's the code
```
int compile(FILE * fpointer)
{
char string[12];
char *tokenp = strtok(... |
You are running strtok on an unitialized string.
|
I found an example on usingstrtoloverhere- I'll replicate the example here:
```
#include <stdio.h>
#include <stdlib.h>
int main () {
char str[30] = "2030300 This is test";
char *ptr;
long ret;
ret = strtol(str, &ptr, 10);
printf("The number(unsigned long integer) is %ld\n", ret);
printf("String pa... |
You're not actually using an uninitialized pointer. You're passing the address of a local variable, which is known.
The variableptris of typechar *, so&ptris of typechar **, which is whatstrtolexpects for its second argument. Thestrtolfunction will then dereference this pointer, yielding an lvalue expression (i.e. ... |
I'm trying to compile my C code but I need to tell the GCC compiler where two file are.
The two files are located here
```
/usr/local/ssl/include/
/usr/local/ssl/lib/
```
I want to add this to mygcc -o file file.cso that my program can work.
|
In gcc, the-Ioption is used for adding a directory to the set of directories to search for header files, and the-Loption is used for adding a directory to the set of directories to search for libraries. Since you're not explicitly linking in any libraries, you shouldn't need the-Loption in this case.
```
gcc -I/usr/... |
What I want is something functionally like this:
```
#if TODAY<OCTOBER_31_2017
#define OK 0
#elif TODAY==OCTOBER_31_2017
#define OK 1
#else
#define OK 2
#endif
```
So I want "OK" to have the relevant compile-time value, depending on today's date.
Is there any way to do it?
|
Assuming a compiler that accepts the-Doption and a POSIX shell/environment invoking it, you can do:
```
cc -DOCTOBER_31_2017=$(date -d 'Oct 31 2017' +%s) \
-DTODAY=$(date -d now +%s) \
yourfile.c
```
and your preprocessor code should work.
(date +%sprints dates as a UNIX timestamps (seconds since 1970-01-01 ... |
I'm trying to make a file pointer and I want the user to enter in the title and then have the program add .txt after the the title and here's one of the ways I tried to do it
```
int main()
{
File * fpointer;
char name;
printf("Type name of program");
scanf("%s.txt", &name);
puts(&name);
}
```
|
scanf's approach will validate an input sequence to have.txtsuffix. In addition, you do not have enough space for a string, becausenamecan hold a single character.
If you want to force a suffix on an existing input, usestrcatfunction:
```
#include <stdio.h>
#include <string.h>
#define MAX_NAME 40
int main() {
F... |
My issue is to access a variable'instruct[0]'of'ready[1]'for example, with structs:
```
typedef struct type_program{
int cont;
int variable;
char instruct[30][10];
} type_program;
typedef struct type_tab{
type_program *executing;
type_program *ready[10];
type_program *blocked[10];
} type_t... |
Assuming you have created atype_tablike so:
```
type_tab some_tab;
```
You can easily accessready[1]andinstruct[0]with:
```
some_tab.ready[1]->instruct[0]
```
However note thatreadybeing an array of pointers, forces you to initialize them withmallocbefore using them.
If you have atype_tabpointer, because you allo... |
The following loop appears in some of our sample C codes:
```
while (i > 0)
printf("We are still in the loop and counting down %d ...\n", i--);
```
Since the while-loop terminates when i becomes 0, we may remove the “> 0”,test as:
```
while (i)
printf("We are still in the loop and counting down %d ...\n", i... |
This depends on the data type ofi:
while(i)means: "Loop as long asiis not zero";while(i>0)means: "Loop as long asiis neither zero nor negative".
Ifiis a variable of anunsigneddata type it cannot be negative sowhile(i)andwhile(i>0)have the same meaning.
Ifihowever is asignedor floating-point variable this is not the... |
I have simple string to int mapping. How should I do lookup by int using hash or other efficient algorithm (please provide some example)?
```
struct string_int_map {
char *str;
int val;
};
struct string_int_map s_to_i_map[] {
{ "test1", 45 },
{ "test2", 95 },
{ "test3", 83 },
{ "test4", ... |
Sort an array and perform binary search. Thanks @Weather for giving the reference.
|
I want to open terminal and cat a file (show its content) using c;
i got error from code below:
```
char * com = "xterm cat /home/user/Desktop/file.c";
system(com);
```
or even:
```
char * com = "/usr/bin/xterm /bin/cat /home/user/Desktop/file.c";
system(com);
```
thanks for any help;
|
You could change your command to:
```
xterm -e less file.c
```
|
```
#include <stdio.h>
#include <unistd.h>
int main(void) {
int i = 0;
for (i = 0; i < 4; i++) {
fork();
printf("foo\n");
}
return 0;
}
```
This prints "foo" 30 times. Why?
And why does it print "foo" 64 times if you pipe the output?
```
$ ./a.out | wc -l
64
```
|
When you invokefork()everything gets duplicated. So you will double in each iteration. That's why it prints 2+4+8+16=30 times. This can be easily seen if you print the value ofitogether with thePIDfor the process.
As mch stated, piping changes the output buffer from line buffered to full buffered, so fork duplicates ... |
No matter what value I enter for x, the output for the value of y is always 1. Any ideas why?
```
#include <stdio.h>
int main() {
int x, y;
y = scanf("%d", &x);
printf("y = %d\n", y);
return 0;
}
```
|
Fromscanf(3) - Linux man page:
These functionsreturn the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
Sincescanfreturn value is the number of items written (in your case, 1, since only 1intwas scanned), not the ... |
My issue is to access a variable'instruct[0]'of'ready[1]'for example, with structs:
```
typedef struct type_program{
int cont;
int variable;
char instruct[30][10];
} type_program;
typedef struct type_tab{
type_program *executing;
type_program *ready[10];
type_program *blocked[10];
} type_t... |
Assuming you have created atype_tablike so:
```
type_tab some_tab;
```
You can easily accessready[1]andinstruct[0]with:
```
some_tab.ready[1]->instruct[0]
```
However note thatreadybeing an array of pointers, forces you to initialize them withmallocbefore using them.
If you have atype_tabpointer, because you allo... |
The following loop appears in some of our sample C codes:
```
while (i > 0)
printf("We are still in the loop and counting down %d ...\n", i--);
```
Since the while-loop terminates when i becomes 0, we may remove the “> 0”,test as:
```
while (i)
printf("We are still in the loop and counting down %d ...\n", i... |
This depends on the data type ofi:
while(i)means: "Loop as long asiis not zero";while(i>0)means: "Loop as long asiis neither zero nor negative".
Ifiis a variable of anunsigneddata type it cannot be negative sowhile(i)andwhile(i>0)have the same meaning.
Ifihowever is asignedor floating-point variable this is not the... |
I have simple string to int mapping. How should I do lookup by int using hash or other efficient algorithm (please provide some example)?
```
struct string_int_map {
char *str;
int val;
};
struct string_int_map s_to_i_map[] {
{ "test1", 45 },
{ "test2", 95 },
{ "test3", 83 },
{ "test4", ... |
Sort an array and perform binary search. Thanks @Weather for giving the reference.
|
I want to open terminal and cat a file (show its content) using c;
i got error from code below:
```
char * com = "xterm cat /home/user/Desktop/file.c";
system(com);
```
or even:
```
char * com = "/usr/bin/xterm /bin/cat /home/user/Desktop/file.c";
system(com);
```
thanks for any help;
|
You could change your command to:
```
xterm -e less file.c
```
|
```
#include <stdio.h>
#include <unistd.h>
int main(void) {
int i = 0;
for (i = 0; i < 4; i++) {
fork();
printf("foo\n");
}
return 0;
}
```
This prints "foo" 30 times. Why?
And why does it print "foo" 64 times if you pipe the output?
```
$ ./a.out | wc -l
64
```
|
When you invokefork()everything gets duplicated. So you will double in each iteration. That's why it prints 2+4+8+16=30 times. This can be easily seen if you print the value ofitogether with thePIDfor the process.
As mch stated, piping changes the output buffer from line buffered to full buffered, so fork duplicates ... |
No matter what value I enter for x, the output for the value of y is always 1. Any ideas why?
```
#include <stdio.h>
int main() {
int x, y;
y = scanf("%d", &x);
printf("y = %d\n", y);
return 0;
}
```
|
Fromscanf(3) - Linux man page:
These functionsreturn the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
Sincescanfreturn value is the number of items written (in your case, 1, since only 1intwas scanned), not the ... |
I am working on a code and I have problem representing the data into the form of row and column. The row collects data from a binary file and after 349 data are collected, it moves to the next column. However, the problem that I am encountering is that, the data I gathered skips to the 4008 data to 4008+349... so it s... |
This
```
for (i = 0; i < DATAPERROW; i++) {
for (int j = 0; j < NUMPLOTS; j++) {
if (j*NUMPLOTS+i < bytes)
printf ("%hd\t", su.shint[j*NUMPLOTS+i]);
}
printf("\n");
}
```
Should be
```
for (i = 0; i < NUMPLOTS; i++) {
for (int j = 0; j < DATAPERROW; j++) {
if (i*DATAPERROW+j < bytes)
prin... |
```
int main()
{
while (n != 0)
{
digit = n / 10;
n = n / 10;
printf("%d ", digit);
}
_getch();
return 0;
}
```
Heading
////////////////////////////////////
input 1234, output 1 2 3 4. But I have a problem with zero, if I enter 0123, output just only 1 2 3
|
This looks like a homework assignment, so I won't write the code for you, but I can tell you the algorithm. Convert n to a string (seeitoa), then iterate over that string, printing each character one at a time.
|
For a class assignment we are writing a program which takes in input, and sorts each line of input with qsort with strcmp as its comparator function. Because the type of strcmp is not the same as required by qsort, a wrapper function needs to be built to satisfy qsort.
I wasn't satisfied with this, and wanted to writ... |
C does not support lambda functions. Your only choice is to create a function of the type expected byqsortand callstrcmpfrom inside of that function.
For example:
```
int qsort_cmp_str(const void *a, const void *b)
{
const char *s1 = a;
const char *s2 = b;
return strcmp(s1, s2);
}
```
|
This question already has answers here:Detect if stdin is a terminal or pipe?(6 answers)Closed5 years ago.
I'm currently working on my school project and wondered if there is any way to tell if user has written<textfile.txtto the terminal.
Like this:./project <textfile.txt
My project reads all the lines from the te... |
You might useisatty(3)to detect if your stdin is a terminal.
You could usefstat(2)onSTDIN_FILENO, e.g. to detect redirection orpipelines.
Or (on Linux)readlink(2)/proc/self/fd/0, seeproc(5)
I recommend accepting some program argument to override such an auto-detection. Readthis.
Be aware that redirection and globb... |
I'm trying to make a system call in Ubuntu 12.04.1. I'm getting an error compiling myhello.cfile:
```
#include <linux/kernel.h>
asmlinkage long sys_hello(void) {
printk("hello world\n");
return 0;
}
```
It shows the error:
error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘long’ asmlinkage long... |
All the system calls must be compiled into the kernel. You need to do this within the kernel build system.you cannot use it outside the kernel or shared object.
|
What is the data structure used to store the return value of MPI_MAXLOC in MPI_Reduce() function for an array ofdoublevalues
|
inC, the MPI type you must use isMPI_DOUBLE_INT, and there is no predefined C structure for that (e.g you have to create it manually) like this
```
struct {
double val;
int rank;
};
```
fwiw, the predefinedMPI_DOUBLE_INTdatatype is defined like this
```
type[0] = MPI_DOUBLE
type[1] = MPI_INT
disp[0] =... |
So I'm trying to override the fscanf function in c, but I only want different behavior to occur if certain conditions are met; if those conditions are not met, I want to just call the original fscanf. I know that you can use dlsym to use the original version of a function while interpositioning it, but the problem wit... |
You can't call the original fscanf from the interposed fscanf. You just have to callvfscanf(). Your interposed function would look like:
```
int fscanf(FILE *stream, const char *format, ...)
{
....
....
va_list ap;
va_start(ap, format);
int rc = vfscanf(stream, format, ap);
va_end(ap);
r... |
i have array of strings.
```
char strings[][30]={"word1","word2",......,""};
```
Iterated over them but at the end i got messageSegmentation fault (core dumped)
Tried with following code :
```
for(int i=0;strings[i] != "";i++){printing items...}
```
I think the problem is with!= ""but why isn't it working?
|
Usestrcmpto compare strings in C.==or!=doesn't work for strings in C.
|
I am writing a C program to get Fibonacci number, the user needs to put the first 2 numbers and the sequence starts from there. Here is my code:
```
#include <stdio.h>
#define MAX_SIZE 100
int main()
{
int i, input[MAX_SIZE];
printf("please Enter first 2 digit of the Sequence\n");
scanf("%d, %d" , &inp... |
When you exit from the loopiis equal toMAX_SIZE
```
printf("%d\n", input[i]);
```
you are printing a value outside of the bounds of the array (input[MAX_SIZE]).
|
Whats the difference between Struct tag and Pointer to Struct? Are the same? Or Here is my example, Is obj and *var two different memory location?
```
#include <stdio.h>
#include <stdlib.h>
struct alloc {
char data;
};
int main(int argc, char** argv) {
struct alloc obj;
struct alloc *var = calloc(5,si... |
Yes, they are. Memory forobjis allocated statically (on stack), whereas forvardynamically (on heap). The main practical difference is, that statically allocated objects get destroyed at the end of the block, but you have to free the memory for dynamically allocated objects manually (in order to prevent memory leaks).
... |
I am defining a function where one of the argument isconst char **p. I understand that it means 'declare p as pointer to pointer to const char'. Now I want to check if the const char is NULL character and thus check(**p == NULL)but it gives warning thatwarning: comparison between pointer and integer. Here is the code ... |
NULL is a macro defining anull-pointer constant, not the ASCII character NUL. If you want to test for a character NUL, then:
```
if( **p == '\0' )
```
or more simply:
```
if( **p == 0 )
```
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed5 years ago.Improve this question
I would like to run a what I called "script C code" from string in my C++ program, for ex... |
The best way for reaching your goal, is to use a C interpreter library.
For example you can use this one:https://github.com/jpoirier/picoc
|
If I have something like !23 How can I parse it to get just the number part?
Input: !23
Output: 23
Input: !
Output: Error
Input: !23eds3
Output: Error
This is my approach of getting the numeric digit. But for some reason strcpy is messing up my array where I am storing some data, its deleting the first element in ... |
Some hints, but not going to write the code for you:
Use the string library functions likestrchrto find the '!'. Then usestrtodto convert a string to a number. Look atstrtod's output to see if it had an error or if it was followed by letters.
Or maybe you wantstrtolfor integers instead.
|
Some libraries might register some handlers withpthread_atfork(). I don't need them as I only usefork()together withexec(). Also, they can cause trouble in some cases. So, is there a way to reset the registered handler list?
Related:callingfork()without theatforkhandlers,fork()async signal safety.
|
POSIX does not document any mechanism for fork handlers installed bypthread_atfork()to be removed, short of termination of the process or replacing the process image. If you don't want them, then don't install them. If they are installed by a third-party library, as you describe, then your options are to find a way ... |
```
once = number/100;
thenth = (number%100)/10;
hundred = number%10;
sum = once + thenth + hundred;
printf("Sum of entered digits is %d\n", sum);
```
how the second number is calculated ex.(345%100)/10=34.5 how to calculate 2nd number please can anyone explain the logic of this program
|
(number % 100), for a non-negativenumberextracts the finaltwodigits, and dividing that by10will effectively discard the unit digit due tointeger division. So it's a scruffy way of calculatingthenth.
You can solve this more elegantly by lopping off the least significant digit ofnumberas you go:
```
hundred = number %... |
I am defining a function where one of the argument isconst char **p. I understand that it means 'declare p as pointer to pointer to const char'. Now I want to check if the const char is NULL character and thus check(**p == NULL)but it gives warning thatwarning: comparison between pointer and integer. Here is the code ... |
NULL is a macro defining anull-pointer constant, not the ASCII character NUL. If you want to test for a character NUL, then:
```
if( **p == '\0' )
```
or more simply:
```
if( **p == 0 )
```
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed5 years ago.Improve this question
I would like to run a what I called "script C code" from string in my C++ program, for ex... |
The best way for reaching your goal, is to use a C interpreter library.
For example you can use this one:https://github.com/jpoirier/picoc
|
If I have something like !23 How can I parse it to get just the number part?
Input: !23
Output: 23
Input: !
Output: Error
Input: !23eds3
Output: Error
This is my approach of getting the numeric digit. But for some reason strcpy is messing up my array where I am storing some data, its deleting the first element in ... |
Some hints, but not going to write the code for you:
Use the string library functions likestrchrto find the '!'. Then usestrtodto convert a string to a number. Look atstrtod's output to see if it had an error or if it was followed by letters.
Or maybe you wantstrtolfor integers instead.
|
Some libraries might register some handlers withpthread_atfork(). I don't need them as I only usefork()together withexec(). Also, they can cause trouble in some cases. So, is there a way to reset the registered handler list?
Related:callingfork()without theatforkhandlers,fork()async signal safety.
|
POSIX does not document any mechanism for fork handlers installed bypthread_atfork()to be removed, short of termination of the process or replacing the process image. If you don't want them, then don't install them. If they are installed by a third-party library, as you describe, then your options are to find a way ... |
Im using this double while loop. Im new to C.
```
int crawler;
char *desired[100];
crawler = getchar();
while(crawler != EOF) {
int i = 0;
while((crawler != '\n') && (crawler != EOF)) {
desired[i] = crawler;
i++;
crawler = getchar();
}
printf("%s", desired);
}
```
I just... |
Your outer loop ends whencrawlerisEOF.
Your inner loop ends whencrawleris'\n'orEOF.
Only the inner loop reads input (by callinggetchar).
Therefore: As soon as the first'\n'is read, the inner loop is never re-entered (the condition rejects'\n'), but the outer loop doesn't end, and it never changes the value ofcrawle... |
I ran into these lines:
```
#define bool bool
#define false false
#define true true
```
I don't think I need to say more than "wtf?", but just to be clear: What is the point of defining something to itself?
The lines come fromclang stdbool.h
|
The C and C++ standards explicitly allow that (and requires that there is no infinite expansion)
BTW, function-like recursive (orself-refential) macros are even more useful:
```
#define puts(X) (nblines++,puts(X))
```
(the innerputsis a call to the standardputsfunction; the macro "overloads" such further calls by c... |
I'm looking for a Leibniz approximation of PI in C.
I've tested this function but it does not seem to work:
```
float leibnizPi(float n){
double pi=1.0;
int i;
int N;
for (i=3, N=2*n+1; i<=N; i+=2)
pi += ((i&2) ? -1.0 : 1.0) / i;
return 4*pi;
}
```
|
I've tested you function and it seems to work fine. Forn=1000, I get a result of3.142592.
How I've tested the function:
```
#include <stdio.h>
float leibnizPi(float n) {
double pi=1.0;
int i;
int N;
for (i=3, N=2*n+1; i<=N; i+=2)
pi += ((i&2) ? -1.0 : 1.0) / i;
return 4*pi;
}
int main(v... |
I just started learning C and I have a very funny problem. I will let the code speak for itself. On scanf I give the value25.15:
```
long double input;
scanf("%Lf", &input);
printf("%Lf\n", input); //its correctly 25.150000
input = input - 0.75;
printf("%Lf\n", input); //Instead of something resembling 24.4 I get -2
... |
I also have same problem as you in CodeBlocks. Works perfectly with double.. Done somegoogling. It seems its known problem. Also try googling "long double giving wrong results c", i hope you will find your answer there.
|
So I'm currently learning obj-c and came across this code in a header file that's provided by apple in CGGeometry.h header file.
```
struct
CGPoint {
CGFloat x;
CGFloat y;
};
typedef struct CG_BOXABLE CGPoint CGPoint;
```
I don't understand the last portion of the code. This part:
```
typedef struct CG_BOXA... |
I believe it's a newly added feature, adding the ability to box the struct without having to add your ownobjc_boxableattributes.
See the radar that seemingly started this feature request:http://openradar.appspot.com/32486932
|
Suppose I have a variable inst which holds an encoded MIPS instruction. I want to set the rt field to 0 without changing the other fields. The rt field is a 5-bit field indexed from 16-20. I first tried:
```
inst = inst & ~(1 << 16);
```
which sets the rt field to 0. Then I want to put the value of a new variable ne... |
I believe the problem is with your first bitmask. The command (1 << 16) only masks the first bit, where you want to mask all of the bits from 16-20. Try:
```
inst = inst & ~(0x3f << 16)
```
Then:
```
inst = inst | (new_reg << 16);
```
|
I am tryin to compile an opensource project for ARM (Xvisor) but apparently gcc is using the wrong ldfile to link the librarylibncurseindeed when I compile, I got the following error:
```
/usr/gnat/bin/../libexec/gcc/x86_64-pc-linux-gnu/6.3.1/ld: cannot find libncurses.so.5
```
Andldconfigseems to have the library i... |
Try to reinstall build-essential package
```
sudo apt-get remove build-essential && sudo apt-get install build-essential
```
/usr/gnatis not the main directory for the system library
|
I have refered to the following webpage :
https://serverfault.com/questions/153983/sockets-found-by-lsof-but-not-by-netstat
Using Python, I have encountered the same problem on SSL sockets:
When I usesocket.close(), the socket stays in CLOSE_WAIT state for an indefinite time
when I usesocket.shutdown(), lsof... |
unwrapdoes a proper SSL shutdown. Such shutdown is similar to the FIN handshake at the end of the TCP connection, only at the SSL/TLS layer. How this shutdown is done in C depends on the specific SSL/TLS stack you are using. But for OpenSSL the function you need to use isSSL_shutdown.
|
Is this possible? I need to make a 2d array and each element is supposed to have an int array of size 2.
So if I make a 10x10 array I need each index to have a [x, y] where x and y are ints.
|
```
int array[10][10][2];
```
Here you have a 3D array. Where the 2D array : array[..][..] has 2 elements inside it.
Or you can use structure.
```
struct number {
int x;
int y;
};
```
then :
```
struct number array[10][10];
```
|
Suppose I have a variable inst which holds an encoded MIPS instruction. I want to set the rt field to 0 without changing the other fields. The rt field is a 5-bit field indexed from 16-20. I first tried:
```
inst = inst & ~(1 << 16);
```
which sets the rt field to 0. Then I want to put the value of a new variable ne... |
I believe the problem is with your first bitmask. The command (1 << 16) only masks the first bit, where you want to mask all of the bits from 16-20. Try:
```
inst = inst & ~(0x3f << 16)
```
Then:
```
inst = inst | (new_reg << 16);
```
|
Does anyone know how to enable the use of OpenMP in Xcode 9.0?
In Xcode 8, I procide as described inthis tutorialbut it doesn't work anymore in Xcode 9.0 ...
The error is :clang-5.0: error: cannot specify -o when generating multiple output files
Thanks in advance for help
|
I think the problem is in flag -index-store-path
In build settings > build options set Enable Index-While-Building Functionality to No
|
I write this code to get sin of angles between 0 and 90
example:
```
1: sin(0) =
2: sin(15)=
....
7: sin(90)=...
```
So I have written this code but he show me only one result
where is my problem ?
```
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
#include <time.h>
int main()
{
... |
This is because of your faulty loop condition. You need to correct your for-loop from
```
for(i=0; i>90; i=i+15)
```
to
```
for (i=0; i<=90; i=i+15)
```
Also remove the;after the for-loop.
|
I am trying to read the packets from a pcap file using a c program and print the time-stamp of each packet.
I am using the below line of code to print the timestamp:
```
printf("%s,",ctime((const time_t*)&header->ts.tv_sec));
```
And my output is as below:
```
Mon Jan 14 09:48:18 2013
```
How do I get it as YYYY-... |
You might like to have a look atlocaltime()andstrftime().
```
#define MYDATE_STR_MAX (<large enough> + 1)
...
struct tm lt = localtime(header->ts.tv_sec);
char st[MYDATE_STR_MAX];
strftime(st, MYDATE_STR_MAX, <format specifier as per man-page here>, lt);
/* use st here */
```
(include<time.h>on top)
|
My code is about saying one sentence about Berlin .. Part of this sentence starts with "Berlin " and the other part is from standard input from the user .. after printing the output .. I get weird random things like "w$
Here is my code :
```
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (){
... |
You haven't included the null terminator forarr(since you are printing it as a C-string using%s).
Add
```
arr[i] = 0;
```
after the while loop.
There are two other potential problems:
You haven't done bounds check. Soarrcould overflow if you enter more than 1000 chars.getchar()can returnEOFon input failure which ... |
I wanted to use the width option (http://en.cppreference.com/w/c/io/fscanf) of sscanf to control the maximal bytes to read. But the following reads more than 3 bytes.
```
#include <stdio.h>
int main() {
long long ll;
char str[4];
int pos;
sscanf(" 281", "%3llx%n", &ll, &pos);
printf("%llx %d\n", ll, pos)... |
Some (most) formats implicitly skip whitespace (basically everything except%cand%[). Skipped whitespace does not count towards the maximum field width.
|
Why we can return the value of a local variable from a function but not it's address? Such as we can write 'return a' but not 'return &a' in C.
|
A modified version of your example in the comments:
```
#include <stdio.h>
int* f() {
int a = 6, *p;
p = &a;
return p;
}
int g() {
int a = 6;
return a;
}
int main() {
int x = g();
int* y = f();
}
```
Bothfandgreturn by value.
One returns anintand stores the value inx. Nowxholds the valu... |
I'm new embedded electronics and am learning via online tutorials. I built and downloaded a code (with the uVision IDE) which made the blue and orange LEDs flash. I want these LEDs to stop flashing, and I want the MCU to go back to the state it was at before I downloaded the code. How would I do that?
|
How to return:
Write FLASH mass erase functionCopy mass flash erase function to the RAM.Jump to itDo the software reset
|
I'm trying to call the following function which should fill an array with sensors' data and return the number of detected sensors:
```
uint8_t ds18b20_read_all(uint8_t pin, ds_sensor_t *result)
```
How am I supposed to call it without knowing the number of sensors? I thought about:
```
ds_sensor_t *result = (ds_sen... |
Max sensors on 1-wire is 75. So you can have up to 75 ds18b20s attached. You can also query the wire to find outhow manysensors are attached usingint ds18b20_scan_devices(int pin, ds18b20_addr_t *addr_list, int addr_count);set addr_count = 75.
|
I want to know if a file is a directory or a regular file with stat :
```
#define _DEFAULT_SOURCE
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int is_regular_file(const char *path)
{
struct stat path_stat;
stat(path, &path_stat);
return S_ISREG(path_stat.st_mode);
}
```
I try on Mac... |
16877is octal40755, which denotes a directory (octal40000) with permissions755(user has full rights, everyone else has read and traversal rights). As suggested, thestatandchmodmanual pages are useful.
Just for example, here is a screenshot with mydirectory-editorshowing octal modes (an option) rather than the usual ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.