question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I wrote the following program to understand the behavior of EOF:
```
#include<stdio.h>
int main ()
char c = 0;
printf("Enter some chars, EOF stops printing:");
while ((c == getc(stdin)) != EOF)
printf("c = %c, (int) c = %d\n", c, (int) c);
return 0;
}
```
However, if I input something s... |
You've got a==instead of a=so you never store whatevergetcreturns:
```
while ((c == getc(stdin)) != EOF) {
^^
```
And of coursecshould beint, notchar.
|
I need a random function for number betwen 11 and 99. I wrote this:
```
int random (void){
int i2;
i2=11+(rand()%99);
return i2;
}
```
but the numbers go over 99. Why?
|
Because ifrand()return98, then98 % 99is98and98 + 11 > 99.
To do this, you need
```
i2 = 11 + ( rand() % 89 );
```
rand() % 89will give you numbers[0, 88], so+11would become[11, 99].
By the way, don't forget tosrand( time( NULL ) ), otherwise it will (most probably) generate the same sequence of (pseudo) random n... |
I am currently working on a embedded C project and I "inherited" some old code containing statements such as:
```
rxStruct = rxStruct;
```
where rxStruct is a variable.
What could be the use of such statements?
|
Without further information, one use of such a statement is to prevent an unused parameter compiler warning ifrxStructis passed in as a parameter and then otherwise not used.
|
I am writing an LLVM pass which analyzes and modifies the generated IR code. Is there a way to identify backedges, I mean to know if a successor of a BasicBlock is actually somewhere above it in path.
|
Yes, there is.
First, note that you need to distinguish between "every path to BB must pass through A", and "there is some path from A that might lead to BB".
I think that you're looking for the first situation - tell if the successor A of the basic block BB is a basic block that the execution must pass through to g... |
I'm trying to learn C by playing with an Arduino Uno. I'm reviewing thecode for the Colorduino library on github. I'm wondering how++works when applied to a struct.
There is aPixelRGBstruct defined inColorduino.h:
```
typedef struct pixelRGB {
unsigned char r;
unsigned char g;
unsigned char b;
} PixelRGB;
``... |
Note, that this code incrementspointertoPixelRGB, not the struct itself.
So, the result of++when applied to pointer, is just incrementing its value bysizeof(PixelRGB)
|
When running this code in debug mode:
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
printf("Values entered: %d %d %d\n", a, b, c);
return EXIT_SUCCESS;
}
```
The program would not request any user input and would just output:
Values entered: 18 78... |
It seems the problem was caused byGDBwriting tostdinthe following line beforescanfwas run:
18-list-thread-groups --available
Andscanf("%d%d%d", &a, &b, &c);was interpreting that line as int's instead of waiting for user input.
The current solution I use is to clearstdinat the beginning of the program using:
```
in... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:Size of character ('a') in C/C++
OS: linuxmint 32-bit
Compiler: gcc & g++
I have try this code:
```
#include <stdio.h>
int main()
{
printf("%d\n",sizeof('a'));
return 0;
}
```
and I compile it with gcc , the result is4, and I ... |
Character constants are represented asintin C. When you are specifyingchartype, it's only 1 byte.
|
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void recursie(int);
int main(int argc, char **argv) {
recursie(3);
}
void recursie(int a){
if(a==0){return;}
recursie(a-1);
printf("%d",a);
recursie(a-1);
}
```
The output is : 1213121. Can someone explain me how i get to this output ?
|
```
recursie(3)
-calls recursie(2)
- calls recursie(1)
-calls recursie(0) -> void
-prints 1
-calls recursie(0) -> void
-prints 2
-calls recursie 1
-calls recursie 0 -> void
-prints 1
-calls recursie 0 -> void
-prints 3
-calls recursie(2)
- calls recursie(1)
-call... |
Does this implementation of node delete works, or it my fail ?
```
void remove_node(node *p)
{
node **i = &node_list;
for (;(*i) != NULL && ((*i) != p); *i = ((*i)->next)) ;
if (*i != NULL)
{
(*i) = (*i)->next;
}
if (p != NULL)
{
free(p);
}
}
```
BTW, as far as I know... |
No. It doesn't work. (yes I know, I cheated - initially I said it did).
As an interview question answer I'd start by listing the assumptions:
node_list starts out valid (and correctly NULL terminated)it is a singly linked listnodes are dynamically allocated
Issues are:
Loop will stop when*i == p. It needs to stop ... |
In this program I have swapped the first 2 names
```
#include<stdio.h>
void swap(char **,char **);
main()
{
char *name[4]={"amol", "robin", "shanu" };
swap(&name[0],&name[2]);
printf("%s %s",name[0],name[2]);
}
void swap(char **x,char **y)
{
char *temp;
temp=*x;
*x=*y;
*y=temp;
}
```
This programs runs perf... |
I assume you understand that to swap integers you would have function likeswap(int *, int *)
Similarly, When you want to swap strings which ischar *. You would need function likeswap(char **, char **).
In such cases, you take their pointers and swap their content (otherwise values will not be swapped once function r... |
I have a cpp function via an interfacefloat* decode()which returns pointers to raw data of a static vector.
Now in my c code I have a
```
float *value0;
value0 = (float*) malloc(M* sizeof(float) );
```
now when I do
```
value0 = work_decode1(h0, code0, 7, retain0);
```
I can only see the first value from the vect... |
float *is a pointer, not an array. The debugger doesn't have any idea how many elements it points to so it just shows you the first one.
In the watch window, you can specify the number of elements with this syntax:
value0,20
Where 20 is the number of elements you want to be visible.
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago.
What do the*and&symbols mean in thi... |
These:
```
*&*&
```
Are redundant and you would never encounter such ridiculous code in a real project. The ampersand takes the address ofp, and the asterisk*dereferences it to produce the originalchar*. Back and forth we go...
Think of it as:
```
*(&(*(&p)))
```
As an aside, your type-less signature formain... |
where can I find the realization code of the function __swtch_pri ?
```
void
__spin_lock_solid (spin_lock_t *lock)
{
while (__spin_lock_locked (lock) || ! __spin_try_lock (lock))
/* Yield to another thread (system call). */
__swtch_pri (0);
}
```
Only find declaration in glibc, see below.
```
/* Attempt ... |
It's in the Mach kernel. Specifically, see/hurd/gnumach/kern/syscall_subr.c. The GNU C library supports a great many operating system kernels other than just Linux and you've probably found this in one of the OS-specific source files.
|
```
float **tree0;
tree0 = (float**)malloc(255 * sizeof(float*));
for( i = 0; i < 255; i++)
tree0[i] = (float*)malloc(M * sizeof(float));
for(i = 0; i < 255; i++)
for( k = 0; k < M; k++)
tree0[i][k] = 2;
```
Should I just free it like this
```
free(tree0);
```
I am heap corruption errors somewher... |
You need to callfree()as many times as you calledmalloc()and on the same addresses which was returned bymalloc(). So, You just do it the way you allocated it:
```
for( i = 0; i < 255; i++)
free(tree0[i])
free(tree0);
```
|
As far as I've understood, when a program (written in C for example) is compiled, it is first translated into assembly language and then into machine language. Why can't (isn't) the "assembly language step" be skipped?
|
Your understanding is wrong, compilers do not necessarily translate C code into assembler. They usually perform several phases and have internal representations, but this doesn't necessarily resemble to a human readable assembler.
Here, I found a nice introduction forLLVM. LLVM is the compiler toolkit that is used fo... |
I stumbled across this code recently:
```
void strcat( char* dest, char* src )
{
while (*dest) dest++;
while (*dest++ = *src++);
}
```
Where it looks like the*dest++ = *src++operation is being used as a condition for the while loop. How is this assignment operation converted to boolean? I'm having a hard t... |
In C, a non-zero value in a logical statement counts as atrue, zero asfalse.
And the result of any assignment statement is the value of the left operand after the assignment.
And so in the second loop, if the value assigned is0, the result of the condition isfalse. In the first loop, if the value of the pointed-to v... |
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed11 years ago.
I have been programming for a few y... |
Bison is a parser generator. It takes it's input in something similar to Backus-Naur notation and outputs code to parse input according to that grammar. It lets you write a parser more easily than you would otherwise. Instead of having to do everything manually, you only have to specify the rules of your grammar and w... |
```
%{
#include <stdio.h>
#include <string.h>
void yyerror(const char *str)
{
fprintf(stderr,"error: %s\n",str);
}
int yywrap()
{
return 1;
}
int main()
{
yyparse();
}
%}
%token TOKMACHINE TOKLOGIN TOKPASSWORD VALUE SPACE NEWLINE
input: auth input | input;
delim: SPACE | NEWLINE;
auth: TOKM... |
Looks like you are missing the%%delimiter. Make that
```
%}
%token ...
%%
input : ...
```
|
I have the following code:
```
char buf[] = {0x45, 0x76, 0x72, 0x23, 0x12};
int main(void)
{
int i;
for (i = 0; i<=sizeof(buf); ++i){
printf("%c\n", buf[i]);
}
}
```
What I want to do is takebuf[i]when it is printed out and and make 0x45 read 0x46. Essentially, how do I add 1 to each value as it i... |
Use+
```
for (i = 0; i<sizeof(buf); ++i){
printf("%c\n", buf[i] + 1); // print the incremented value
//printf("%c\n", buf[i]++); // increment the printed value
}
```
|
I have a C++ program that shows an error:
```
too few arguments to function void split(char*, char**, int, int, int*)
```
Code:
```
#include <iostream>
#include <stdlib.h>
using namespace std;
void split(char* lin, char** word, int i, int w, int* c);
int main() {
char line[80] = "myline";
int n = 5;
char **... |
The function split takes 5 arguments and no default argument. You try to call it with 4 arguments. That wont work.
|
I have an array of objects in Java and I want to allow native C code direct access to that array (no copying or accessor functions). Is this possible? I don't mind if the solution is JVM-specific.
|
of course it is possible with JNI.
It's worth consulting this link :http://journals.ecs.soton.ac.uk/java/tutorial/native1.1/implementing/array.htmlin short -
```
#include <jni.h>
#include "IntArray.h"
JNIEXPORT jint JNICALL
Java_IntArray_sumArray(JNIEnv *env, jobject obj, jintArray arr)
{
jsize len = (*env)->Get... |
I defined a static struct in C like this:
```
typedef static struct {
int a;
int b;
} Hello;
```
Do I need to initiate the struct before I use it? How to access the variable inside of it?
|
You need to define the struct first, then instantiate it in a static variable
```
typedef struct {
int a;
int b;
} Hello;
static Hello hello;
```
Then you can access your data like this :
```
hello.a = 42;
```
|
I don't know what the compilar is doing with++*p;
Can anyone explain me pictorically what is going on inside the memory in this code?
```
int main()
{
int arr[]={1,2,3,4};
int *p;
p=arr;
++*p;
printf("%d",*p);
}
```
|
The answer should be 2
The reason is ++*p is is actually incrementing the first member in the array by 1.
|
I have a C++ program that shows an error:
```
too few arguments to function void split(char*, char**, int, int, int*)
```
Code:
```
#include <iostream>
#include <stdlib.h>
using namespace std;
void split(char* lin, char** word, int i, int w, int* c);
int main() {
char line[80] = "myline";
int n = 5;
char **... |
The function split takes 5 arguments and no default argument. You try to call it with 4 arguments. That wont work.
|
I have an array of objects in Java and I want to allow native C code direct access to that array (no copying or accessor functions). Is this possible? I don't mind if the solution is JVM-specific.
|
of course it is possible with JNI.
It's worth consulting this link :http://journals.ecs.soton.ac.uk/java/tutorial/native1.1/implementing/array.htmlin short -
```
#include <jni.h>
#include "IntArray.h"
JNIEXPORT jint JNICALL
Java_IntArray_sumArray(JNIEnv *env, jobject obj, jintArray arr)
{
jsize len = (*env)->Get... |
I defined a static struct in C like this:
```
typedef static struct {
int a;
int b;
} Hello;
```
Do I need to initiate the struct before I use it? How to access the variable inside of it?
|
You need to define the struct first, then instantiate it in a static variable
```
typedef struct {
int a;
int b;
} Hello;
static Hello hello;
```
Then you can access your data like this :
```
hello.a = 42;
```
|
I don't know what the compilar is doing with++*p;
Can anyone explain me pictorically what is going on inside the memory in this code?
```
int main()
{
int arr[]={1,2,3,4};
int *p;
p=arr;
++*p;
printf("%d",*p);
}
```
|
The answer should be 2
The reason is ++*p is is actually incrementing the first member in the array by 1.
|
How should i create my own Events (This includes the code to bind the necessary callback) in c/C++ programming? It is directly available in Java.
|
There aren't built-in events in C++, but if you don't want to reimplement your own classes, tryboost signals.
|
I've encountered a problem usingRSA_generate_key. The method generate the same public key in two different C sources. So these two sources are a client and a server of an application, compiled and running (for now) onlocalhost. How can I generate a different pair every time RSA_generate_key is called?
|
From RSA_generatey key manual:
The pseudo-random number generator must be seeded prior to calling RSA_generate_key().
You need call RAND_add with a start seed, if in linux you can read the seeds from /dev/random if you can wait for enough entropy or from /dev/urandom if you need a fast response.
You can learn more ... |
Hello all can someone help me with this piece of code
```
struct
{
unsigned BLOCKDATA:16;
unsigned QUALCOUNT:4;
unsigned BLOCKTYPE:2;
unsigned BE:1;
unsigned Z:1;
unsigned SYN:1;
unsigned DOK:1;
unsigned BM:1;
unsigned SYNDROME:5;
}
RDSout;
```
... |
This way you can declare how much bits you want reserved for that variable. It's commonly used to align data structures. Thewikipedia articlecontains a good explanation.
|
How to capture a parameter after some string in command line?
```
./executable.out -apps path_to_out
```
In the above code I want to store path_to_out in a string variable. What is the efficient way of doing that?
|
It kind of depends what kind of options you want. If you are willing to have only single-letter options, you can use the C library functiongetoptto parse the command line. If you would like long options (e.g.,--apps), you can usegetopt_long, but this is a GNU extension that will not port well. If you want really, real... |
I'm attempting to parse a text file backwards. I have the parsing done, now I'm trying to give my function a limit so that it doesn't read my entire 5Mb-2Gb log file. I'm passing this limit as a size_t and I was trying to think of a way to default the limit to read everything in the file.
since passing -1 to an unsig... |
In order to get the maximum possible value asize_tcan hold, usestd::numeric_limits. This would be the most portable way to do it:
```
#include <limits>
size_t max_value = std::numeric_limits<size_t>::max();
```
|
Is typeof in C, really an operator?I'm thinking because there is no polymorphism in C, that there is nothing to do at run-time. That is, the answer to typeof is known at compile-time. (I can't think of a use of typeof that would not be known at compile time.) So it appears to be more of a compile-time directive, tha... |
Sincetypeofis a compiler extension, there is not really a definition for it, but in the tradition of C it would be an operator, e.gsizeofand_Alignofare also seen as an operators.
And you are mistaken, C has dynamic types that are only determined at run time: variable modified (VM) types.
```
size_t n = strtoull(argv... |
I'm trying to do the following:
```
execl("/bin/grep","grep","print",fd,NULL);
```
where fd is a file descriptor.
So basically this should grep for "print" in the file pointed to by fd.
It doesn't seem to work although I get no compile errors/warnings.
It works when I give a filename such as"Something.txt"instead of... |
There are 2 issues:
You're seducingexeclinto using a small integer as a pointerYou're expectinggrepto understand file descriptors
If I understand your question correctly, right before youexec, you should redirect the descriptor intoSTDIN_FILENO. Something like:
```
dup2(fd, STDIN_FILENO);
execl("/bin/grep", "grep",... |
I am getting this error in my C code. I don't know what I am doing wrong. If I comment this code my program works.This piece of code is inside int main().
```
if(argc!=2 && strcmp(argv[0],"selection-sort")==0 && strcmp(argv[1],"input.txt")==0 && strcmp(argv[2],"output.txt")==0)
{
printf("The c... |
The way it looks I think you're not in a loop but just checking args in main. You probably want something likereturn 1orexit(1)instead of the break.
|
The purpose of O_NOCTTY is documented as :
O_NOCTTY - prevent the OS from assigning the opened file as the
process's controlling terminal when opening a TTY device file
Can somebody explain the intention of preventing a file as opening a controlling terminal ?
|
Having a controlling tty means there are certain conditions where specific signals might be sent to your program in response to things happening on the tty/window where your program is running. If the program is intended to be a daemon, it's generally cleaner to make sure you don't have a controlling tty than it is to... |
How should i create my own Events (This includes the code to bind the necessary callback) in c/C++ programming? It is directly available in Java.
|
There aren't built-in events in C++, but if you don't want to reimplement your own classes, tryboost signals.
|
I've encountered a problem usingRSA_generate_key. The method generate the same public key in two different C sources. So these two sources are a client and a server of an application, compiled and running (for now) onlocalhost. How can I generate a different pair every time RSA_generate_key is called?
|
From RSA_generatey key manual:
The pseudo-random number generator must be seeded prior to calling RSA_generate_key().
You need call RAND_add with a start seed, if in linux you can read the seeds from /dev/random if you can wait for enough entropy or from /dev/urandom if you need a fast response.
You can learn more ... |
Hello all can someone help me with this piece of code
```
struct
{
unsigned BLOCKDATA:16;
unsigned QUALCOUNT:4;
unsigned BLOCKTYPE:2;
unsigned BE:1;
unsigned Z:1;
unsigned SYN:1;
unsigned DOK:1;
unsigned BM:1;
unsigned SYNDROME:5;
}
RDSout;
```
... |
This way you can declare how much bits you want reserved for that variable. It's commonly used to align data structures. Thewikipedia articlecontains a good explanation.
|
How to capture a parameter after some string in command line?
```
./executable.out -apps path_to_out
```
In the above code I want to store path_to_out in a string variable. What is the efficient way of doing that?
|
It kind of depends what kind of options you want. If you are willing to have only single-letter options, you can use the C library functiongetoptto parse the command line. If you would like long options (e.g.,--apps), you can usegetopt_long, but this is a GNU extension that will not port well. If you want really, real... |
I'm attempting to parse a text file backwards. I have the parsing done, now I'm trying to give my function a limit so that it doesn't read my entire 5Mb-2Gb log file. I'm passing this limit as a size_t and I was trying to think of a way to default the limit to read everything in the file.
since passing -1 to an unsig... |
In order to get the maximum possible value asize_tcan hold, usestd::numeric_limits. This would be the most portable way to do it:
```
#include <limits>
size_t max_value = std::numeric_limits<size_t>::max();
```
|
Is typeof in C, really an operator?I'm thinking because there is no polymorphism in C, that there is nothing to do at run-time. That is, the answer to typeof is known at compile-time. (I can't think of a use of typeof that would not be known at compile time.) So it appears to be more of a compile-time directive, tha... |
Sincetypeofis a compiler extension, there is not really a definition for it, but in the tradition of C it would be an operator, e.gsizeofand_Alignofare also seen as an operators.
And you are mistaken, C has dynamic types that are only determined at run time: variable modified (VM) types.
```
size_t n = strtoull(argv... |
I'm trying to do the following:
```
execl("/bin/grep","grep","print",fd,NULL);
```
where fd is a file descriptor.
So basically this should grep for "print" in the file pointed to by fd.
It doesn't seem to work although I get no compile errors/warnings.
It works when I give a filename such as"Something.txt"instead of... |
There are 2 issues:
You're seducingexeclinto using a small integer as a pointerYou're expectinggrepto understand file descriptors
If I understand your question correctly, right before youexec, you should redirect the descriptor intoSTDIN_FILENO. Something like:
```
dup2(fd, STDIN_FILENO);
execl("/bin/grep", "grep",... |
I am getting this error in my C code. I don't know what I am doing wrong. If I comment this code my program works.This piece of code is inside int main().
```
if(argc!=2 && strcmp(argv[0],"selection-sort")==0 && strcmp(argv[1],"input.txt")==0 && strcmp(argv[2],"output.txt")==0)
{
printf("The c... |
The way it looks I think you're not in a loop but just checking args in main. You probably want something likereturn 1orexit(1)instead of the break.
|
The purpose of O_NOCTTY is documented as :
O_NOCTTY - prevent the OS from assigning the opened file as the
process's controlling terminal when opening a TTY device file
Can somebody explain the intention of preventing a file as opening a controlling terminal ?
|
Having a controlling tty means there are certain conditions where specific signals might be sent to your program in response to things happening on the tty/window where your program is running. If the program is intended to be a daemon, it's generally cleaner to make sure you don't have a controlling tty than it is to... |
Hi all can someone please tell me what does this line of code do
```
xdata.yarray[3] = *(ptr++);
xdata.yarray[2] = *(ptr++);
xdata.yarray[1] = *(ptr++);
xdata.yarray[0] = *(ptr++);
```
I am trying to figure out someone Else's code so having problems
would also appreciate if anyone could offer some useful point... |
Settingarrto the initial value ofptr, the code fills the valuesarr[0],arr[1],arr[2],arr[3]into the elementsxdata.yarray[3], ...,xdata.yarray[0]-- i.e. it copies a range of four elements in reverse order. As a side effect, it modifies the value ofptrso that it isarr + 4in the end.
Remember that*ptris the same asptr[0... |
I had a look at GtkGlExt, but it's only for GTK2. Unfortunately, after some hours of searching, it seems that no one take care of having something like an OpenGLDrawingArea…
Any information will be welcomed. Even if it's like "it's not possible for now".
|
It looks like you have a few options here.
Use an in-developmentport of gtkglext to gtk3Use SDL to draw into your GTK app by setting theSDL_WINDOWIDenvironment variableManage GLX yourself to create an OpenGL context for your GTK app.
I found a appspectrum3dwhich implements both of the first two alternatives.
The th... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:count number of files with a given extension in a directory - C++?
How to get the number of files in the specific folder using c or c++ function? Is there any c library function that could get the number of files in a given directory?
|
Here is a working example of opendir/readdir/closedir use (no recursion here):
```
void listdir(char *dir) {
struct dirent *dp;
DIR *fd;
if ((fd = opendir(dir)) == NULL) {
fprintf(stderr, "listdir: can't open %s\n", dir);
return;
}
while ((dp = readdir(fd)) != NULL) {
if (!strcmp(dp->d_name, ".")... |
I need to call cpp method from c file.
I have written this interface for that..
cpp file
```
extern "C" void C_Test(int p){
Class::CPP_Test(p);
}
```
c file
```
extern void C_Test(int p);
void C_Function(){
C_Test(10); //error
}
```
I get error in c file"undefined reference to C_Test(int)"
any idea wh... |
You must declare extern only for function prototype, and ensure to link correctly. In addiction to this, CPP_Test(p) must be a static member of Class, otherwise your code does not work. At last, extern "C" must enclose in brackets its content, more like
```
extern "C"
{
void C_Test(int p)
{
Class::CPP_Test(p)... |
I've got to read a date format (dd-mm-yyyy;) from a char* string using sscanf with this line of code:
```
sscanf(string, "%[^-]-%[^-]-%[^;];", day, month, year)
```
where day/month/year are char* string of 3/3/5 elemets each.
In this way it works but when i try to use day/moth/year asintegervariables (with samessca... |
You need to pass the address of theintvariables:
```
int day, month, year;
sscanf(string, "%d-%d-%d;", &day, &month, &year);
```
sscanf()returns the number of assignments made, recommend checking the return value before usingday,monthandyear:
```
if (3 == sscanf(string, "%d-%d-%d;", &day, &month, &year))
{
}
```
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Error: lvalue required in this simple C code? (Ternary with assignment?)
In the following piece of code I got an error like "lvalue required as left operand of assignment". I am unable to understand why such an error is being reported. But... |
Without your extra ()s, I think the operator precedence is grouping it as
((i > j) ? k = i : k) = j;
Which obviously isn't what you want and does have lvalue issues.
Fix it with
k = (i > j) ? i : j;
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:How do I tokenize a string in C++?
strtok function is not thread safe. Microsoft has Windows-specific strtok_s and CString::Tokenize safe functions. Is there cross-platform CRT/C++ library way to do this without manual coding?
|
boost::split.http://www.boost.org/doc/libs/1_51_0/doc/html/string_algo/reference.html#header.boost.algorithm.string.split_hpp
example of usage
```
#include <vector>
#include <string>
#include <boost/algorithm/string.hpp>
int main()
{
const std::string s = "hello and what";
std::vector<std::string> v;
boost... |
I want to exercise some UNIX commands using C language. When I include<unistd.h>header file and when I usefork()method it gives me a compile time error:"can not include unistd.h". I check on he Internet and thefork()method is available in<unistd.h>header file only. Please help me on this.
Is now<unistd.h>is replaced ... |
TheDOSBoxweb site says it is an emulation of DOS for Unix machines, not an emulator of Unix for Windows (DOS) machines. You needCygwinorMinGWor something similar if you want to emulate Unix on Windows.
|
I need to call cpp method from c file.
I have written this interface for that..
cpp file
```
extern "C" void C_Test(int p){
Class::CPP_Test(p);
}
```
c file
```
extern void C_Test(int p);
void C_Function(){
C_Test(10); //error
}
```
I get error in c file"undefined reference to C_Test(int)"
any idea wh... |
You must declare extern only for function prototype, and ensure to link correctly. In addiction to this, CPP_Test(p) must be a static member of Class, otherwise your code does not work. At last, extern "C" must enclose in brackets its content, more like
```
extern "C"
{
void C_Test(int p)
{
Class::CPP_Test(p)... |
I've got to read a date format (dd-mm-yyyy;) from a char* string using sscanf with this line of code:
```
sscanf(string, "%[^-]-%[^-]-%[^;];", day, month, year)
```
where day/month/year are char* string of 3/3/5 elemets each.
In this way it works but when i try to use day/moth/year asintegervariables (with samessca... |
You need to pass the address of theintvariables:
```
int day, month, year;
sscanf(string, "%d-%d-%d;", &day, &month, &year);
```
sscanf()returns the number of assignments made, recommend checking the return value before usingday,monthandyear:
```
if (3 == sscanf(string, "%d-%d-%d;", &day, &month, &year))
{
}
```
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Error: lvalue required in this simple C code? (Ternary with assignment?)
In the following piece of code I got an error like "lvalue required as left operand of assignment". I am unable to understand why such an error is being reported. But... |
Without your extra ()s, I think the operator precedence is grouping it as
((i > j) ? k = i : k) = j;
Which obviously isn't what you want and does have lvalue issues.
Fix it with
k = (i > j) ? i : j;
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:How do I tokenize a string in C++?
strtok function is not thread safe. Microsoft has Windows-specific strtok_s and CString::Tokenize safe functions. Is there cross-platform CRT/C++ library way to do this without manual coding?
|
boost::split.http://www.boost.org/doc/libs/1_51_0/doc/html/string_algo/reference.html#header.boost.algorithm.string.split_hpp
example of usage
```
#include <vector>
#include <string>
#include <boost/algorithm/string.hpp>
int main()
{
const std::string s = "hello and what";
std::vector<std::string> v;
boost... |
I want to exercise some UNIX commands using C language. When I include<unistd.h>header file and when I usefork()method it gives me a compile time error:"can not include unistd.h". I check on he Internet and thefork()method is available in<unistd.h>header file only. Please help me on this.
Is now<unistd.h>is replaced ... |
TheDOSBoxweb site says it is an emulation of DOS for Unix machines, not an emulator of Unix for Windows (DOS) machines. You needCygwinorMinGWor something similar if you want to emulate Unix on Windows.
|
I am trying to control Dynamixel servos using a GUI made using Qt. Dynamixel provides a C set ofC librariesto control the motors, while the only way of making GUI's I know is Qt, which is essentially C++. Will it be possible to use Dynamixel C libraries from Qt C++ code in any way?
|
Yes, C++ can compile C with a C++ compiler and you can link C++ against C. Just be sure that any C function you call uses C linkage. This is made by enclosing the prototype of the C function by anextern "C"
```
#ifdef __cplusplus
extern "C"{
#endif
void c_function_prototype();
#ifdef __cplusplus
}
#endif
```
The... |
How do I use dpkg commands in C? What headers/commands are available?
I tried a web search, but it mostly displays manpages for dpkg, and I don't see the said manpage mention anything C-related.
|
Unfortunately for you, dpkg provides a much better api for Perl or Ruby than for C. The package you want is libdpkg-dev, which provides the static library libdpkg.a. However, be warned that this library is volatile and intended for internal use only by the dpkg binary. Use at your own risk ;)
|
I wrote a simple application which compare strings. My problem is with white spaces. Here's the sample code:
```
int main(int argc,char *argv[]) {
if(strcmp(argv[1], "go up")==0){
printf("up up and away\n");
}
if(strcmp(argv[1], "down")==0){
printf("down you go\n");
}
return 0... |
Yes, you just have to escape it. In your case the program sees "go up" as two arguments.
Try this:
```
./try go\ up
```
|
I am trying to print the results of an MD5 hash to the console and it is working for the most part. To ensure correctness, I used an online MD5 calculator to compare results. Most of the characters are the same, but a few are missing in mine and they are are all leading zeroes.
Let me explain. The result is a 16 byte... |
Use"%02x".
The two means you always want the output to be (at least) two characters wide.
The zero means if padding is necessary, to use zeros instead of spaces.
|
I am a complete beginner in C programming, so please have some patience with me. I am trying to input a file name from the user in the console and I want to print a helpful message that prompts the user to enter the filename he wants to open. But when I run this in the command prompt, the cursor waits for the input fi... |
I do not see any issues with the code you have pasted, works fine with gcc. It must be something to do with the stdout not being flushed, which could be specific to the compiler you are using...
|
I have this piece of code for instance:
```
while(true){
printf("looping");
getch();
}
```
Instead of waiting for user input on each loop, the loop just continues without me; printing
```
loop
loop
loop
```
until I close the program.
Is there a better way to read a single character ? All i really want to ... |
Just use fgetc. I assume you're using this to break out of the loop, so to update your example:
```
#include <stdio.h>
char iput;
while(true){
printf("looping");
iput = fgetc(stdin);
if(iput == 'n')
break;
}
```
|
In the below code:
```
int a=5,b=6,c=7;;
int *const ptr = &a;
//if ptr = &b; is wrong since it is a pointer constant.
```
whether deferencing the pointer is applicable or not?
```
*ptr = 8; //is it allowed?
```
If not, then why?
Then in which places is the deferencing applicable?
|
```
int *const ptr = &a;
```
In this case the pointer is constant but the data to which it points is not constant.So you cannot make the pointer point to some other variable but you can modify the pointed value.
```
*ptr = 8;
```
is allowed because it only changes the value stored at the address to which the pointe... |
I need to check if the user entered a integer in a scanf() (in C). I have this code:
```
do {
srs = scanf("%d", &x);
} while (!srs);
```
If I enter a number it works and continues with the program, but if I enter a char, it just asks me for input again. Though, if then of this I enter a correct integer, it don't... |
When you don't enter the number first, it leaves the non-numeric character on the input stream for the next call to pick up. So you get in an infinite loop.
You should be usingfgetsto read a whole line of input, thensscanfon that input line.
```
do {
char line[512];
fgets(line,512,stdin);
srs = sscanf(li... |
I am using Keil. I have following files 'Driver.h' and 'Driver.c'.
Driver.h
```
extern static int Status[5];
```
I know that above statement is wrong. Meaning of static changes when it is declared globally. But still,
I want to declare a variable which is an array. It should be usable by another file and it should... |
Remove thestatic, to declare an externally located array. Then make sure that exactly one of the C files in the project actually define it, usingint Status[5];.
Not sure what you mean by "it should have scope in which value should not changed unless we change it", of course it won't change unless you change it ... It... |
```
bool somemethod(int number){
return true;
}
```
I keep getting this error message when I try to compile code with this method
```
/Users/user/Desktop/test.c:14: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘somemethod’
```
|
Thing isboolisn't a true keyword in C. Includestdbool.hif you need it - this should work with C99 implementations.
|
I have to declare an array of structures of size 16. The following code gives an error
code1.c:12:1: error: initializer element is not constant
```
typedef struct node
{
int tokenvalue;
struct node *next;
char *n;
} node;
node *dummy=(node *)malloc(26*sizeof(node));
```
Also using node dummy[26] gives segmentation... |
You can't initialize objects having static storage with anything non compile-time constant. Leave it uninitialized and assign some memory to it in a function.
|
I just wanted to know that there is any free stack usage analyzer for C, something likehttp://www.absint.com/stackanalyzer/index.htm
|
I think that gprof is a good tool.
http://www.cs.utah.edu/dept/old/texinfo/as/gprof.html
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:How can I delete a file pointed to by a FILE* in C?
I want to delete a file at the end of aCprogram, by which point the filename has been long forgotten. It would be nice if I could just use the FILE * to delete it directly or find the fil... |
nice if I could just use the FILE * to delete it directly or find the
filename and then use remove()... rather than having to memorize the
filename for this
There's no way to retrieve the file name from aFILE *. AFILE *isn't necessarily a real file; just think ofpopen(3)for example.
|
When I try to compile (on windows xp, with visual c++ 6.0) a c (NOT A C++) program which has the winusb.h header file, I get problems with c++ annotations (__in) like:
```
__in HANDLE DeviceHandle,
```
What do I need to get this compiled in c?
Thanks alot in advance!
|
Just ignore it (and the similar annoations):
```
#define __in
#define __out
#define __in_opt
```
|
From what I understand, the C language consists of a 4 stage compilation process:
On my Windows OS -
PreprocessorAssemblingCompilationLinking
I want to know if there are any differences between a C compiler and C++ compiler, in terms of the steps above. I believe that C++ can also consist of the above 4 stages.
Ar... |
The preprocessing and linking stages are basically the same (C and C++ share the preprocessor, and linking is done with no regard for the source language). The compilation/assembling phase is still there, but it has to be different - after all, we are dealing with a difference language here.
Edit: the details of C vs... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:what is the difference between const int*, const int * const, int const *constant pointer
Is there any difference between these two statements?
```
void * const sam;
```
and
```
void const *sam;
```
|
```
void * const sam;
```
the pointer is read-only. The qualifier is after the*.
```
void const *sam;
```
thepointeeis read-only. The qualifier is before the*.
|
Good morning,
Is it possible, using dyld interposition feature, to interpose this kind of C function ?
```
typedef struct aStructure {
IOReturn (*aCfunction)(void *self, UInt32 integer); // self is a
// pointer to aStructure
} aStructure;
```
How the func... |
Probably only possible if you can figure out where the actual function is, and interposethat.
There will be code to initialize the function pointer field in the structure to point at an actual function and I guess that's where you need to change things.
Also, you calling line is slighly off, it needs to be
```
(*my... |
I'm writing a C function to check if a socket connection from client is available. I use 'recv' function with MSG_PEEK not to alter the input buffer.
However, when the socket connection is closed by client, 'recv' is supposed to return -1, but it doesn't. After client closed, 'recv' in the function below returns 0 al... |
recv does NOT return -1 when the socket is closed properly, but rather '0'.
0 -> graceful closing of the socket
-1-> An actual error occurred
> 0-> Data has been read.
|
I am reading matrix through file with the help offscanf().
With thefscanf()I am able to extract the matrix from the file.
But I am not able to find out the column size of matrix.
input file is :12 3 -46 5 7
```
int main()
{
char arr[10],len;
int count=0;
FILE *input= fopen("input.txt", "r");
whil... |
first time, even if function getColumn try read.
```
int getColumn(FILE* fp){
char buff[BUFSIZ]={0};
int count=0;
char *p;
if(NULL==fgets(buff, BUFSIZ, fp))
return -1;
rewind(fp);
for(p=buff;NULL!=strtok(p, " \t\n");p=NULL)
++count;
return count;
}
...
FILE *input= fopen("... |
If I need to assign zeros to a chunk of memory. If the architecture is 32bits can assignment oflong long(which is 8 bytes on particular architecture) be more efficient then assignment ofint(which is 4 bytes), or will it be equal to two int assignments? And will the assignment ofintbe more efficient then assignment usi... |
Why not usememset()?
http://www.elook.org/programming/c/memset.html
(from above site)
Syntax:
```
#include <string.h>
void *memset( void *buffer, int ch, size_t count );
```
Description:
The function memset() copies ch into the first count characters of buffer, and returns buffer. memset() is useful for intializ... |
I have a program which depends onMSVCR90.dll, library which I'm shipping with it alongside the main executable among other things:
```
ProgramFolder\Main.exe
ProgramFolder\MSVCR90.dll
```
I wanted to know if when a new update to it is available (fixing a security issue for example) the one I supply would take preced... |
You can check theexecutables import headerto find which version of C runtime it has got references to. Removing it from system32 directory wont help, instead it will create a crash.
|
Functions likememPartInfoGet()requirePART_ID, in the manual it states thatmalloc()uses free lists of system memory partition. Is there a way to getstruct mem_part* PART_IDthat identifies with the system partition? To be able to use those functions?
|
memSysPartIdis what I was looking for.
|
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
The program is probably running. You'll need to kill it before recompiling.
|
I was writing a program and facing this problem that the following function used to return garbage values:
```
int* foo(int temp){
int x = temp;
return &x;
}
```
When I modified it to this, it worked fine:
```
int* foo(int *temp){
int *x = temp;
return x
}
```
What was wrong with the first version?
|
The first version returns a reference to a local variablexwhose storage is limited to the functionfoo. When the function exits,xcan no longer be used. Returning a reference to it is one instance of adangling pointer.
In the second version, you're really only passing in and returning the same pointer value, which refe... |
In a C/C++ program, is it correct for me to do this:
```
int i;
FILE **files = malloc(numFiles * sizeof(FILE *));
std::string file("foo"), ext(".bar");
char *num[10];
for (i = 0; i < numFiles; i++) {
files[i] = fopen((file + itoa(i, num, 10) + ext).c_str(), "w");
}
```
This is basically what I am doing, but I a... |
Sure they are blanked, you did not write anything, you simply open the file in writing mode!
You have to use the fwrite or fprintf function to write the data to the file and then close the file with fclose.
|
This program (in C) doesn't output what I'd expect:
```
int main()
{
int i, j ;
for ( i = 1 ; i <= 2 ; i++ )
{
for ( j = 1 ; j <= 2 ; j++ )
{
if ( i == j )
continue ;
printf ( "\n%d %d\n", i, j ) ;
}
}
}
```
I think it should be
```
1 2... |
Number 3 cannot be ever reached by the loops' indices.
|
Given this macro:
```
#define SOME_MACRO(ret, f, args) \
typedef ret (*some_func_##f) args; \
static some_func_##f my_func_##f = NULL;
```
Please let me know the equivalent for:
```
SOME_MACRO(void, myFunctionName, (int a));
```
Thanks.
|
You can use the-Eflag of gcc to see how the macro is expanded:
```
typedef void (*some_func_myFunctionName) (int a); static some_func_myFunctionName my_func_myFunctionName = ((void *)0);;
```
|
I need your help in writing a efficient program.
I have approx 50 functions saycall_1(),call_2()...call_50(). I need to call them based on the index read from a data packet, i.e if the field in data is 25 in need to callcall_25(), if 10 thencall_10().
I have written this in if else condition like
```
if (index == 5... |
Yes, use a lookup table of function pointers:
```
typedef void(*fp)(void);
void call_01(void);
void call_02(void);
/* ... */
fp functions[] = { &call_01,
&call_02,
/* ... */
};
void call()
{
unsigned int n = get_index();
functions[n]();
}
```
|
Can "#pragma omp parallel for" be used inside a loop in the following form:
```
For (i=0;i<...;.i+=1)
{ #pragma omp parallel for
for(j=0;j<...;j+=1)
{ Some code.....}
```
Will this just parralelize the loop on 'j' ?
Thanks on advence !
|
Yes, it can be used like that. But compiler directives have to be on a line of their own
```
for( ... )
{
#pragma omp parallel for
for( ...
//..
```
Also, this will indeed only execute the inner loop in parallel. If you need both loops to execute in parallel you need a second#pragma omp parallel forabove the... |
I have a question about enum variable in c++:
```
type enmu {
DAY1 = 1,
DAY2,
DAY3,
DAY4
} DAYS;
void main() {
DAYS days;
}
```
then what is the default value of days?
|
It's uninitialized andundefined behaviorto read the value.
Just like saying
```
int x;
```
xdoesn't have a value until you initialize it.
|
I am implementingmemset()method. Below is the code snippet:
```
void my_memset(void* ptr, int n, size_t size)
{
unsigned int i;
for( i = 0; i < size; ++i, ++(char*)ptr )
*(char*)ptr = n;
}
```
I am getting theerroras:
```
prog.cpp: In function ‘void my_memset(void*, int, size_t)’:
prog.cpp:8: e... |
```
void my_memset(void* ptr, int n, size_t size)
{
char *cptr = (char *)ptr;
char *limit = cptr + size;
for(; cptr < limit; cptr++) {
*cptr = n;
}
}
```
you can't increment through a cast like that, and you shouldn't want to.
|
How to return 1000 variables from a function in C?This is an interview question asked which I was unable to answer.
I guess with the help of pointers we can do that. I am new to pointers and C can anyone give me solution to solve this problem either using pointers or different approach?
|
Pack them all in a structure and return the structure.
```
struct YourStructure
{
int a1;
int b2;
int z1000;
};
YouStructure doSomething();
```
|
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... |
Yes there is.
Its called WinUSB -http://msdn.microsoft.com/en-us/library/windows/hardware/ff540196(v=vs.85).aspx
Sample WinUSB code found here -http://msdn.microsoft.com/en-us/library/windows/hardware/ff540174(v=vs.85).aspx
|
I am having this code snippet:
```
struct stat *fileData;
if((fd=open("abc.txt",O_RDONLY)==-1)
perror("file not opened");
if((fstat(fd,fileData)==-1)
perror("stucture not filled");
printf("%d",fileData.st_size);
```
It shows me error:
```
request for member ‘st_size’ in something not a structure or unio... |
As it stands you're writing (fstatis) to an uninitialized pointer and then trying to read from it as if it were astruct stat. You should change your code to:
```
struct stat fileData;
if((fstat(fd, &fileData) == -1)
^
```
Alternatively you couldmallocmemory tofileDataand then usefileData->st_size. This... |
I'm migrating a script from C to PHP (http://svn.stellman-greene.com/mgrs_to_utm/trunk/) and I have a problem with this concept inmgrs_to_utm.c:
```
Letters[0] = (toupper(MGRS[j]) - (long)'A');
if ((Letters[0] == LETTER_I) || (Letters[0] == LETTER_O))
```
MGRS[j]is a part of string, but WTF I can substract a(long)'A... |
In ASCII, the character 'A' has value 65, so Letters[0] effectively contains an offset into the alphabet (A being 0).
If MGRS[j] is 'I' (73) then we take 'A' (65) from it to leave 8
```
A B C D E F G H I J K...
0 1 2 3 4 5 6 7 8 9 10
```
The code is pretty much the same as:
```
if ( MGRS[j] == 'I' || MGRS[j] == 'O... |
I'm usingthis implementationof SHA1 in C. Works fine on Windows but it does not output correct hashes on Unix (tried it on Ubuntu and Mac OS 10.8). Furthermore, on Ubuntu it outputs different hash from the same message.
I guess I could use another implementation, just curious why that happens.
EDIT
Thanks, you guys... |
Are these 64bit unix'es?
```
/* UINT4 defines a four byte word */
typedef unsigned long int UINT4;
```
will actually be 8 bytes on 64 bit Linux (but 4 bytes on 64 bit Windows)
https://en.wikipedia.org/wiki/64-bit_computing#64-bit_data_models
|
I am having some memory leaking troubles in an embedded application and while looking in the code, I see I do notfreeaddrinfo()whengetaddrinfo()returns non-zero:
```
s = getaddrinfo(hostname, port, &hints, &result);
if (s != 0) {
log_error();
} else {
// do stuff
freeaddrinfo(result);
}
```
Could this lead to ... |
The specification doesn't say thatresultisn't assigned if it fails, so it appears that a conforming implementation could do so.
Why not free it unconditionally?
```
result = 0;
s = getaddrinfo(hostname, port, &hints, &result);
if (s) {
// log error
} else {
// success
}
if (result) {
freeaddrinfo(result)... |
I saw this code inthis .c file.
```
struct node {
Item data;
struct node *next;
};
struct stack_type {
struct node *top;
};
```
What are the benefits of creating two structs when one would do?
|
It may make the code clearer to distinguish between the whole stack and a single node.
|
We have
```
int main(int argc, char** argv, char** envc)
```
for the ordinary. but I want to know if there is any other argument main can have instead of these. And if there is any, what does it point to?
|
Well, heres the breakdown:
argc-- C standardargv-- C standardenv-- Works on most UNIX and MS Win, but not standardapple-- Other information passed as forth argument by Mac OSX and Darwin
|
I'm an Arduinopadawanlearner. I want to pass a byte array to a function and get the size of the array.
```
byte data[] = {
B00000000,
B00000001,
B00000011,
B00000111
};
Serial.println(sizeof(data)); // ----------------------> displays 4
```
When I pass it to a functionsizeofreturns 2. How can I get ... |
When e.g. passing arrays as parameters, the compiler no longer has the size of the array. Instead the array gets passed as a pointer, and inwriteDatathesizeofoperation gets the size of the pointer and not the array (or whatever) it points to.
|
I am getting an error when I run the executable:
```
(a.out:6815): GooCanvas-CRITICAL **: goo_canvas_item_get_parent: assertion `GOO_IS_CANVAS_ITEM (item)' failed
```
I want to find out which function call is leading to this warning (since I am not calling the above function), I tried running with gdb but didn't sho... |
Try to addG_DEBUG=fatal_criticalsto your environment. This way, your program will abort() when a critical error occurs, so your gdb can point you where the assertion fails.
That, or adding a breakpoint to theg_criticalfunction.
|
How can I keep track of time with sub second precision. Can you guys provide me with some ideas and strategies. Also, the pros and cons of each, I am trying to implement this for a hard real-time system using a Linux kernel. The Linux clock() function is not accurate enough since its precision is by seconds.
|
You can useclock_gettime()to return astruct timespec:
```
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
```
The actual resolution is typically not anywhere near nanoseconds but should get you into the millisecond range or better.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.