question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I've got a string declared like this:
```
str=malloc(sizeof(char)*128);
```
I want to clear it completely so that whenI dostrncat()operation, the new characters will be written to the beginning ofstr. The reason I need to clear it is that I'm writing over it with a simplified version of itself (deleting excess whit... |
I suggest you simply do this:
```
*str = '\0';
```
You don't need to clear the entire contents of the buffer. You can just set the firstcharto zero and then you have the empty string.
|
I may be blamed of duplicatingthisorthisor even any ofthesebut really no one answers my issue. I need to launch an app by clicking on a button on my UI, but the application i want to launch has no customURL Schemeand here my nightmare gets started. I tried to call the app(using NSBundle-path) ect but i could see no wa... |
There are 3 ways to open an app from your app on iOS:
URL schemesUsing the UIDocumentInteractionController to allow the user to open a file in another appUsing private API's
Simple. No there is no registry like system on iOS.
|
I am looking to use theDynaPDFin my Android project as a C library. However on the downloads page the only option I can see that could be used is "DynaPDF for linux for x86 (32)", as I understand it x86 is based on architecture where as Android use ARM architecture. I am quite new to native programming and so would ap... |
To port the library, you must have access to the sources (the download page of DynaPDF has links to the compiled libraries, which is not very useful).
|
If the file is .c MSVC will compile.
If it's .cpp it"cannot convert from 'void *' to 'unsigned char *'"
I'm using theMEMORY_BASIC_INFORMATION::BaseAddressinwindows.hwhich isvoid*, assigning it to achar*so I can see the actual address you know?
When I cast it to char*, and later back tovoid*(to use it in windows fun... |
In C++, you must use an explicit cast to convert avoid*to anything else:
```
void *vp;
unsigned char *cp = static_cast<unsigned char *>(vp);
```
This is indeed different from the situation in C, where avoid*can be implicitly converted to any other pointer type. The reverse situation is still as in C:
```
void *vp =... |
How can I "compile" Objective-C Code to (only) C-Code?There is a way to preprocess Objective-C in Xcode (Product -> Generate Output -> Generate Preprocessed File), but this is not what I'm looking for...
Thanks...
|
clang (the compiler front-end used by Xcode nowadays) has a-rewrite-objcoption built-in, which allows you to generate C++ code based on Objective-C (or Objective-C++) code.
Just don't ask me how to combine that with Xcode.
|
I have this code
whitespaces is a type int, so I can use the getchar function
```
do
{
...code...
whitespaces=getchar();}
while ( whitespaces != (EOF) || whitespaces!='\n');
```
but it doesnt exit the loop when i hit CTRL+Z (i am using windows 7)
what am I doing wrong?
EDIT : thank you, all of you...! very hel... |
You must use&&instead of||in thewhilecondition.
|
```
#include <stdio.h>
void main(){
char *str[]={"aa","bb"};
str[0][0]='h';
}
```
I receive a segmentation fault when executing this code. Does anyone know the reason?
Thanks in advance.
|
You are assigning to a location occupied by a string constant, an undefined behavior. If you know the max lengths of your strings, you can do this:
```
char ss[][3] = {"aa", "bb"};
```
It's not a precise equivalent, but it should work. If you do not know max length, or do not want to waste a few bytes here and there... |
I've got a string declared like this:
```
str=malloc(sizeof(char)*128);
```
I want to clear it completely so that whenI dostrncat()operation, the new characters will be written to the beginning ofstr. The reason I need to clear it is that I'm writing over it with a simplified version of itself (deleting excess whit... |
I suggest you simply do this:
```
*str = '\0';
```
You don't need to clear the entire contents of the buffer. You can just set the firstcharto zero and then you have the empty string.
|
I may be blamed of duplicatingthisorthisor even any ofthesebut really no one answers my issue. I need to launch an app by clicking on a button on my UI, but the application i want to launch has no customURL Schemeand here my nightmare gets started. I tried to call the app(using NSBundle-path) ect but i could see no wa... |
There are 3 ways to open an app from your app on iOS:
URL schemesUsing the UIDocumentInteractionController to allow the user to open a file in another appUsing private API's
Simple. No there is no registry like system on iOS.
|
I am looking to use theDynaPDFin my Android project as a C library. However on the downloads page the only option I can see that could be used is "DynaPDF for linux for x86 (32)", as I understand it x86 is based on architecture where as Android use ARM architecture. I am quite new to native programming and so would ap... |
To port the library, you must have access to the sources (the download page of DynaPDF has links to the compiled libraries, which is not very useful).
|
I have this code
whitespaces is a type int, so I can use the getchar function
```
do
{
...code...
whitespaces=getchar();}
while ( whitespaces != (EOF) || whitespaces!='\n');
```
but it doesnt exit the loop when i hit CTRL+Z (i am using windows 7)
what am I doing wrong?
EDIT : thank you, all of you...! very hel... |
You must use&&instead of||in thewhilecondition.
|
```
#include <stdio.h>
void main(){
char *str[]={"aa","bb"};
str[0][0]='h';
}
```
I receive a segmentation fault when executing this code. Does anyone know the reason?
Thanks in advance.
|
You are assigning to a location occupied by a string constant, an undefined behavior. If you know the max lengths of your strings, you can do this:
```
char ss[][3] = {"aa", "bb"};
```
It's not a precise equivalent, but it should work. If you do not know max length, or do not want to waste a few bytes here and there... |
I've got a string declared like this:
```
str=malloc(sizeof(char)*128);
```
I want to clear it completely so that whenI dostrncat()operation, the new characters will be written to the beginning ofstr. The reason I need to clear it is that I'm writing over it with a simplified version of itself (deleting excess whit... |
I suggest you simply do this:
```
*str = '\0';
```
You don't need to clear the entire contents of the buffer. You can just set the firstcharto zero and then you have the empty string.
|
I may be blamed of duplicatingthisorthisor even any ofthesebut really no one answers my issue. I need to launch an app by clicking on a button on my UI, but the application i want to launch has no customURL Schemeand here my nightmare gets started. I tried to call the app(using NSBundle-path) ect but i could see no wa... |
There are 3 ways to open an app from your app on iOS:
URL schemesUsing the UIDocumentInteractionController to allow the user to open a file in another appUsing private API's
Simple. No there is no registry like system on iOS.
|
I am looking to use theDynaPDFin my Android project as a C library. However on the downloads page the only option I can see that could be used is "DynaPDF for linux for x86 (32)", as I understand it x86 is based on architecture where as Android use ARM architecture. I am quite new to native programming and so would ap... |
To port the library, you must have access to the sources (the download page of DynaPDF has links to the compiled libraries, which is not very useful).
|
I am trying to get all the input from the command line and putting it in a linked list.
the numbers from the command line are of this format 0-1 2-3 4-9 etcc
Here is what I did to store a pair of numbers in two variables:
```
scanf("%d-%d", &a, &b);
```
Now, this scanf statement is inside a loop and my question is: ... |
A famous, if not notorious characteristic ofscanfis that it will leave data in input buffer when reading non-string data(e.g,int). Check out here:Leave data in input buffer.
Try this:
```
do
{
int x = scanf("%d-%d", &a, &b);
}while ((x != EOF) && (getchar() != '\n'));
```
You need to comparescanfoutput with EOF. ... |
I want to insert•into GtkTextView widget. In Python + pyGTK this line was sufficient:
```
self.__textBuffer.insert_at_cursor(u'\u2022')
```
Because I'm rewriting my application to C i need to translate this line of code.
I was trying to do:
```
gtk_text_buffer_insert_at_cursor(textBuffer, "\x20\x22", 2);
```
But ... |
You need to UTF-8 encode it, since GTK+'s encoding is UTF-8.
Thus:
```
const char bullet_utf8[] = "\xe2\x80\xa2";
gtk_text_buffer_insert_at_cursor(textBuffer, bullet_utf8, strlen(bullet_utf8));
```
You can see the UTF-8 encoding of this characterhere, for instance.
|
I came across the following line of code :
```
memcmp(mac, (char []){0x01,0x00,0x5E}, 3)
```
Maybe it will work ; Is it alright to code memcmp in the above manner ? Thanks.
|
Yes, it will work, no problem, it's the same as:
```
char arr[] = {0x01,0x00,0x5E};
memcmp(mac, arr, 3);
```
|
I am trying to understand pointers in C but I am currently confused with the following:
char *p = "hello"This is a char pointer pointing at the character array, starting ath.char p[] = "hello"This is an array that storeshello.
What is the difference when I pass both these variables into this function?
```
void prin... |
char*andchar[]are different types, but it's not immediately apparent in all cases. This is because arraysdecay into pointers, meaning that if an expression of typechar[]is provided where one of typechar*is expected, the compiler automatically converts the array into a pointer to its first element.
Your example functi... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:How do you determine the size of a file in C?
How can I obtain a file's size in C? I opened with an application written in C. I would like to know the size, because I want to put the content of the loaded file into a string, which I alloc ... |
You can use the fseek and ftell functions:
```
FILE* f = fopen("try.txt","rb");
fseek(f, 0, SEEK_END);
printf("size of the file is %ld", ftell(f));
```
|
Well, I'm trying get some values fromplaces.sqlitedatabase. But when I do
$ sqlite3 /home/<user>/.mozilla/firefox/xx.default/places.sqlite "SELECT url FROM moz_places"
I get the following error:Error: file is encrypted or is not a databasehow to fix this?
|
Most likely, there is a version mismatch between the sqlite3-library used by the "sqlite3" command, and the one firefox is using. On my laptop the command you quoted execute without errors. (Ubuntu 10.10, Firefox 11.0, libsqlite3-0 3.7.2-1ubuntu0.1)
(Ref:Error: file is encrypted or is not a database)
|
Yo. I have this extremely simple swap function that seems to not work. Probably a pointer issue so any advice would be nice.
```
void swap(pQueue *h, int index1, int index2) {
student *temp = &h->heaparray[index1];
h->heaparray[index1] = h->heaparray[index2];
h->heaparray[index2] = *temp;
}
```
pQueueis a ... |
You need to copy the actual value ofh->heaparray[index1](not its address) intotempand then later copy that value intoh->heaparray[index2], like so:
```
void swap(pQueue *h, int index1, int index2) {
student temp = h->heaparray[index1];
h->heaparray[index1] = h->heaparray[index2];
h->heaparray[index2] = temp; ... |
I am working on an adaption of the code shownhere, however, instead of using individual values I want to create an enum of possible values.
I would like to keep this in the header file if possible, and I would like it to include the values something like...
```
enum Notes{
NOTE_B0 = 31,
NOTE_C1 = 33,
NOT... |
The best you can do is create a static const array of all the enum values somewhere and iterate through that. If the enum values were all consecutive you could obviously iterate through them easily enough, but short of that you're out of luck.
|
I am using glColor4f(). Surprisingly, changing the alpha, i.e., the fourth argument doesn't cause any change in transparency. The code segment is:
```
const GLfloat squareVertices[] = {
0.5, 0.5, 0.0,
-0.5, 0.5, 0.0,
0.5, -0.5, 0.0,
-0.5, -0.5, 0.0};
glEnableClientState (GL_VERTEX_ARRAY);
glClear(GL_COLOR_BUFFER... |
You need to enable blending if you want to use transparency:
glEnable(GL_BLEND);
See alsoglBlendFuncto setup the blending function.
|
Trying to learn C. Want to read the first line of a text file, my code is:
```
#include <stdio.h>
int main()
{
FILE *in = fopen("test.txt", "rt");
// read the first line from the file
char buffer[100];
fgets(buffer, 20, in);
printf("first line of \"test.txt\": %s\n", buffer);
fclose(in);
... |
try this afterfopen()call:
```
if(in == NULL){
printf("Can't read teste.txt because: %s.\n", strerror(errno));
return 1;
}
```
and add the headers:
```
#include <errno.h>
#include <string.h>
```
|
Where can I found theplaces.sqlitefile database on Ubuntu/Linux 10.4, Firefox 5.0 (X11)?
I want read the open urls on firefox using C. But I not found the file. I tried followingthese instructions, but the.mozilladir does not exists in/home/<user>/folder.
|
Try:
```
find / -name 'places.sqlite'
```
In my system the answer was:
```
/home/edu/.mozilla/firefox/qk8lh1kf.default/places.sqlite
```
|
I'd like to execute a simple POST request using libsoup. The api of the website i'd like to send data to requires only one field named 'content'. With curl i do this:
```
curl -si -F 'content=mycontent' http://mywebsite.org/api
```
How can I do the same with libsoup?
|
Google probably does this better for you than me. Here is a link with the libsoup client basics.http://developer.gnome.org/libsoup/stable/libsoup-client-howto.html
From there you should try something similar to
```
guint status;
SoupMessage *msg;
const char * mycontent; //alloc and fill this with your data
msg = sou... |
I am new to C++ and i am trying to learn pointers.
As a working exercise i try to read a nxn matrix using pointers to pointers.
This is what i have tried so far, but the scanf is failing.
What am i doing wrong?Later edit:
```
int **matrix;
int i=0;
int j=0;
int li=0;
int dim;
printf("What is the dimmension:");
scan... |
If you are using C++ this better do like this
```
matrix = new int*[dim];
for(int = 0; i < dim; ++i)
matrix[i] = new int[dim];
// to read matrix
scanf("%d", matrix[i][j]);
```
|
I'm trying to implement BigInt and have read some threads and articles regarding it, most of them suggested to use higher bases (256 or 232or even 264).
Why higher bases are good for this purpose?
Other question I have is how am I supposed to convert a string into higher base (>16). I read there is no standard way, ... |
The CPU cycles spent multiplying or adding a number that fits in a register tend to be identical. So you will get the least number of iterations, and best performance, by using up the whole register. That is, on a 32-bit architecture, make your base unit 32 bits, and on a 64-bit architecture, make it 64 bits. Otherwis... |
For using openSSL API for public key encryption, how is the key (public & private) initialized in a C program, given private key in *.key file format, and public key in *.pem file format:
```
EVP_PKEY *key;
/* How is key initialized ?
*/
ctx = EVP_PKEY_CTX_new(key);
```
Thanks.
|
try this:
```
EVP_PKEY *pkey;
FILE *f = fopen("<path for your PEM or DER encoded key>", "rb");
if (f == NULL){
// error handling...
}
//if your key is PEM encoded use this
pkey = PEM_read_PUBKEY(f, NULL, NULL, NULL); // pkey now contains the pubKey.
//We are pa... |
How do I execute a R command in C, without using R extensions, something like:
```
int main() {
system("R g<- graph(c(0,1,0,4,0,9,1,7,1,9,2,9,2,3,2,5,3,6,3,9,4,5,4,8,5,8,6,7,6,8,7,8),n=10,dir=FALSE)
plot(g)")
return(0)
}
```
|
You can run R using the system() call as you have, but you can't stick R functions on the command line like that.
What you can do is to write the R code to a file and call it withsystem("R CMD BATCH foo.R")- minimally:
```
main(){system("R CMD BATCH test.R");}
```
Now, by default the output graphics from R CMD BATC... |
Consider the following code:
```
#include <stdio.h>
int aaa(char *f, ...)
{
putchar(*f);
return 0;
}
int main(void)
{
aaa("abc");
aaa("%dabc", 3);
aaa(("abc"));
aaa(("%dabc", 3));
return 0;
}
```
I was wondering why the following lines:
```
aaa("abc");
aaa("%dabc", 3);
aa... |
The statement
```
aaa(("%dabc", 3));
```
calls the functionaaawith the argument("%dabc", 3)which returns the value3.
Look up thecomma operatorfor more information.
|
I have an array 'y' with x no. of elements inside it (the number 'x' is given by user), I need to create an array of structures which has elements of exactly the same type as that in array 'y' i.e the array of structures would have 'x' elements.
|
If I understand you right, you have an "array" of some type, and the number of elements is decided by the user. I'm guessing you allocate it usingmalloclike this:
```
type_of_y *y = malloc(x * sizeof(type_of_y));
```
And now you want to create a similar "array" from a structure, with the same number of elements. Why... |
I'm a newbie in mySQL programming, and seems to have encountered a very basic problem.
I have the following code, but got segmentation fault at the "create database" part.
```
MYSQL *s1;
MYSQL mysql_sense;
char strBuf[8192] = {0};
char DB_NAME[300] = "0_4_3";
mysql_init(&mysql_sense);
sprintf(strBuf, "CREATE DATAB... |
You don't do amysql_connect()or amysql_real_connect().You don't check the return value ofmysql_init().
|
I have the following code
```
int myInt;
sscanf(str, "%d=%s", &myInt, str);
```
Will this be valid? Is there a better way to do this if I have it in a loop?
|
My guess is that this wil usually work because it seems like the source string will always be >= the result string, and that would seem to cause deterministic and as-specified results.
But I still wouldn't do it. Library functions typically haverestrict-qualified parameters in order to allow for optimizations and pr... |
Even after years of C, pointers still confuse me.
Are these two the same:
```
int *num;
someFunc(num)
```
and
```
int num;
someFunc(&num);
```
Declaring a variable with*makes it a pointer,&turns a variable (momentarily) into a pointer?
|
No they are not the same. In the first case you have a pointer which is pointing to some random memory location (as you have not initialized it). In the second case, the pointer obtained insomeFuncwill be pointing to a valid location (the address of variablenum).
|
I know that in the past there was an option-fprefix-function-namethat would add a prefix to all generated symbols, it doesn't seem to be part of gcc anymore. Is there any other way to do this?
|
I believethis answerwill give you the solution.
In short, you can 'prefix' symbols in an existing library usingobjcopylike this:
objcopy --prefix-symbols=foo_ foo.o
|
experts...
I have a little questions. I want to create a client for Jack audio server and when I want to get a buffer to write into it like this:
sample_t *out = (sample_t *) jack_port_get_buffer(output_port, nframes);
i get this:
error: 'sample_t' was not declared in this scope
I don't know what to do because I ... |
did you typedef the original variable name of jack?
```
typedef jack_default_audio_sample_t sample_t;
```
Most of the time,sample_twill be too generic for a variable name in a library, that's why they "rename" it to sample_t.
|
I found this in a multi-threaded c application. The authors commented that it's used to make a thread crash in a custom assert function. GCC is fine with it, but clang issues the following warning:
```
note: consider using __builtin_trap() or qualifying pointer with 'volatile'
```
and also issues one of those, for e... |
Writing toNULLaddress is not guaranteed to crash your program reliably, soGCC introduced__builtin_trapfor that.
It looks like clang decided to go further, and eliminate such writes altogether, almost forcing you into using__builtin_trap. Their other option of castingNULLtovolatilepointer does not look attractive comp... |
I am generating random numbers by using srand(time(NULL)).
Any idea why it always gives just even random numbers? In my case its giving so. Please help i need odd numbers too.
I need the set of 0s, 1s.
for eg : {1,1,0,0,1,0,0,0,1,1,0}
|
Call
```
srand(time(NULL));
```
only one time at the beginning of your program, it "shuffles" the random sequence.
Then call
```
rand();
```
And it will return a number in the range0toRAND_MAX.
If you want only 0 or 1 then you can try with
```
int n = rand() % 2;
```
or
```
int n = rand() & 0x01;
```
|
This is some sample code fromThe C Programming Language by Ritchie & Kernighan.
```
int c;
while((c=getchar())!=EOF) {
putchar(c);
}
```
Notice that putchar referes to a variable of typeint. Why is it possible to return and display both characters and integers with this code?
|
Anintis usually represented by 4 bytes while acharis actually just 1 byte of data. You can easily store a full character and more in the singleintthatgetchar()returns. When an int is passed toputchar(int)it just lops off the extra space before displaying it. This technique is useful for passingEOFwhich is actually not... |
Is it possible to use function expressions in C? For example, I have the following code snippet (inside themainfunction):
```
void print_line(char *data) {
printf("%s\n", data);
}
// print all elements in my_list
list_foreach(&my_list, print_line);
```
I'd like to do something like this instead:
```
list_foreach... |
In a word, No. At least not in a Javascript-like syntax. Function pointers are as close as your are going to get. There is very little difference between the two syntactically. If you are looking for the behavior of closures or inner functions, then you definitely are not going to see them soon.
|
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 want to know the tools that beaut... |
You're going to have to ask a better question. What platform are you targeting? What framework are you using? "Beautiful" is in the eye of the beholder.
|
How does one idiomatically "pop" from the start of asingly-linked list in GLib? There are several functions that can be glued together but don't stand out as the intended inverse ofg_slist_prepend.
|
Depending on your use case, either
```
// pop and discard head
list = g_slist_delete_link(list, list);
```
or
```
// pop head but keep it for further use
GSList *head = list;
list = g_slist_remove_link(list, head);
// do stuff with head
g_slist_free1(head);
```
|
I know that you can align variables to a cache line by using for exampleattribute((align(64)))in gcc. However, I'm interested in aligning (or you could call it padding) at structure declaration time. So for example, for the followingstructI want to ask the compiler to create necessary padding so that any object of thi... |
Yes. I can't remember where I got this code from. I think it might have been Herb Sutter's blog:
```
#define CACHE_LINE_SIZE 64 // Intel Core 2 cache line size.
template<typename T>
struct CacheLineStorage {
public:
[[ align(CACHE_LINE_SIZE) ]] T data;
private:
char pad[ CACHE_LINE... |
So I'm reading in chars one by one from a file:
```
char temp[3];
temp[0] = nextchar;
printf("%c",temp[0]); //prints %
temp[1] = nextchar = fgetc(srcptr);
printf("%c",temp[1]); //prints 2
temp[2] = nextchar = fgetc(srcptr);
printf("%c",temp[2]); //prints 0
if(strcmp(temp, "%20") == 0) { printf("%s","blahblah"); }... |
You need to null terminate temp.
EDIT
Changechar temp[3];tochar temp[4]; temp[3] = 0;
|
I usually work withqmakefor myCandC++projects but recently thought to learnCMake. A nice thing aboutqmakeis that they have a variable reference here:http://qt-project.org/doc/qt-4.8/qmake-variable-reference.html
I was searching for something similar forCMakebut could not find one :( . Can someone please point me to o... |
Does this one fit your needs:
http://www.cmake.org/cmake/help/v2.8.8/cmake.html?
I recently set up a sample project for cmake. Probably it helps you to get startet:
https://github.com/moooeeeep/cmake_sample
|
How to include SVN revision of my project (not file revision) in C source code or in Makefile?
|
We use a line like this in our makefile:
```
REPO_REV := $(shell svnversion -n)
```
That stores the revision number of the working copy into a make variable. To use it in C code, you can have your makefile use that value to define a macro on the compiler command line (something like-DREPO_REV=$(REPO_REV)for gcc).
|
This question already has answers here:?: ternary conditional operator behaviour when leaving one expression empty(2 answers)Closed9 years ago.
Typically the '?' operator is used in the following form:
```
A ? B : C
```
However in cases where B = A I have seen the following abbreviation
```
A ? : C
```
This surpr... |
It is not permitted by the language C (as far as I know), but compilers such as gcc have the shortcut a?:c as anextension.a?:cmeans the same asa?a:c.
|
Please tell me what is the difference of
```
typedef struct Tcl_ObjType {
char *name;
Tcl_FreeInternalRepProc *freeIntRepProc;
Tcl_DupInternalRepProc *dupIntRepProc;
Tcl_UpdateStringProc *updateStringProc;
Tcl_SetFromAnyProc *setFromAnyProc;
} Tcl_ObjType;
```
and
```
struct Tcl_ObjType {
ch... |
ForC++, there is no difference.
If this was aCprogram and you used the first variant, you could do:
```
Tcl_ObjType instanceOfStructure;
```
instead of
```
struct Tcl_ObjType instanceOfStructure;
```
|
Almost all thepipeexamples I've seen advice closing the unused write/read ends. Also man clearly states thatpipe() creates a pipe, a unidirectional data channelBut I've tried reading and writing to both ends of the pipe in both the parent and the child and everything seems to be OK.
So my doubt is why do we need 2 pi... |
If you use the same pipe how does the child separate its messages from the parents messages and vice versa?
For example:
```
Parent writes to pipe
Parent reads from pipe hoping to get message from child but gets its own message :(
```
It is much easier to use one pipe for child->parent and another pipe for parent->... |
I don't know exactly why a file pointer reads an extra line from a file, specifically the last line, here is the code:
```
FILE *fp ;
fp = fopen ("mac_ip.txt", "r") ;
int mac;
char *ip = (char *) malloc(15);
while(!feof(fp)){
fscanf(fp,"%i",&mac);
fscanf(fp,"%s",ip);
printf("MAC: %i\n",mac);
printf(... |
Because after reading the last two values, you still haven't hit EOF. So the loop goes on. In the next pass of the loop, fscanf actually does not read the last line for the second time like it appears, the fscanfs fail, but the printfs print out the values from the previous pass of the loop.
|
I compile an example.c file that has the line:
```
#include "parse/properties/properties.h"
```
The compiler creates get an example.o file. Is the path to the header file included in the example.o file? or is that information external?
|
It may or may not, the object file format is not standardised (the standard does not even mention "object files"). A compiler might insert the #include for debugging purposes, or it may skip it completely.
Note also that #include'ing is done by the compiler in what the standard desrcibes as the first phase in transla... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
Please explain the reason for the following outputs.
```
#include <stdio.h>
int main()
{
int i = 0, j = 0;
int val1 = 0;
int val2 = 0;
val1 =... |
You are modifying the same variable more than once without an intervening sequence point, this isUndefined Behavior.An Undefined behavior simply means that there may or may not be any feasible explanation to the behavior of the program.
Good Read:Undefined behavior and sequence points
|
Can I know if sscanf modifies the string passed to it. Or can anybody please point me where I can find the source code for sscanf ?
I downloaded glibc and found the following :
```
extern int sscanf (__const char *__restrict __s,
__const char *__restrict __format, ...) __THROW;
extern int sscanf (__co... |
sscanfnever modifies the string you pass to it; you can tell by theconstqualifier.
You can find the Glibc source code forsscanfon itsGitweb.
|
I've been using OpenCV for quite some time now and I always ignored more or less an oddity that occurs while writing AVIs with OpenCV commands. But now I need it for another purpose and it has to be accurate.
When I read a XVID compressed AVI with cvCaptureFromFile (or FromAVI) and then write the frames with cvVideoW... |
1) Upgrade to the newest OpenCV available and try again.
2) If that doesn't work, you'll have to choose another multimedia framework to read the frames:ffmpegorgstreamer.
That's all I can think right now.
|
I'm trying to get a file list excluding diretories like "." and "..".
I use the following code to do that:
```
DIR *dir;
struct dirent *ent;
dir = opendir(currentDir);
if (dir != NULL)
{
while ((ent = readdir (dir)) != NULL)
{
if (ent->d_name == "." || ent->d_name == "..")
... |
You should be usingstrcmpto compare strings. Rather than this:
```
if (ent->d_name == ".")
```
you need this:
```
if (strcmp(ent->d_name, ".") == 0)
```
Your code is comparing the pointers directly, rather than comparing the content of the strings.
Seethe strcmp documentationfor more information.
|
Is there a tool or library which I can plot on C or C++ the vertex and edges of a graph like "plot" in R?
|
GraphViz, a popular command-line graph drawing toolkit can theoretically be used as aC library- although I have never tried it.
|
I have generated .h and .c files which must be compiled as C++ files with Visual Studio.
I heard I could do something likeset_source_files_properties( ${SOURCES} PROPERTIES LANGUAGE "CXX" ). In parallel, I have read that I should not do that as it should used only in exotic situations.
So, what is the best way to for... |
I have been using the individual properties (most likely you can also set directory properties - but this is not as fine grained) without any problems. Not for setting the language though (but why should it be any different?):
```
SET_SOURCE_FILES_PROPERTIES( file1.c PROPERTIES LANGUAGE CXX )
```
This works under Li... |
I have a multithreaded application that activate multiple Mono domains from native code.
Each domain has it's own thread.
I use the following code to activate a domain:
```
///Create a new domain.
m_domain = mono_domain_create_appdomain((char*) name.c_str(), NULL);
///Activate the domain.
mono_domain_set(m_domain, ... |
I was calling the functionmono_assembly_close, beforemono_domain_unload:
```
mono_assembly_close(m_assembly);
```
So I removed this call, and created acritical sectionfor the unloading code.
|
I have a doubt in the following code,
i have a function as follows,
```
void deleteNode(struct myList ** root)
{
struct myList *temp;
temp = *root;
...//some conditions here
*root = *root->link; //this line gives an error
*root = temp->link; //this doesnt give any error
}
```
so what is the differen... |
The problem here is that the "->" operator is binding more tightly than the "*" operator. So your first statement:
```
// what you have written
*root->link;
```
is evaluating to:
```
// what you're getting - bad
*(root->link);
```
rather than:
```
// what you want - good
(*root)->link;
```
Since root is a pointe... |
When I give the first input, an extra 0 appears beforegets()works. But if I removegets(), then there is no problem.printf()can't be used because it breaks on blank space. Please give any alternative solution or what should I do?
```
#include <cstdio>
#include <iostream>
#include <stdlib.h>
using namespace std;
in... |
Thescanf()leaves the end-of-line character of the first line in the input stream which is then consumed bygets(). This is a common beginner's error often discussed here.
Recommendations:
Do not mixscanf()routines withgets()routines.Except for short test programs do not usegets()(instead usefgets()) because withgets(... |
I am trying to read contents of a file that is some 3KB into a buffer and then writing the contents of the buffer into another file. The file in which data is written into contains only a part of data that is written into it. Its size is around 1KB. How to write the remaining data?
```
fp1 = fopen("a.txt","rb");
fp2 ... |
fflush(fp2)orfclose(fp2)will move the pending, buffered bytes to disk.
|
I have a program test.c which needs to include a header file common.h. I am new to writing make files and so far I have the right make file for just test.c (it uses openssl):
```
INC=/usr/local/ssl/include/
LIB=/usr/local/ssl/lib/
all:
gcc -I$(INC) -L$(LIB) -o test test.c -lcrypto -ldl
```
How do I edit the... |
You don't compile header files directly. They will be included by#includein the C files. If common.h is located in the same directory as the make file, you won't need to add anything. Otherwise, you might want to edit the makefile to add other folders that include header files:
```
INC=-I/usr/local/ssl/include/ \
... |
I have a function setPosition declared like:
```
void setPosition(char ***grid, int a, int b) {
int x = a / 8;
int xbit = a % 8;
int y = b;
(*grid)[x][y] |= 1 << xbit;
}
```
and in my main, I have:
```
char grid[1000][1000];
setPosition(&grid, 10, 5);
```
But I get "warning: passing argument 1 of ‘... |
Arrays and pointers are not the same type, even though arrays dodecay to pointerswhen passed to functions. You can change the method signature to take an array
```
void setPosition(char grid[][1000], Pos *p)
```
but if you are doing C++,vector<vector<char> >would provide a much better and more flexible option.
|
Here is the problem and what I currently have, I just don't understand how it is wrong...
getByte - Extract byte n from word x Bytes numbered from 0 (LSB) to
3 (MSB) Examples: getByte(0x12345678,1) = 0x56 Legal ops: ! ~ &
^ | + << >> Max ops: 6 Rating: 2
```
int getByte(int x, int n) {
return ((... |
Your shifting doesn't make any sense - first, you shift left by (24 - 8n) bits, then you shift back right by 8n bits. Why? Also, it's wrong. If n is 0, you shift x left by 24 bits and return that value. Try pen and paper to see that this is entirely wrong.
The correct approach would be to do:
```
int getByte(int x, ... |
If I want to traverse a quadtree, do the dimensions have to be only 2^n ?
If not, what if it cannot be divided into equal subquadrants? for example, 5x6 table with data.
|
There are several ways to approach this problem.
First of all, your subdivisions are entirely arbitrary. You can set up the first subdivision to interpret your table 5x6 table dimensions as [1 + 4] x [2 + 4]. Then your four quadrants would be 1x2, 1x4, 4x2 and 4x4. At this point you can recurse as dimensions are 2^n.... |
```
char i;
for(i=0;i<16;i++)
printf("%c","asdf"[i]);
i=1;
if("123"[i]==1)
i=1;
if("456"[4]==1)
i=1;
if("789"[1]==1)
i=1;
```
The output is:
```
asdf 123 456
```
Seemingly most of the 'strings' are directly after each other in the memory. I don't think that this is randomly, or is it?
Moreover, the ... |
Constant strings are often stored separately from the program code, and it's not surprising that they are arranged close together in memory. However you should not rely on this.
Your program hasundefined behaviourand something different could happen if you try to run your code using a different compiler. For example,... |
I have a while loop that decodes a video file by retrieving each frame, so something like this:
```
while (get_frame(codec_ctx, format_ctx, video_stream, frame) != 0) {
...
}
```
Now, once a frame is retrieved, it needs to be drawn onto the screen at a certain point in the future (according to the frame's tim... |
You can push a (frame, time) pair onto a queue, then have a separate thread execute the following algorithm:
```
loop {
time, frame = pop(queue);
wait_until(time);
display(frame);
}
```
wherepopwaits for an item to be pushed onto the queue if it is empty.
|
I'm writing a small c program which connects to the google api via Oauth2.
Therefore I need to send a client secret to google.
I store this secret in my code, which I want to push to github, but how can I avoid to show my client secret to everybody who looks at my code?
|
use a configuration file where you'll store the API key... you have many options, the simplest being writing the key directly into the file, more sophisticated being using some kind of serializers (like json, xml, inifile etc...), the right option is up to you (usually, you'll want to serialize if you want to store se... |
I want a c program which ask for Hexadecimal number and gives output equivalent octal number. I use the code to convert int into octal using printf() function.
```
#include<stdio.h>
Void main(){
int i;
printf("Enter the Hax number: ");
scanf("%x",&i);
printf("Octal equivalent of number is %o",i);
}
```
|
Hexadecimal and Octal are just different representations of the same underlying number format. ie binary. So no conversion is really happening in your example. Its just that you are interpreting/printing the same number in 2 different ways. Andprintfis indeed doing a good job in your example
```
Enter the Hax number:... |
Some operations to read and write from streams may set the error flag in a stream, which can be tested usingferror(stream), while I'm quite sure this must be a frequently asked question, I wasn't able to find a list of all the possible causes of errors in SO or in the general web. What could cause ferror() to be set?
... |
There isn't any simple list of possible errors. However, depending on the device you're reading from or writing to, the problems could include:
Device fails (short circuits, overheats, dies of old age, ...)Device is pulled out of machine (USB stick)Device is switched off or loses power (external disk drive)Device is... |
Is there a way in C or Objective-C to convert presentation files (.ppt/.key) into a set of images?
many thanks!
|
I doubt. ppt file is the fact XML style document. So if you want to parse it you have to write a XML parser who puts element in the exact position... So in fact you have to create your own powerpoint.
But, you might (both PowerPoint and Keynote) consider to export presentation to pdf, and then this will be a lot simp... |
I am learning FileIO in C and was little confused with the binary files. My question is what is the use of having binary files when we can always use files in ASCII or someother format which can be easily understandable. Also in what applications are binary files more useful?
Any help on this really appriciated.Thanks... |
All files are binary in nature. ASCII files are those subset of binary files that contain what can be considered to be 'human-readable' data. A pure binary file is not constrained to that subset of characters that is readable.
|
Sometimes I get libraries from different design teams. One uses gcc 3.x and another uses gcc 4.x. How can I identify whether these two libraries are compatible? I know it is something with libstdc++, but could you please give me a clear answer?
|
This is a good starting point
http://gcc.gnu.org/onlinedocs/gcc/Compatibility.html
This article discusses binary compatibility ( it can apply to libraries too ) between different tools. This still holds good when the different tools are differnt versions of gcc. One major thing to be checked is application binary in... |
I have a program test.c which needs to include a header file common.h. I am new to writing make files and so far I have the right make file for just test.c (it uses openssl):
```
INC=/usr/local/ssl/include/
LIB=/usr/local/ssl/lib/
all:
gcc -I$(INC) -L$(LIB) -o test test.c -lcrypto -ldl
```
How do I edit the... |
You don't compile header files directly. They will be included by#includein the C files. If common.h is located in the same directory as the make file, you won't need to add anything. Otherwise, you might want to edit the makefile to add other folders that include header files:
```
INC=-I/usr/local/ssl/include/ \
... |
I have a function setPosition declared like:
```
void setPosition(char ***grid, int a, int b) {
int x = a / 8;
int xbit = a % 8;
int y = b;
(*grid)[x][y] |= 1 << xbit;
}
```
and in my main, I have:
```
char grid[1000][1000];
setPosition(&grid, 10, 5);
```
But I get "warning: passing argument 1 of ‘... |
Arrays and pointers are not the same type, even though arrays dodecay to pointerswhen passed to functions. You can change the method signature to take an array
```
void setPosition(char grid[][1000], Pos *p)
```
but if you are doing C++,vector<vector<char> >would provide a much better and more flexible option.
|
Here is the problem and what I currently have, I just don't understand how it is wrong...
getByte - Extract byte n from word x Bytes numbered from 0 (LSB) to
3 (MSB) Examples: getByte(0x12345678,1) = 0x56 Legal ops: ! ~ &
^ | + << >> Max ops: 6 Rating: 2
```
int getByte(int x, int n) {
return ((... |
Your shifting doesn't make any sense - first, you shift left by (24 - 8n) bits, then you shift back right by 8n bits. Why? Also, it's wrong. If n is 0, you shift x left by 24 bits and return that value. Try pen and paper to see that this is entirely wrong.
The correct approach would be to do:
```
int getByte(int x, ... |
If I want to traverse a quadtree, do the dimensions have to be only 2^n ?
If not, what if it cannot be divided into equal subquadrants? for example, 5x6 table with data.
|
There are several ways to approach this problem.
First of all, your subdivisions are entirely arbitrary. You can set up the first subdivision to interpret your table 5x6 table dimensions as [1 + 4] x [2 + 4]. Then your four quadrants would be 1x2, 1x4, 4x2 and 4x4. At this point you can recurse as dimensions are 2^n.... |
```
char i;
for(i=0;i<16;i++)
printf("%c","asdf"[i]);
i=1;
if("123"[i]==1)
i=1;
if("456"[4]==1)
i=1;
if("789"[1]==1)
i=1;
```
The output is:
```
asdf 123 456
```
Seemingly most of the 'strings' are directly after each other in the memory. I don't think that this is randomly, or is it?
Moreover, the ... |
Constant strings are often stored separately from the program code, and it's not surprising that they are arranged close together in memory. However you should not rely on this.
Your program hasundefined behaviourand something different could happen if you try to run your code using a different compiler. For example,... |
If I have the following function and the optional argumentmyobjis not passed, doesmyobjremainNULLor is it set toPy_None?
```
static PyObject * myfunc(PyObject * self, PyObject * args) {
PyObject * myobj = NULL;
if (!PyArg_ParseTuple(args, "|O", &myobj)) {
return NULL;
}
// ...
}
```
According... |
It will remain NULL. And of course a pointer to a struct is a C object.
|
I just came across below question on Internet:
Macros and function are related in what aspect?(a)recursion(b)varying no of arguments(c)hypochecking(d)type declaration"
I am ruling out the option d cause macros just do argument substitution. Option a is not applicable to macros.
I am weighing between option b and c.... |
"Is there any terminology called “hypochecking” in C/C++?"
NO
|
Which line is the correct (best) way for defining a pointer?
```
typedef ptrdiff_t pointer; // pointers are ptrdiff_t.
-- or --
typedef void* pointer; // pointers are void*.
pointer ptr = malloc(1024);
```
|
Pointers in C are of typeT*whereTis the type pointed to;void*is the generic pointer type. Usually, you let C implicitly convertvoid*to something useful, e.g.
```
char *buffer = malloc(1024);
```
ptrdiff_tis the type returned by the subtraction of two pointers, e.g.
```
ptrdiff_t d = write_ptr - buffer;
// now you k... |
I am reading a C book, talking about ranges of floating point, the author gave the table:
```
Type Smallest Positive Value Largest value Precision
==== ======================= ============= =========
float 1.17549 x 10^-38 3.40282 x 10^38 6 digits
double 2.22507 x 10^-308 1.... |
A 32 bit floating point number has 23 + 1 bits of mantissa and an 8 bit exponent (-126 to 127 is used though) so the largest number you can represent is:
```
(1 + 1 / 2 + ... 1 / (2 ^ 23)) * (2 ^ 127) =
(2 ^ 23 + 2 ^ 23 + .... 1) * (2 ^ (127 - 23)) =
(2 ^ 24 - 1) * (2 ^ 104) ~= 3.4e38
```
|
I have a rooted device and set the build properties as given in the Android Dev Linkhttp://android-developers.blogspot.in/2011/07/debugging-android-jni-with-checkjni.html
```
$ adb shell stop
$ adb shell setprop debug.checkjni 1
$ adb shell start
```
But after doing this i am getting CheckJNI is OFF in the DDMS log
... |
Try this:
Go to data > localpropertiesIn localproperties if have write permissionHave a file with local.prop in your local disk with this text dalvik.vm.checkjni=true.adb push /data/local.prop /local.prop.Then restart the device then you will see CheckJNI Option in LOGCAT.
|
How to pass the param like char * as a reference?
My function uses malloc()
```
void set(char *buf)
{
buf = malloc(4*sizeof(char));
buf = "test";
}
char *str;
set(str);
puts(str);
```
|
You pass the address of the pointer:
```
void set(char **buf)
{
*buf = malloc(5*sizeof(char));
// 1. don't assign the other string, copy it to the pointer, to avoid memory leaks, using string literal etc.
// 2. you need to allocate a byte for the null terminator as well
strcpy(*buf, "test");
}
char *... |
I want to increment up where I use a[0]. Something likea++. The only other solution I can think of is a switch case or a bunch of if/else if statement, but that seems inefficient. Is this possible?
```
#include <stdio.h>
int
main(void)
{
const char *a[6];
a[0]="one";
a[1]="two";
a[2]="three";
... |
What about this?
```
printf(..., a[i]);
```
|
What is the equivalent ofpthread_mutex_lockandpthread_cond_waitin the linux kernel. and how to use them. Could you please provide simple (hello world) examples.
|
For the mutex (as Als said ):
mutex_lock()andmutex_unlock()and we should init the mutex before we use it withmutex_init()(from#include <linux/mutex.h>)
For the equivalent ofpthread_cond_wait
wait_event_interruptible()andwake_up_interruptible()and we should init the wait_queue_head withinit_waitqueue_head()(from#inc... |
I'm coding something in C and dealing with situations where it would be helpful to be able to say "cast this to a pointer pointing to a datatype with the same number of bytes as this number".
An example will make it clearer - I'm usingsize_tto get the size of a pointer on the system. Now I want to portably cast avoid... |
What wrong aboutsize_t*(assuming I understood your question)
In the general case, where you need pointer to a type withnbytes, you can do:
```
void *voidptr=... //assign whatever you want.
char (*myptr)[n]=voidptr; //a pointer to char[n]
```
|
For example, I define a macro:
```
#ifdef VERSION
//.... do something
#endif
```
How can I check ifVERSIONexist in my object file or not? I tried to disassemble it withobjdump, but found no actual value of my macroVERSION.VERSIONis defined in Makefile.
|
Try compiling with-g3option ingcc. It stores macro information too in the generated ELF file.
After this, if you've defined a macroMACRO_NAMEjustgrepfor it in the output executable or your object file. For example,
```
$ grep MACRO_NAME a.out # any object file will do instead of a.out
Binary file a.out matches
```
... |
I am trying to implement a Data Flow Anomaly Detection using ptrace. After a bit of research I implemented a program which is similar to strace. Now, I'm confused about this, which is what the wiki tells me about system calls:
"System calls provide the interface between a process and the operating system"
When I am ... |
You are operating in the address space of a separate process; this requires the intercession of (and permission from) the kernel, since independent processes cannot normally affect each others' address spaces.
|
I'm trying to get the contents from the file yh.dat which HAS the text like "456 78921" and somthing else by C.But when I try debug the code,the FILE pointer isn't NULL(0x00428af8) and the _ptr and the _base is NULL(0x000000).They says "CXX0030:Error:expression cannot be evaluated".How to solve it?
```
int main(){
... |
To allow you to change the file buffering, C doesn't set up the buffer for a file until you issue the first read. As such, until you attempt at least one read, it's normal for the members of whatever struct the FILE * points at to be in an only semi-initialized state.
Have you tried just reading data to see if it wor... |
I've read in a document that you can replace mod operation by logical and like this :
Instead:
```
int Limit = Value % Range;
```
You do:
```
int Limit = Value & (Range-1);
```
But compilers still generate mod instructions and my question is basically : Why do compilers don't use the most efficient approach if th... |
Um no... that only works whenRangeis a power of two.
For all other values, you still need the modulus%operator.
There are also some subtle (possibly implementation-defined) differences when working with negative numbers.
As a side note: Using the%operator is probably more readable too.
|
I want to store all of the data that is kept in encoding_symbols_tab [0] in symbol_and_header.
'encoding_symbols_tab' points to an array with e.g. 500 * 1024 chars.
I modified the following code for this example.
```
void** encoding_symbols_tab;
(..)
char* return_symbol_and_header_array ()
{ //abcd
char* s... |
Use
```
((char**)encoding_symbols_tab) [0][k];
```
|
I have the following piece of code wherecheckis for char type
```
do{
printf("Do you want to add an edge(n to stop adding)\n");
check = getchar();
}while(check!='n');
```
and
```
do{
printf("Do you want to add an edge(n to stop adding)\n");
scanf("%c",&check);
}while(check!='n');
```
Both ... |
To solve your issue, try this:
```
void main()
{
char check;
char c;
do
{
printf("Do you want to add an edge(n to stop adding)\n");
check = getchar();
do { c = getchar(); } while (c != '\n' && c != EOF); // This gobbles the rest of the chars on stdin
} while(check != 'n' &... |
I have the following sequences in C code:
```
variable == T_CONSTANT
```
or
```
variable != T_CONSTANT
```
Using Python, how can I replace these bySOME_MACRO(variable)or!SOME_MACRO(variable), respectively?
|
A very simple and error-prone method is to use regular expressions:
```
>>> s = "a == T_CONSTANT"
>>> import re
>>> re.sub(r"(\w+)\s*==\s*T_CONSTANT", r"SOME_MACRO(\1)", s)
'SOME_MACRO(a)'
```
A similar regex can be used for the!=part.
|
```
#include<stdio.h>
int main()
{
struct value{
int bit1 : 1;
int bit3 : 4;
int bit4 : 4;
}bit={1,2,2};
printf("%d %d %d\n",bit.bit1,bit.bit3,bit.bit4);
return 0;
}
```
Output :
-1 2 2
Please explain the oupput of the program ?
|
bit1is a signed 1-bit integer, that can hold the values-1and0only.
|
I came across below interview question on the net.
" Write the code for Getnextnode function in a singly LL with following prototype
```
Node GetNextNode(Node n);
```
and validate it "
The generic case solution is straight forward like something below:
```
Node GetNextNode(Node n)
{
Node temp = *(n.link);
... |
There is another way to store the end of the list, havelinkpoint to the node itself. In such a way your link is always valid and you can simply test for the end by comparing the two for equality.
|
When I execute the following code:
```
int main()
{
char **temp;
printf("Size of **temp %d", sizeof(**temp));
printf("Size of *temp %d", sizeof(*temp));
printf("Size of temp %d", sizeof(temp));
return 0;
}
```
I get:
```
Size of **temp 1
Size of *temp 8
Size of temp 8
```
What I don't understan... |
In the original question you weren't callingsizeof.duskwufffixed that for you.
The output produced was:
```
Size of **temp 1
Size of *temp 8
Size of temp 8
```
Reason:
On a 64-bit architecture, pointers are 8-bytes (regardless of what they point to)
```
**temp is of type char ==> 1 byte
*temp is of type poin... |
I have been reading from the book "The C Programming Language" learning C, and I stumbled upon the arithmetics[i] - '0'which they said that it gives the numeric value of the character stored in s[i]. I didn't quite understand it, how could it give the value by subtraction?
Note This is used in the atoi function, which... |
Possible duplicate :See here
Well'0'represent48in character set. So subtracting it('0') with any other character value like this'1','2'will give respective number, so'9'-'0'will give you9.
Note the difference we are sub both chars :'9'-'0', here both arechar
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.