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 terminator usingctrl+@at the end of the string.
|
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 terminator usingctrl+@at the end of the string.
|
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 the pointerpto a new value. In this case, the above arrayX[]is converted to the address of its first enrollment or&X[0].
return p[1]de-referencesp, returning the value inX[1]or0.
|
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;
#pragma omp parallel sections
{
#pragma omp section
recBitonicSortOpenMP( lo, k, ASCENDING );
#pragma omp section
recBitonicSortOpenMP( lo + k, k, DESCENDING );
}
bitonicMergeOpenMP( lo, cnt, dir );
}
}
```
It is an implementation of Bitonic Sort.
|
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;
#pragma omp parallel sections
{
#pragma omp section
recBitonicSortOpenMP( lo, k, ASCENDING );
#pragma omp section
recBitonicSortOpenMP( lo + k, k, DESCENDING );
}
bitonicMergeOpenMP( lo, cnt, dir );
}
}
```
It is an implementation of Bitonic Sort.
|
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 (c == NULL)
return;
while (n > 0) {
int q;
--n;
for(q = 0x80; q; q >>= 1)
printf("%x", !!(t[n] & q));
}
}
```
|
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 greater than or equal to 0 and less than 24 (less than or equal to 23) then.... go to the if statement and print the value ofnotherwise... ask the user to input the value ofni.e. it should again go back in the loop.
|
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 *string = "abcdefghijklmnopqrstuvwxyz";
while(*string != '\0'){
*string = ToUpperCase(*string);
++string;
}
}
```
warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
|
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");
for (i=0; i<MAX; i++){
scanf("%d\n", input[i]);
}
for(i=0; i<MAX; i++)
printf("%d\n", input[i]);
return 0;
}
```
|
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 nothing about it.
So, does it exist a CMake way to implement user macro, that will be generate something data similar the__FILE__macro?
|
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 message a variadic number of arguments should be used.
Note: This is for Unix. Assume your OS provides a similar function.
|
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 expecting to see aret 4because in my mindmainis the callee of some other function and therefore must clean up its two arguments from the stack: and int and a pointer to char array. Why does it not do so?
|
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-3 (arge) arguments. Again, the caller (eg. _start) can just provide 3 and let the implementor choose.
|
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 nothing about it.
So, does it exist a CMake way to implement user macro, that will be generate something data similar the__FILE__macro?
|
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 message a variadic number of arguments should be used.
Note: This is for Unix. Assume your OS provides a similar function.
|
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 expecting to see aret 4because in my mindmainis the callee of some other function and therefore must clean up its two arguments from the stack: and int and a pointer to char array. Why does it not do so?
|
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-3 (arge) arguments. Again, the caller (eg. _start) can just provide 3 and let the implementor choose.
|
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 them with the corresponding english statements:[X] or []ArrayXsize of... or Array undefined size of...(type1, type2)function passingtype1andtype2returning...
*pointer(s) to... Keep doing this in a spiral/clockwise direction until all tokens have been covered. Always resolve anything in parenthesis first!
Reference:1.Clockwise-rule2.right-left rule
|
```
#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 remove the printf function inside the check function I get
```
5
```
as the output. Can anyone explain why this happens?
|
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 exists and when I try to replace it an error dialogue appears saying the file is being used by another process.
I have tried:
open VS prompt --> devenv /ResetSettingsrun as administratorclearing ReSharper cache
Nothing worked.
Help would be very much appreciated
Update: after clearing ReSharper cache it seemed like the issue was solved, but it wasn't. I can't point out when exactly it happens. it feels like this happens randomly.
|
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 information online that explains the internal functioning of a keystream generator. So, what is the proper way to create a keystream generator?
|
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); however, I am struggling to understand the right-hand-side. It's probably fairly simple, but I can't find any similar examples of this sort of assignment in any of the online C tutorials that I've seen.
If anyone can shed some light on it, I would really appreciate it!
|
```
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 information online that explains the internal functioning of a keystream generator. So, what is the proper way to create a keystream generator?
|
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); however, I am struggling to understand the right-hand-side. It's probably fairly simple, but I can't find any similar examples of this sort of assignment in any of the online C tutorials that I've seen.
If anyone can shed some light on it, I would really appreciate it!
|
```
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 to know why a very similar code doesn't work.
|
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 version is better than the other.
|
```
#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: unsigned conversion from 'int' to 'unsigned char' changes value from '292' to '36' [-Woverflow]
unsigned char c =292;
^~~
36 255
```
So,UCHAR_MAXin my system is 255, and that's the largest value you are allowed to assign toc.
292 just overflowsc, and because it's an unsigned type, it goes from 0 to 255, thus it wraps around, giving you 292 - (255 + 1) = 36.
|
```
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 *.
Thus, when you sayreturn y, you are not returning the contents of the arrayy- you are returning the value ofy, which is an address to the first element of theyarray.
So the return type of your function should bechar *.
|
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. And thus,INT_FAST16_MAXisINT32_MAX.
See also:
What's the difference between "int" and "int_fast16_t"?
|
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()
{
myStruct * ptr = &m1;
return ptr->inner;
}
int main()
{
innerStruct * retval = getMyStructPtr();
return 0;
}
```
Link to online compiler:https://onlinegdb.com/SJAFJCy0Z
|
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 innerStruct *
```
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.Closed5 years ago.Improve this question
I would like to use LibVLC in C++, but looking in the documentation I saw that a version named LibVLCpp existed.
Only impossible to find it. Does LibVLC work in C++ ?
|
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[] = "hello";
int i=0;
lol(s1,&i);
printf("%d", i);
_getch();
}
```
Could anyone perfome this but with recursion?
|
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 not valid C99+, but can I do this, exactly as it is, in C89? If not, how would I have to do this?
(fdoesn't have side-effects)
|
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, whether "legal"or not.
|
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 function ‘__builtin_isnan’
if (npy_isnan(k) || npy_isnan(n) || npy_isnan(p)) {
Ubuntu 16.04, Intel i7. For other work I have Anaconda 1.6.3 installed. Python 2.7.13 and gfortran.
I followed the setuphereandhere.
Any ideas? Maybe a gcc switch?
|
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 issue is fixed upstream.
|
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 = numElements();
pNode[numElem];
for(i = 0; i < numElem; i++){
pNode[i].number = (rand() % (MAX - MIN)) + MIN;
//c = (rand() % (MAX - MIN)) + MIN;
printf("P is %d\n",pNode[i].number);
printf("C = %d",c);
}
}
```
Main.c
```
Node *pNode;
LinkedList(pNode);
```
|
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, you need to look into SIMD.
You can check the remaining length of the array (values you have not inverted) in every iteration of the loop, and invert 64, 32, 16 or 8 bits at once, the biggest that fits.
|
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 Prefix_Conversion(char Infix_Postfix_Expression[]){
//some code here
}
```
It gives me an error of:
[Error] invalid conversion from 'char' to 'char*' [f-permissive]
[Note] initilizing argument of 1 if 'void Prefix_Conversion(char*)'
Is the prototype, arguments and array right?
|
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(string, " ");
while(fgets(string, sizeof(string), fpointer))
{
printf("%s" tokenp);
tokenp = strtok(NULL, " \n");
}
}
```
|
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 part is |%s|", ptr);
return(0);
}
```
Is the use of the uninitialized pointer inchar *ptrcorrect? If so, why isn't this a case of using an uninitialized pointer incorrectly?
|
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. one you can assign to) of typechar *to assign an address toptr.
|
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/local/ssl/include -o file file.c
```
If you were linking in libraries, something like the following format should work, assuming thatfile.ccalls a function inlibmyLib.a:
```
gcc -I/usr/local/ssl/include -o file file.c -L/path/to/my/library -lmyLib
```
Seethis questionfor more details regarding library linking order.
|
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 00:00:00 UTC), which should allow you to compare them with the C preprocessor's integer arithmetic. )
|
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() {
File * fpointer;
char name[MAX_NAME+5];
printf("Type name of program: ");
scanf("%40s", name);
strcat(name, ".txt");
puts(name);
return 0;
}
```
Demo.
|
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_tab;
```
thanks.
|
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 allocated it in the heap:
```
type_tab *some_tab = malloc(sizeof(type_tab));
```
Then the access will have to be done with:
```
some_tab->ready[1]->instruct[0]
```
|
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--);
```
So what is the possible consequences resulted from such a change?question
|
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 case.
In your example howeveriobviously cannot become negative...
|
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", 67 },
};
```
Sol:
Sort an array and then perform binary search. Thanks for the help people.
|
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 also the buffer content. That's why you get 64 printouts.
|
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 integer value of the scanned character
```
int main() {
int x, y, z, n;
n = scanf("%d", &x);
printf("n = %d\n", n); // prints 1
n = scanf("%d%d", &x, &y);
printf("n = %d\n", n); // prints 2
n = scanf("%d%d%d", &x, &y,&z);
printf("n = %d\n", n); // prints 3
return 0;
}
```
|
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_tab;
```
thanks.
|
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 allocated it in the heap:
```
type_tab *some_tab = malloc(sizeof(type_tab));
```
Then the access will have to be done with:
```
some_tab->ready[1]->instruct[0]
```
|
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--);
```
So what is the possible consequences resulted from such a change?question
|
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 case.
In your example howeveriobviously cannot become negative...
|
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", 67 },
};
```
Sol:
Sort an array and then perform binary search. Thanks for the help people.
|
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 also the buffer content. That's why you get 64 printouts.
|
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 integer value of the scanned character
```
int main() {
int x, y, z, n;
n = scanf("%d", &x);
printf("n = %d\n", n); // prints 1
n = scanf("%d%d", &x, &y);
printf("n = %d\n", n); // prints 2
n = scanf("%d%d%d", &x, &y,&z);
printf("n = %d\n", n); // prints 3
return 0;
}
```
|
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 skips datas from 350 to 4008. I need data from 350 to 350+349 to fill the next column and so on for the next columns too. However, I couldn't troubleshoot where the problem lies. Please help!
|
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)
printf ("%hd\t", su.shint[i*DATAPERROW+j]);
}
printf("\n");
}
```
|
```
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 write a function which takes in a function of type:
```
int (*cmp)(const char *, const char *)
```
and returns a function of type:
```
int (*qsortcmp)(const void *, const void *)
```
Is this possible? Have I been writing too much haskell? I would like to know.
|
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 text file tostdinand viascanfworks with them. But when I don't use the<textfile.txt"thing", it starts without the data. Instead, I'd like it to write an error and stop the program.
Thanks a lot.
|
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 globbing is done by the shell, seethis.
|
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 sys_hello(void)
|
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] = 0
disp[1] = sizeof(double)
block[0] = 1
block[1] = 1
MPI_TYPE_CREATE_STRUCT(2, block, disp, type, MPI_DOUBLE_INT)
```
note that inFortran, you have to useMPI_2DOUBLE_PRECISION(and yes, the index is a double precision in Fortran !)
this is explained inhttp://mpi-forum.org/docs/mpi-3.1/mpi31-report/node114.htm#Node114and there is even an example with double for bothCandFortran
|
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 with fscanf is that it's variadic. I can get all of the parameters passed into my function using va_list and va_arg, but how am I supposed to call the original fscanf on these parameters when I don't actually know how many parameters there are?
|
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);
return rc;
}
```
|
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" , &input[0], &input[1]);
for (i = 2; i < MAX_SIZE; i++)
{
input[i] = input[i-2] + input[i-1];
printf("%d\n", input[i]);
}
return 0;
}
```
But when i run the code with a input 2 and 3, I get a output like this1499141456, which is clearly not the sequence. please help.
|
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,sizeof(struct alloc));
(var -> data) = 'P';
printf("Data:%d",obj.data);
return (EXIT_SUCCESS);
}
```
|
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).
You can find more information on this topichere.
|
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 example
```
bool func(const char **p)
{ if (**p == NULL)
return false;}
```
I am not sure why it's complaining so. Isn't **p supposed to dereference the character value pointer *p points to? Or am I making confusion betweenNULLand'\0'?
|
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 exemple :
```
int main(){
// my string (from a file): printf("Hello, Stackoverflow!")
RunScript(MyStringScript);
return 0;
}
```
I could use clang or other, but I have no idea how to do that...
PS: The goal is not to make a C interpreter, no, just run a C code to broaden my program.
|
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 my array.
```
if (args[0][0] == '!'){
char str_index[1];
strcpy(str_index, &args[0][1]);
int index = atoi(str_index);
}
```
Also I haven't programmed in C a lot this is only my second program in C.
|
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 to avoid that behavior of the library (possibly by avoiding the library altogether) or to live with it.
|
```
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 % 10;
number /= 10;
tenth = number % 10;
number /= 10;
once = number;
```
Hopefully, the ability to roll this into a loop to solve a more general case is now obvious.
|
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 example
```
bool func(const char **p)
{ if (**p == NULL)
return false;}
```
I am not sure why it's complaining so. Isn't **p supposed to dereference the character value pointer *p points to? Or am I making confusion betweenNULLand'\0'?
|
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 exemple :
```
int main(){
// my string (from a file): printf("Hello, Stackoverflow!")
RunScript(MyStringScript);
return 0;
}
```
I could use clang or other, but I have no idea how to do that...
PS: The goal is not to make a C interpreter, no, just run a C code to broaden my program.
|
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 my array.
```
if (args[0][0] == '!'){
char str_index[1];
strcpy(str_index, &args[0][1]);
int index = atoi(str_index);
}
```
Also I haven't programmed in C a lot this is only my second program in C.
|
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 to avoid that behavior of the library (possibly by avoiding the library altogether) or to live with it.
|
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 dont see why Im getting infinite loop in here (LLLLLLLLL..). Stdin looks like this:
```
Lorem(newline)
Ipsum(newline)
Beach(newline)
Crocodile(newline)
Crox(newline)
C(EOF)
```
Any idea? thanks.
|
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 ofcrawler.
Result: The outer loop spins without reading any input.
|
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 countingnblines)
Your define could be useful, e.g. with later constructs like#ifdef true, and it can't be a simple#define truebecause that would "erase" every further use oftrue, so it has to be exactly#define true true.
|
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(void)
{
printf("Pi: %f\n", leibnizPi(1000));
return 0;
}
```
|
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
```
How is it possible that 25.15 - 0.75 gives me -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_BOXABLE CGPoint CGPoint;
```
So from my C days I remember defining a struct using typedef saves you from having to call it like so:
```
struct CGPoint{
}
```
And instead call it like this:
```
CGPoint{
}
```
But, what is the CG_BOXABLE and CGPoint? Is it like an inheritance thing or something? I'm referring to the first CGPoint.
|
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 new_reg into the rt field. I tried:
```
inst = inst | (new_reg << 16);
```
Could anyone confirm whether these two lines of code are correct?
|
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 in it
```
ldconfig -p | grep "curse"
libncursesw.so.5 (libc6,x86-64) => /lib/x86_64-linux-gnu/libncursesw.so.5
libncurses.so.5 (libc6,x86-64) => /lib/x86_64-linux-gnu/libncurses.so.5
libncurses.so.5 (libc6) => /lib/i386-linux-gnu/libncurses.so.5
libncurses.so.5 (libc6) => /lib32/libncurses.so.5
```
I don't understand why gcc is using the gnat ldfile instead of the system ldfile.
|
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 says "can't identify protocol"
The solution was to unwrap the SSL layer before closing:
```
origsock = socket.unwrap()
origsock.close()
```
This closes the sockets properly in my app.
I like to ask whatunwrap()does in python and how to do it in c ?!
|
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 new_reg into the rt field. I tried:
```
inst = inst | (new_reg << 16);
```
Could anyone confirm whether these two lines of code are correct?
|
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()
{
int i;
float x;
for (i=0;i>90;i=i+15);
{
x = sin(i);
printf("sin(%d)= %f\n", i, x);
}
getch();
return 0;
}
```
|
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-MM-DD HH:MM:SS like the one shown below?
```
2016-02-16 13:14:33.224487
```
I am new to c programming and have no clue what i am doing. Please help.
Thanks!
|
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 (){
#define MAX 1000
char arr [MAX] ;
char star [] = "Berlin ";
int i = 0;
while ((arr[i] = getchar()) != '\n') {
i++;
}
printf("%s%s", star,arr);
return 0;
}
```
|
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 you need to take into account.
|
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);
sscanf(" 281", "%3s%n", &str, &pos);
printf("%s %d\n", str, pos);
return 0;
}
```
It prints out the following.
```
281 4
281 4
```
I had thought it prints
```
28 3
28 3
```
Is this the correct use of sscanf? fscanf works in the similar way.
|
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 value6previously ina.
The other function returns a pointer and stores the pointer value iny. Nowyholds the value previously stored inp.
The problem is just that the pointer is now invalid (dangling), as the thingppointed to no longer exists.
|
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_sensor_t *) malloc(NUM_OF_SENSORS * sizeof(ds_sensor_t));
uint8_t count = ds18b20_read_all(pin, result);
```
But again I don't know NUM_OF_SENSORS. Should I just choose a large enough number?
EDIT:
The source code of the function:https://github.com/SuperHouse/esp-open-rtos/blob/master/extras/ds18b20/ds18b20.c
|
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 and Linux and when I print S_ISREG(path_stat.st_mode) is always equal to 1 and path_stat.st_mode is always equal to 16877.
|
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 symbol ones:
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.