question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I am writing a C program that forks once it accepts a client connection. Once this happens, I want to spawn two threads, but I cannot seem to get this working.
```
pthread_t t1, t2;
void *r_loop();
void *w_loop();
.
.
.
sockfd = accept(r_sockfd, (struct sockaddr *) &address, &len);
if (sockfd < 0... |
The problem could be this: pthread_create() on success alwasy returns zero. You are passing to pthread_join() an incorrect value (that is zero instead of t1 and t2) making them to return immediately. Then the following exit() also kills the new starting threads
|
I have a .lib file, source code of which I don't have.
I need an exported function from it, but I'm writing in C, and the function is C++ name-mangled. I can't writeextern "C", because I don't have the source code.
How do I link mangled function without source code and switching to C++?
|
Make C++ wrapper:
wrapper.cpp:
```
#include "3rdparty.hpp"
extern "C" int foo(int a, int b)
{
return third_party::secret_function(a, b);
}
```
consumer.c:
```
extern int foo(int, int);
// ...
```
Build:(e.g. with GCC)
```
g++ -o wrapper.o wrapper.cpp
gcc -o consumer.o consumer.c
g++ -o program consumer.o w... |
This question already has answers here:Closed11 years ago.
Possible Duplicate:Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
I have encountered with a strange problem regards increment operator.
I get different output of same expression in PHP and C.
In C language
```
main()
{
... |
In C the result is undefined because either of the two operands could be evaluated first, thus reading it a second time is erroneous.
And, well, in PHP I wouldn't be surprised if the result was 42 pending some changes to php.ini.
|
I've modified the small part of a simulator but I've faced to strange segmentation fault. GDB shows the error is appear from a class where I've not modified. I guess my code has memory access violation upon accessing its own array which accordingly destroys the content of other array (allocated in the program memory s... |
In short,Valgrindwill do this. Just run it asvalgrind /path/to/executable
|
I am working on a problem where I need to store and retrive the data from the database . I am using C for that on windows system . I am familiar with MYSQL database . I just need to know whether its possible for me to access database using C if yes which IDE I can use and how can I connect it to MYSQL .
|
Yes, you can connect your C code to MySQL using a connector (driver) available on MySql home page:http://www.mysql.com/products/connector/
There is a nice tutorial on writing C programs accessing MySQL:MySQL C API programming tutorial
You can use any IDE you want for writing your code, for example Visual Studio. Her... |
I have written a very simple C program to print "Hello World" in my Notepad text editor and saved it as test1.exe. I opened my cmd and ran the file test.exe and the received error is as follows:
The NTVDM CPU has encountered an Illegeal instruction. CS:0607
IP:0103 OP:63 6c 75 64 65 Choose 'Close' to terminate the... |
You need to save the file astest.cand thencompileit totest.exe. The exact details of how you compile it will depend on what C compiler you have installed, but forcygwinorMinGWit would be:
```
$ gcc -Wall test.c -o test.exe
```
If you don't have a compiler installed yet and just want to quickly try running a small C ... |
I have an animated png that I want to load in my MFC project to show it animated. I need this because it's a loading animation, and I would love to know how to do it. Would love if you can tell me how this works for png files.
|
Maybe this is what you want:
http://www.codeproject.com/Articles/1427/Add-GIF-animation-to-your-MFC-and-ATL-projects-wit
|
When I using variable parameters, it works well with int and double, but when it comes to float, error happens.
Here is the code.
```
void vaParamTest(int a, ...)
{
va_list ap;
va_start(ap, a);
for (int i = 0; i < a; i++)
printf("%f\t", va_arg(ap, float));
putchar('\n');
va_end(ap);
}
``... |
Variables that are passes as variadic function arguments aredefault-promoted, which makes allfloats intodoubles. You can never have afloatargument (just likeyou can never have acharargument). Inprintf,%falways meansdouble.
|
For an assignment, a small portion of it indicates that an integer must only be five digits long. If an integer is entered such as 1234567, then the result should be 34567.
Is there any way that I can set this directly with scanf? Of course, setting it to only read five integers is easy, but it won't read the right-m... |
You could use the mod operator.int m = enteredNumber % 100000;This will truncate your number down.
Here.. I tried it.
```
#include <math.h>
int main(int argc, char** argv)
{
char* number = "12334567";
int numberAsInt = atoi(number);
int shorterNumber = numberAsInt % 100000;
printf("The number is %d\n", s... |
I usedSetupDiGetDriverInfoDetailto retrive the details of the driver. I used the following code fragment for this. But each time I execute my exe I am gettingERROR_INSUFFICIENT_BUFFER. How to solve this?
SetupDiGetDriverInfoDetail(hDevInfo, &DeviceInfoData, &drvInfoData,
&drvIn... |
First, read Microsoft's explanation of why theSetupDiGetDriverInfoDetail functionmight return ERROR_INSUFFICIENT_BUFFER. Second, write code to call it twice.
Call SetupDiGetDriverInfoDetail the first time with a pointer to a DWORD variable where you will find out how many bytes you need. Allocate memory for a suffi... |
I'm trying to recreate the head, and tail commands from linux for my programming class.
We just started using C so I'm new to the idea of allocating memory and pointers.
I'm wondering why this doesn't work.
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char **argv){
/* Checks if correct amount of... |
I think it's better to write:
```
char fileName[strlen(argv[1])+1];
strcpy(fileName, argv[1]);
```
or (if you don't whant to make a copy of string) :
```
char* fileName = argv[1];
```
|
This:
```
label := string([]byte{97, 98, 99, 0, 0, 0, 0})
fmt.Printf("%s\n", label)
```
does this (^@is the null-byte):
```
go run test.go
abc^@^@^@
```
|
There's this function hidden inside Go's syscall package that finds the first null byte ([]byte{0}) and returns the length. I'm assuming it's called clen for C-Length.
Sorry I'm a year late on this answer, but I think it's alotsimpler than the other two (no unnecessary imports, etc.)
```
func clen(n []byte) int {
... |
I have read that converting a function pointer to a data pointer and vice versa works on most platforms but is not guaranteed to work. Why is this the case? Shouldn't both be simply addresses into main memory and therefore be compatible?
|
An architecture doesn't have to store code and data in the same memory. With a Harvard architecture, code and data are stored in completely different memory. Most architectures are Von Neumann architectures with code and data in the same memory but C doesn't limit itself to only certain types of architectures if at al... |
My question is about thesizeofoperator in C.
sizeof('a');equals4, as it will take'a'as an integer: 97.
sizeof("a");equals2: why? Also(int)("a")will give some garbage value. Why?
|
'a'is acharacter constant- of typeintin standard C - and represents a singlecharacter."a"is a different sort of thing: it's astring literal, and is actually made up oftwocharacters:aand a terminating null character.
A string literal is an array ofchar, with enough space to hold each character in the string and the t... |
Using Linux system callsopenandread. Thereadcall accepts 3 parameters
```
read(File descriptor, Buffer array, Size of the buffer array);
```
My question is related to the argument #3. Suppose I have multiple text files that I want to read into my buffer array. But as far as I know C doesn't have something likeVector... |
You could alsostat()the file to determine its size and then callmmap()on it. Your file will appear as an "array" without the need tomalloc()memory.
|
```
for(i=0; 0; i)
{
//statement
}
```
Why the statement executes only one time ? Either it does not execute the statement or the statement should go into an infinite loop. but the statement executes just one time. Can you please help me.
|
Make sure you don't have a semi-colon after the for loop otherwise the compiler will take the semi-colon to be the end of the loop and anything in the following braces will be executed once.
```
for(i=0; 0; i); // end of loop
{
// do something once
}
```
You don't have a semicolon in your example but I've seen p... |
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed9 years ago.Improve this question
What is the correct Hello World program in C?
Since the first page ofGoogle results... |
Depends how lazy you are: :)
```
#error Hello World
```
|
Closed.This question isoff-topic. It is not currently accepting answers.Want to improve this question?Update the questionso it'son-topicfor Stack Overflow.Closed11 years ago.Improve this question
I downloaded Visual C++ express edition 2008 but the problem is the file doesn't has any extension. I don't know how to ru... |
Visual Studio 2008 Express edition is available in multiple download forms fromthis address@ Microsoft. The default Visual C++ download is a over-the-web installer (vcsetup.exe). the full download as an ISO mountable or burnable to a disc is also available.
And the ISO is about 784.9 MB if you go that route, just to ... |
I am new to C and am having some troubles with strings. How do I create a string of variable length containing a specified character in C? This is what I have tried but I get a compiler error:
```
int cLen = 8 /* Specified Length */
char chr = 'a'; /* Specified Character */
char outStr[cLen];
int tm... |
You can try:
```
char *str = malloc(cLen + 1);
memset(str, 'a', cLen);
str[cLen] = '\0';
```
(edited to properly terminate the string with '\0')
|
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.
Given the string:
"10 + 20 - 5 * 7... |
Take a look atthispost bynewacct.
```
NSString *equation = @"10 + 20 - 5 * 7 + (20 / 5)";
// dummy predicate that contains our expression
NSPredicate *pred = [NSPredicate predicateWithFormat:
[equation stringByAppendingString:@" == 42"]];//42 is just a rightExpression to make it an equation
NSE... |
The following code calls an except script which copies an file via ftp to a server.
```
int status;
int child_pnr;
if((child_pnr = fork())==0)
{
printf("Childnr %i\n",child_pnr);
execv("/home/..../ftptest.exp",NULL);
}
else if (child_pnr > 0)
{
printf("Parent... childnr %i generated\n",child_pnr);
... |
By "interrupted", I presume you mean that the parent does not wait for the child to complete the operation before doing whatever it does next?
The parent and the child will run in parallel after the fork. If you want the parent to "hang" until the child is done then you need towaitfor it.
Seeman waitand search for f... |
I am writing a python module in C.
The module needs to be compiled for python version 2.4, 2.5, 2.6 and 2.7.
Now I ran in to the problem that in python 2.5 they definedPy_ssize_tfor the size of lists, but in 2.4 they just usedint.
So my question is:
Is there an easy way to check if I'm using the API of version 2.4 o... |
Yes,patchlevel.hin the Python include dir defines what you are looking for:
```
#define PY_MAJOR_VERSION 2
#define PY_MINOR_VERSION 5
#define PY_MICRO_VERSION 2
```
|
I have a structure as shown below.
```
typedef struct
{
attribute_code_t field_id;
uint8_t instance_num;
uint8_t length;
uint8_t data[32];
uint32_t crc_value;
}table_entry_t;
```
I want to populate the structure as follows.
```
entry->field_id = 54;;
entry->instance_num = 0;
entry->length = 4;
e... |
The following code copies data to first 4 bytes of 32- byte.
```
tmpdata = 0xfdfcfefa;
memcpy(entry->data, &tmpdata, sizeof(uint8_t) *4);
```
|
I'm beginner with C and I am learning on my own.
I am trying to convert an int to binary for bitwise operations, and I am not really sure how to do it? I have tried to use mod and other mathematics to do it, but I have been unsuccessful. I have searched around and have not found a clear way of this. Please assist.
|
You don't need to do any conversion of anintto use bitwise operators on it. They automatically work on thebitsthat compose theint.
If you want to view the binary representation of a number, you can use (assuming the 8 least significant bits)...
```
int num = 4;
int i;
for (i = 7; i >= 0; i--) {
printf("%d", (n... |
Doing K&R exercise 1-16, and want to simply printf the contents of a char array.
```
#define MAXLINE 1000 /* max num of input chars */
char longest[MAXLINE]; /* char array to hold longest input */
...get input, store, calculate longest input line...
printf("Length : %d, Text was : %s\n", max, longest);
... |
Change
```
(c = getchar() != EOF)
```
to
```
(c = getchar()) != EOF
```
Your version sets c to 1 for every character read, and to 0 for eof.
|
I have two functions,func1andfunc2, each with a breakpoint set.
Is it possible to have GDB stop on thefunc2breakpoint iff the previous breakpoint hit wasfunc1?
|
The best way to do this is to use commands in breakpoints.
You can direct GDB to execute certain commands (like, to increment a counter) when the two breakpoints are hit. The execution is halted conditionally based on the count of these variables/flags.
I found this information onthis link. Please refer the same for... |
I'm beginner with C and I am learning on my own.
I am trying to convert an int to binary for bitwise operations, and I am not really sure how to do it? I have tried to use mod and other mathematics to do it, but I have been unsuccessful. I have searched around and have not found a clear way of this. Please assist.
|
You don't need to do any conversion of anintto use bitwise operators on it. They automatically work on thebitsthat compose theint.
If you want to view the binary representation of a number, you can use (assuming the 8 least significant bits)...
```
int num = 4;
int i;
for (i = 7; i >= 0; i--) {
printf("%d", (n... |
Doing K&R exercise 1-16, and want to simply printf the contents of a char array.
```
#define MAXLINE 1000 /* max num of input chars */
char longest[MAXLINE]; /* char array to hold longest input */
...get input, store, calculate longest input line...
printf("Length : %d, Text was : %s\n", max, longest);
... |
Change
```
(c = getchar() != EOF)
```
to
```
(c = getchar()) != EOF
```
Your version sets c to 1 for every character read, and to 0 for eof.
|
I have two functions,func1andfunc2, each with a breakpoint set.
Is it possible to have GDB stop on thefunc2breakpoint iff the previous breakpoint hit wasfunc1?
|
The best way to do this is to use commands in breakpoints.
You can direct GDB to execute certain commands (like, to increment a counter) when the two breakpoints are hit. The execution is halted conditionally based on the count of these variables/flags.
I found this information onthis link. Please refer the same for... |
I have sort of a homework and it asks me to end the program gracefully without explicit termination such as calling exit() or killing the threads.
However I cannot think of any other methods thanreturn 0, so what are the methods to end a program gracefully?
|
Killing the threads is absolutely not a graceful way to terminate a program. I think what your instructor means is that all yourparentthreads should wait on theirchildthreads before terminating themselves.
Ideally, an explicit callpthread_exitfrom the main thread would ensure that all it's children continue running e... |
I need an software emulator PC/SC reader for Linux, but can't find.
The only thing I found ishttp://vsmartcard.sourceforge.net/. But this library requires a mobile phone to emulate PC / SC device.
Can I find somewhere fully software emulator of PC/SC reader?
Thank you for you attention!
|
The link you provided is the answer to your question.
The project proposed on that link is the Virtual Smart Card Architecture which can be used to simulate smart cards for different purposes. You do not require a mobile phone, that is just one use case scenario they present.
http://vsmartcard.sourceforge.net/virtual... |
I am confused from something.
first:
```
int *ptr;
ptr = malloc(10 * sizeof(int));
```
This type of getting dynamic(heap) memory atrun-time, notcompile timelike arrays.
malloc()may be returnNULLif there is no memory.
AndNULLis a#definein Standard C Library#define NULL ((void *)0)
So, if themallocreturnNULLand it... |
No, you have it wrong. Imagine themallocfunction something like this:
```
void *malloc(size_t n)
{
/* magic */
return NULL;
}
```
The compiler replacesNULLwhen that translation unit is compiled, i.e. when the standard library is compiled so no trace ofNULLsurvives past the preprocessor phase. After that poin... |
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.Closed10 years ago.
I must write a C/C++ program which ... |
Use any resolver library you like. Popular libraries includeUDNSandadns. You could also just modify the source code todig(which is part of thebinddistribution).
|
Is there a way to know which thread (coroutine) executing a Lua script is at the origin of a lua_pushcclosure call?
In order to manage some stuff relative to lua threads (delayed pause/resume, or private thread variables) I need to identify the thread involved in the callback. I know I can get the thread index when c... |
If you're in a C function that has been called from Lua, and you want to know what thread you're in... just calllua_pushthread(L).
|
I have a MFC Dialog Application. I add a Edit Control in the Dialog and turn the autoSuggestion on by using following code
```
SHAutoComplete(txtPath.m_hWnd, SHACF_FILESYS_DIRS);
```
things work fine. But when I Scroll the Suggestion list and press Enter, The list does not close. How Can I do this? Thanks
|
Take a lookhere: How To Use the ENTER Key from Edit Controls in a Dialog Box
|
What is the expected behaviour for this code snippet?
```
char * aNullPointer = 0;
snprintf (res, 128, "Testing %s null pointer",aNullPointer);
```
Note that I am deliberately trying to get it to de-reference my null pointeraNullPointer.
Behaviour 1)respoints to a string "Testing (null) null pointer"
Behaviour 2) ... |
It's undefined behavior - there's nothing to expect. The fact that some implementations check forNULLand replace it with "nil" or "null" is just a nicety, you can't rely on it at all.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Redirecting/redefining print() for embedded Lua
I am new to Lua and rather confused.
I have seenthisbut Im not sure it works for 5.2.
I have read about _ENV table(?) but again not sure if this has anything to do with it.
So on to the que... |
FromLua 5.2 manual:
```
Lua keeps a distinguished environment called the global environment.
This value is kept at a special index in the C registry (see §4.5).
In Lua, the variable _G is initialized with this same value.
```
Sothis answer to the question you linkedwill work if you replace the calls toluaL_registert... |
First, you can successfully compile the following main.c through DDK build utility.
```
#include <ntddk.h>
NTSTATUS DriverEntry(PDRIVER_OBJECT, PUNICODE_STRING)
{
try
{
leave;
}
except (1)
{
}
return 0;
}
```
And however, please note that:
Both of "leave" and "except" are not v... |
As Rohan noted, they are defined by macro inwarning.h. The definitions are there for backward compatibility with old code which used the non-underscore versions.
|
I have a MFC Dialog Application. I add a Edit Control in the Dialog and turn the autoSuggestion on by using following code
```
SHAutoComplete(txtPath.m_hWnd, SHACF_FILESYS_DIRS);
```
things work fine. But when I Scroll the Suggestion list and press Enter, The list does not close. How Can I do this? Thanks
|
Take a lookhere: How To Use the ENTER Key from Edit Controls in a Dialog Box
|
What is the expected behaviour for this code snippet?
```
char * aNullPointer = 0;
snprintf (res, 128, "Testing %s null pointer",aNullPointer);
```
Note that I am deliberately trying to get it to de-reference my null pointeraNullPointer.
Behaviour 1)respoints to a string "Testing (null) null pointer"
Behaviour 2) ... |
It's undefined behavior - there's nothing to expect. The fact that some implementations check forNULLand replace it with "nil" or "null" is just a nicety, you can't rely on it at all.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Redirecting/redefining print() for embedded Lua
I am new to Lua and rather confused.
I have seenthisbut Im not sure it works for 5.2.
I have read about _ENV table(?) but again not sure if this has anything to do with it.
So on to the que... |
FromLua 5.2 manual:
```
Lua keeps a distinguished environment called the global environment.
This value is kept at a special index in the C registry (see §4.5).
In Lua, the variable _G is initialized with this same value.
```
Sothis answer to the question you linkedwill work if you replace the calls toluaL_registert... |
First, you can successfully compile the following main.c through DDK build utility.
```
#include <ntddk.h>
NTSTATUS DriverEntry(PDRIVER_OBJECT, PUNICODE_STRING)
{
try
{
leave;
}
except (1)
{
}
return 0;
}
```
And however, please note that:
Both of "leave" and "except" are not v... |
As Rohan noted, they are defined by macro inwarning.h. The definitions are there for backward compatibility with old code which used the non-underscore versions.
|
I'm trying to format a 10-digit Unix time stamp (currently a string) using ctime.
However, ctime() expects a parameter of type time_t, not a string.
What must I do before I can use ctime?
In other words, can I easily convert the string into a time_t?
|
You're saying you have something like 1346426869 as a string and want it to be a time_t?
```
time_t raw_time = atoi("1346426869");
printf("current time is %s",ctime(&raw_time));
> current time is Fri Aug 31 11:27:49 2012
```
|
There'ssyscallwhich allows indirect system calls in Linux. What are the reasons to use it - and why is it better than direct call to the function?
|
Sometimes the kernel adds system calls and it takes a while for the C library to support them.
Or maybe you are compiling on an old Linux distribution, but want to run on a newer one.
Example code:
```
// syscall 277 is sync_file_range() on x86_64 Linux. The header
// files lack it on scc-suse10 where we compile, ... |
I need to know which perl script is using my C CLI.
Using bash I can easily print "who" ran a script using:
```
CALLER=$(ps ax | grep "^ *$PPID" | awk '{print $NF}')
echo $CALLER
```
Up to now I have been using this as a wrapper but it's not ideal. Is there a way to get this information from within C?
(I'm running... |
You should look atgetpidandgetppidfunctions from<unistd.h>.
```
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int
main(void)
{
printf("%ld%ld", (long)getpid(), (long)getppid());
return 0;
}
```
|
Here's the code which I ran on Mac OS X (10.8.1, 64-bit and 10.6.8, 32-bit) and Ubuntu (10.04, 32-bit):
```
printf("%d\n", atoi("2147483648"));
// returns -2147483648 in Mac OS X 10.8.1 and 10.6.8
// returns 2147483647 in Ubuntu
```
Here's what I found after some Googling:http://gynvael.coldwind.pl/?id=365
Is there... |
This is not surprising, because the behavioris not specifiedby the standard:
There is no standard specification on what happens when the converted value would be out of the range of representable values by an int.
Thestrtolfunction gives you more info in the return, as it setserrnotoERANGEwhen the value does not fit... |
I am having trouble creating a PixelBuffer in OpenGL ESv2.
If my config specifiesEGL_WINDOW_BITI can successfully calleglCreateContext. However, when usingEGL_PBUFFER_BITI am getting anEGL_BAD_CONFIG.
I am working with an embedded system where I will be calling OpenGL ESv2 to do some GPGPU. I do not have a windowi... |
I ended up writing a function to print out all my possible configurations. It turns out that even though glChooseConfiguration was returning GL_TRUE, it wasn't returning a configuration.
I wasn't getting any configurations.
OpenGL ES emulator apparently does not support PixelBuffers for OpenGL ES v2, only v1
|
I wish to suppress the default output of the functionsmbc_opendir(), and print only using printf.
gcc filename.c -lsmbclient
```
#include <libsmbclient.h>
#include <stdio.h>
void auth_fn()
{
}
int main(int argc,char* argv[])
{
int dirHandle;
if(smbc_init(auth_fn, 10)) /* Initialize things */
{
ret... |
Try debug level 0, it shall log only critical errors:smbc_init(auth_fn, 0)
|
I have 2 forms which actually output different results which I dont understand
```
int x = *(int*)&M[index]
```
compared to
```
int x = (int)M[index]
```
Can someone explain to me what is the difference?
|
If the datatype of M is not int[], they may differ, take the case where you have an array of 2 (16 bit) shorts, 0x0123 and 0x4567. The memory layout (big endian) would/may be;
```
0x01 0x23 0x45 0x67
```
In the latter case with M[0], you'd assign the short correctly to the integer since you'd read M[0] and convert i... |
How is short int (or short) and int different in C? They have the same size and range. If they are essentially the same, what is the use of having two data types?
|
Theymayhave the same size, but it is guaranteed thatintis equal to or bigger thanshort int.
|
Here SIMPLE_EX2 is being ORed with 0x0040 and the whole this providing as an address to SIMPLE_EX1. Is my understanding correct?
```
#define SIMPLE_EX1 (0x0040 | SIMPLE_EX2)
```
|
|is not a pipe sign in C. It's a bit-wise or. So this expression:
```
0x0040 | SIMPLE_EX2
```
Simply gets the value ofSIMPLE_EX2and sets it's 7thbit (from right) to 1.
Unlikely, but note that ifSIMPLE_EX2itself is an expression with an operator that has lower precedence than|, the overall expression may be interp... |
st_sizeisdefinedas being anoff_t.
off_tisdefinedas being asigned integer type.
Why isst_sizedefined as a signed type? Can it be negative? What does it mean if it is negative?
|
The best reason I can think of is to avoid introducing an unsigned version ofoff_tas an extra type; POSIX already has a ridiculous abundance of integer types with similar uses.
Aside from that, being able to store -1 inst_sizewhen size is not a concept that makes sense is probably useful; I'm not sure if any implemen... |
```
int num = atoi(argv[1]);
unsigned long times[num];
```
I have this code and I assumed it won't compile because I am trying to allocate the array using a value from a command line argument, which compiler doesn't know at the compile time.
But I compiled this code and it worked.
Can someone explain what is going o... |
C99 allows to allocate an array with a var. This is calledvariable length arraysakaVLA
I don't have the C99 in my hand, the section is 6.7.5.2 in C99, and the following links are from the internet.
vla - wikipedia
c99 - wikipedia
be aware that vla is not supported in c++, more informationhere
|
I'm trying to format a 10-digit Unix time stamp (currently a string) using ctime.
However, ctime() expects a parameter of type time_t, not a string.
What must I do before I can use ctime?
In other words, can I easily convert the string into a time_t?
|
You're saying you have something like 1346426869 as a string and want it to be a time_t?
```
time_t raw_time = atoi("1346426869");
printf("current time is %s",ctime(&raw_time));
> current time is Fri Aug 31 11:27:49 2012
```
|
There'ssyscallwhich allows indirect system calls in Linux. What are the reasons to use it - and why is it better than direct call to the function?
|
Sometimes the kernel adds system calls and it takes a while for the C library to support them.
Or maybe you are compiling on an old Linux distribution, but want to run on a newer one.
Example code:
```
// syscall 277 is sync_file_range() on x86_64 Linux. The header
// files lack it on scc-suse10 where we compile, ... |
I need to know which perl script is using my C CLI.
Using bash I can easily print "who" ran a script using:
```
CALLER=$(ps ax | grep "^ *$PPID" | awk '{print $NF}')
echo $CALLER
```
Up to now I have been using this as a wrapper but it's not ideal. Is there a way to get this information from within C?
(I'm running... |
You should look atgetpidandgetppidfunctions from<unistd.h>.
```
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int
main(void)
{
printf("%ld%ld", (long)getpid(), (long)getppid());
return 0;
}
```
|
Here's the code which I ran on Mac OS X (10.8.1, 64-bit and 10.6.8, 32-bit) and Ubuntu (10.04, 32-bit):
```
printf("%d\n", atoi("2147483648"));
// returns -2147483648 in Mac OS X 10.8.1 and 10.6.8
// returns 2147483647 in Ubuntu
```
Here's what I found after some Googling:http://gynvael.coldwind.pl/?id=365
Is there... |
This is not surprising, because the behavioris not specifiedby the standard:
There is no standard specification on what happens when the converted value would be out of the range of representable values by an int.
Thestrtolfunction gives you more info in the return, as it setserrnotoERANGEwhen the value does not fit... |
I am having trouble creating a PixelBuffer in OpenGL ESv2.
If my config specifiesEGL_WINDOW_BITI can successfully calleglCreateContext. However, when usingEGL_PBUFFER_BITI am getting anEGL_BAD_CONFIG.
I am working with an embedded system where I will be calling OpenGL ESv2 to do some GPGPU. I do not have a windowi... |
I ended up writing a function to print out all my possible configurations. It turns out that even though glChooseConfiguration was returning GL_TRUE, it wasn't returning a configuration.
I wasn't getting any configurations.
OpenGL ES emulator apparently does not support PixelBuffers for OpenGL ES v2, only v1
|
I wish to suppress the default output of the functionsmbc_opendir(), and print only using printf.
gcc filename.c -lsmbclient
```
#include <libsmbclient.h>
#include <stdio.h>
void auth_fn()
{
}
int main(int argc,char* argv[])
{
int dirHandle;
if(smbc_init(auth_fn, 10)) /* Initialize things */
{
ret... |
Try debug level 0, it shall log only critical errors:smbc_init(auth_fn, 0)
|
I have 2 forms which actually output different results which I dont understand
```
int x = *(int*)&M[index]
```
compared to
```
int x = (int)M[index]
```
Can someone explain to me what is the difference?
|
If the datatype of M is not int[], they may differ, take the case where you have an array of 2 (16 bit) shorts, 0x0123 and 0x4567. The memory layout (big endian) would/may be;
```
0x01 0x23 0x45 0x67
```
In the latter case with M[0], you'd assign the short correctly to the integer since you'd read M[0] and convert i... |
How is short int (or short) and int different in C? They have the same size and range. If they are essentially the same, what is the use of having two data types?
|
Theymayhave the same size, but it is guaranteed thatintis equal to or bigger thanshort int.
|
Here SIMPLE_EX2 is being ORed with 0x0040 and the whole this providing as an address to SIMPLE_EX1. Is my understanding correct?
```
#define SIMPLE_EX1 (0x0040 | SIMPLE_EX2)
```
|
|is not a pipe sign in C. It's a bit-wise or. So this expression:
```
0x0040 | SIMPLE_EX2
```
Simply gets the value ofSIMPLE_EX2and sets it's 7thbit (from right) to 1.
Unlikely, but note that ifSIMPLE_EX2itself is an expression with an operator that has lower precedence than|, the overall expression may be interp... |
st_sizeisdefinedas being anoff_t.
off_tisdefinedas being asigned integer type.
Why isst_sizedefined as a signed type? Can it be negative? What does it mean if it is negative?
|
The best reason I can think of is to avoid introducing an unsigned version ofoff_tas an extra type; POSIX already has a ridiculous abundance of integer types with similar uses.
Aside from that, being able to store -1 inst_sizewhen size is not a concept that makes sense is probably useful; I'm not sure if any implemen... |
I have 2 forms which actually output different results which I dont understand
```
int x = *(int*)&M[index]
```
compared to
```
int x = (int)M[index]
```
Can someone explain to me what is the difference?
|
If the datatype of M is not int[], they may differ, take the case where you have an array of 2 (16 bit) shorts, 0x0123 and 0x4567. The memory layout (big endian) would/may be;
```
0x01 0x23 0x45 0x67
```
In the latter case with M[0], you'd assign the short correctly to the integer since you'd read M[0] and convert i... |
How is short int (or short) and int different in C? They have the same size and range. If they are essentially the same, what is the use of having two data types?
|
Theymayhave the same size, but it is guaranteed thatintis equal to or bigger thanshort int.
|
Here SIMPLE_EX2 is being ORed with 0x0040 and the whole this providing as an address to SIMPLE_EX1. Is my understanding correct?
```
#define SIMPLE_EX1 (0x0040 | SIMPLE_EX2)
```
|
|is not a pipe sign in C. It's a bit-wise or. So this expression:
```
0x0040 | SIMPLE_EX2
```
Simply gets the value ofSIMPLE_EX2and sets it's 7thbit (from right) to 1.
Unlikely, but note that ifSIMPLE_EX2itself is an expression with an operator that has lower precedence than|, the overall expression may be interp... |
st_sizeisdefinedas being anoff_t.
off_tisdefinedas being asigned integer type.
Why isst_sizedefined as a signed type? Can it be negative? What does it mean if it is negative?
|
The best reason I can think of is to avoid introducing an unsigned version ofoff_tas an extra type; POSIX already has a ridiculous abundance of integer types with similar uses.
Aside from that, being able to store -1 inst_sizewhen size is not a concept that makes sense is probably useful; I'm not sure if any implemen... |
```
int num = atoi(argv[1]);
unsigned long times[num];
```
I have this code and I assumed it won't compile because I am trying to allocate the array using a value from a command line argument, which compiler doesn't know at the compile time.
But I compiled this code and it worked.
Can someone explain what is going o... |
C99 allows to allocate an array with a var. This is calledvariable length arraysakaVLA
I don't have the C99 in my hand, the section is 6.7.5.2 in C99, and the following links are from the internet.
vla - wikipedia
c99 - wikipedia
be aware that vla is not supported in c++, more informationhere
|
```
#include<stdio.h>
int main()
{
char str[25] = "helloworld";
printf("%s %s", &str+2,str+2);
return 0;
}
```
What is the difference between &str+2 and str+2 here as str=&str. please help me.
thanks
|
when you have an array:str[xxx]strgive you the memory address of the beginning of the array sostr+2would point to"lloworld".&strgives youthe address where str is stored. So by printing &str+2 you an have unexpected behaviors.
|
I want to find "\r\n\r\n" in a HTTP header.
I know it's at the end of the packet, so if I reverse search "\r\n\r\n" I'll get good performance.
Is there a function implement reverse search in C or C++ ?
If so, which one?
Thanks.
|
Reverse searching for "\r\n\r\n" might give you wrong result. It is not correct logic, because the HTTP body might contain "\r\n\r\n".
|
I need a log of all the memory locations a C program modifies during its execution. The problem is a bit more involved than watching a region of memory usinggdb/valgrind, because I do not have thestartorendaddresses for the memory region. Basically, whenever and wherever the program does a memory update (in the form... |
You can monitor memory stores, reads, contents of registers, etc. withPin, a tool created by Intel. Here is aproject from MIT that simulates a processor cache(instruction and/or data). Pin is used to create a detailed instruction trace, and the trace is then used as input to the cache simulator.
|
When you type a character in EditBox - MessagBox c create the character.
He can not understand - I will be grateful for the help.Code here
|
You have to catch either
EN_CHANGE:
Sent when the user has taken an action that may have altered text in an edit control. Unlike the EN_UPDATE notification code, this notification code is sent after the system updates the screen.
or
EN_UPDATE:
Sent when an edit control is about to redraw itself. This notification c... |
I have to delete the file/directory pointed to bypath. So I callremove(path), and if this fails withENOTEMPTY, then it is a non-empty directory and I handle it accordingly.
```
status = remove(path);
if (status == -1 && errno == ENOTEMPTY)
ftw(path, recursive_dir_delete, 64);
```
On compilation, I getENOTEMPTY u... |
Error constants are declared in the C standard header<errno.h>. You have to#includethat file in your project.
|
I have two.cfiles: one contains the main and the other contains all of my functions.
In my main I have a part where I want to read a char at a time the loop looks like this:
```
while(ch = ReadFile(fp)) != EOF)
{
// Code
}
```
wherechis an integer (int ch;) andfpis a file pointer (FILE* fp;).
And (different.cf... |
Update:-
The famousgetcfrom<stdio.h>is a solution:-
```
while((ch = getc(fp)) != EOF)
{
//...
}
...
int ReadFile(FILE* fp)
{
//Do what you wish... :)
return getc(fp);
}
```
Declared asint getc( FILE * _File);
|
I am looking for a library interface to allow me to check what has been posted to a serial port.
To be more precise, I am using a teensy 2.0 to interface with a button. I want to run code within the program without simulating a key press, and thought that printing something to serial would be a easy way to connect to... |
I've once usedRxTx libraryto establish a communication channel between PC and an external MCU via USB port. Worked fine : )
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:2GB limit on file size when using fwrite in C?
I realized that for my C compiler, the fread function can only correctly read a file smaller than 2GB (2147483648). I am wondering whether we could read >2GB file at all. Thanks
|
You need to compile withlarge file support. Alternatively, on some platforms you can usefopen64.
|
I am writing a program to read data from a Bluetooth USB dongle. I am using Linux, so I suspect there may be a POSIX library to read from it, or perhaps there is a predefined file descriptor for each USB drive. How do I read a stream of data from a USB port in C?
|
The most common way of interacting with random USB device islibusb. This provides low-level access to the device, so if you want something more complex (for example, if it's an actual USB drive with a filesystem on it), you might want to use some existing driver for the device rather than trying to interact with it ... |
I have achar buf[3];array where I need to put:buf[0] = chwherechis anint. But the compiler give the following warning:
conversion to ‘char’ from ‘int’ may alter its value
How do I remove this? I tried cast tounsigned charbut no luck.
|
Use an explicit cast:
```
buf[0] = (char)ch;
```
|
For example, in Linux, I have a pointer pointing to a task_struct. Later, the task_struct might migrate or deleted. How do I know whether the pointer still points to a task_struct or not?
|
It's not possible.
Pointers only contain addresses, and generally it's not possible to determine whether or not a given address is "valid".
Sometimes you can ask the entity that gave you the pointer to begin with if it's still valid, but that of course depends on the exact details of the entity. The language itself ... |
In GNU-GCC with Linux this is working#define sprintfc(string, ...) sprintf(string+strlen(string), ##__VA_ARGS__)Is there definition with same effect for Visual Studio 2010?
|
Microsoft Visual C compilerdoes support variadic macros. However, the problem isthe GCC extension ##, which removes the leading comma if no arguments are passed.
Because sprintf() is never called without a second argument, your code should work fine if you just remove the ##.
|
Is there function likesprintf()in Linux Kernel (likeprintf()->printk())?
|
yes.https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/lib/vsprintf.c#n1828
```
int snprintf(char *buf, size_t size, const char *fmt, ...)
{
va_list args;
int i;
va_start(args, fmt);
i = vsnprintf(buf, size, fmt, args);
va_end(args);
return i;
}
EXPORT_SYMBOL(snprintf);
```... |
I need to implement an arithmetic algorithm for hexadecimal numbers. So I want every arithmetic operation i.e addition, multiplication, subtraction, and division to be performed in base 16.
Is there anyway to sort of set a base?
|
Please.
Modern computers work in binary, by directly operating on voltages that represent 1s and 0s. That's just they way they work, you can't change that in software.
What you can do is change the base used for I/O, so that you print out numbers in hexadecimal, for instance:
```
int a = 47, b = 95;
int c = a + b; ... |
I have a simple program, for learning purposes, yet I keep on getting null returned when I realloc from allocated array.
```
#include <stdio.h>
#include <stdlib.h>
void main()
{
char *ptr, *retval;
ptr = (char *)calloc(10, sizeof(char));
if (ptr == NULL)
printf("calloc failed\n");
else
... |
It works as expected for me:
```
calloc successful
realloc successful
*** glibc detected *** double free or corruption
```
The code looks fine, assuming the double free was intentional. Don't callfree(ptr)since you've already released it by reallocating it.
|
I am adding a new protocol to the existing embedded system on ARM cortex processor. I need to do a load test and performance test after adding the new protocol to earlier system. The source code is in C and C++.
Please let me know if any free test code to do a load and performance test, network I/O test etc on this e... |
For system performance profiling you can useoprofileorgprof.
For network profiling you can useetherealornetstat.
For I/O statistics you can useiostatorsar.
For CPU profiling you can usempstat.
These are only a few tools. I'm sure there are more options available.
|
Let's take this example code:
```
#include <stdio.h>
int main(void){
int x = 1;
if(*(char *)&x == 1) printf("little-endian\n");
else printf("big-endian\n");
return 0;
}
```
I have seen this (or similar one) instruction*(char *)&xmultiple times and now i want to completely understand what does it mea... |
You're about right, but a better listing would be:
Take the address ofxConvert address into a pointer to characterDereference that pointer, i.e. read the firstcharat&xCompare character value to integer1
Note that this is rather edgy code, the read value will depend on the machine's byte endianness.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:How is string.find implemented in CPython?
I have read many posts here in stack-overflow comparing the performance of sub-string search (e.g.Python string search efficiency,Is this the most efficient way to search for a substring?,substrin... |
The actual cpython string search implementation is here:
http://hg.python.org/cpython/file/tip/Objects/stringlib/fastsearch.h
It appears to use Boyer-Moore.
|
I am porting an application(in C language) from HP-UX to Linux(icc compiler). i have a problem with pstat.h. It's there only in HP-UX but not in Linux and im getting error "pstat_getproc is undeclared". Is there any alternate solution to this? Is there any substitute for sys/pstat.h? As of now I am planning to replace... |
There is no direct equivalent; the whole family ofpstatfunctions is extremely HP/UX specific. Probably the closest equivalent is the/procinterface -- to get information on the current process, for instance, one can examine the pseudofiles in/proc/self.
You will, indeed, probably need to replace most of the code which... |
In C, is there a difference between integer division a/b and floor(a/b) where both a and b are integers?
More specifically what happens during both processes?
|
a/bdoes integer division. If eitheraorbis negative, the result depends on the compiler (rounding can go toward zero or toward negative infinity in pre-C99; in C99+, the rounding goes toward 0). The result has typeint.floor(a/b)does the same division, converts the result to double, discards the (nonexistent) fractional... |
I have written a code that reads from a file named network.dat
The code I wrote is
```
f = fopen("network.dat", "r");
if(f == NULL)
exit(1);
int read, N;
printf("%p\n", f);//output file pointer, included this just to check if file is opened properly
fscanf(f, "%d%d", &N, &read);//error here
... |
Your scanf() format string is incorrect. "%d,%d" looks for two integers separated by a comma. If you want to read two integers separated by whitespace, just do "%d%d".
|
It's been a while since I start programming in C, however, I still feel confused aboutunsigned. If we compiled this code:
```
#include <stdio.h>
int main(int argc, char **argv)
{
unsigned int x = -1;
return 0;
}
```
both gcc and VC++ don't raise any error or even a warning regarding using negative number w... |
It is NOT just a hint. The following two snippets should behave differently:
Signed int:
```
int x = -1;
printf("%d\n", x > 0); // prints 0
```
Unsigned int:
```
unsigned int x = -1;
printf("%d\n", x > 0); // prints 1
```
And you could probably come up with 5 more examples where the signedness matters. For ex... |
I work with Microchip PIC microcontrollers. I'm trying use clang for autocompletion in Vim.
Of course, I need to make clang to be able to compile my sources. The trouble is that PIC compilers are specific and have some special attributes, for which clang generates warnings.
Here's part of PIC header file:
```
exter... |
This should disable warnings generated by-Wattributes:
```
clang -Wno-attributes
```
|
I am using DevC++ as my compiler on Windows XP. Here is my code:
```
#include<stdio.h>
int main(void){
int a;
printf("%d\n", a);
int b = a;
a = 10;
printf("%d %d %d", a, b, a);
getch();
return 0;
}
```
Outputs:
```
2
10 2 10
```
I don't understand why the variableagets the value2.
|
```
int a;
printf("%d\n", a);
```
A uninitialized object has an indeterminate value. Accessing an uninitialized object is undefined behavior. If you try to print its value, you can get2printed, or42or your application can crash.
|
I have this struct:
```
struct foo {
char *a;
char *b;
char *c;
char *d;
};
```
it's possible allocate space for struct itself and its members instead of e.g,
```
struct foo f;
f.a = malloc();
f.b = malloc();
f.c = malloc();
f.d = malloc();
strcpy(f.a, "a");
strcpy(f.b, "b");
//..
```
something like this(o... |
You can certainly allocate memory for the struct itself and its members in one go, if that's what you're asking. You just have to know how much you're going to need it (in total) and take care of any possible alignmentation issues (not present in this particular case, though).
```
struct foo *f = malloc(sizeof *f + s... |
Theluasql.sqlite3module has been compiled into my C program successfully, statically linked. But, it seems the module has not been registered yet. The call ofrequire 'luasql.sqlite3'always fails in Lua scripts.
Some other modules callluaL_registerto register themselves. ButluaL_registeris not called inluaopen_luasql_... |
Here is the way of putting luaopen_ functions into the package.preload table.
```
lua_getfield(L, LUA_GLOBALSINDEX, "package");
lua_getfield(L, -1, "preload");
lua_pushcfunction(L, luaopen_socket_core);
lua_setfield(L, -2, "socket.core");
```
|
```
main()
{
FILE *fp;
char c;
int count=1;
fp=fopen("D:\file.txt","r");
printf("%d ",count);
c = fgetc(fp);
while(c!=EOF)
{
if(c=='\n')
{
count++;
printf("\n%d",count);
}
putchar(c);
c=fgetc(fp);
}
... |
You are also printing the newline you just read from the file,
Change
```
if(c=='\n') {
count++;
printf("\n%d ",count);
}
putchar(c);
```
to
```
if(c=='\n') {
count++;
printf("\n%d",count);
} else {
putchar(c);
}
```
Alternativly, don't print the newline when you print the line number,
```
putchar(c);
if(c... |
Where can we write code like
```
struct Foo
{
int bar;
int baz;
} foo()
{
}
```
C89/C90? C99? C11? Or maybe it's K&R only?
And what about this
```
void foo(bar, baz)
int bar;
int baz;
{
}
```
|
It's standard since C89. In K&R C, it was not possible to return structs, only pointers to structs.
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:Writing GUI applicatins on Mac OS X with c++
I am looking for an easy to use program/framework for making c++ GUI on a mac.
|
Qt is a very popular C++ GUI framework that targets Mac (and Windows and Linux and mobile)
http://qt.nokia.com/
|
```
#include<iostream>
#include<cstdio>
#define M 1000000007
using namespace std;
long long int power(int a,int b)
{
if(b==0)
return 1;
else if(b==1)
return a;
else if(b%2==0)
return power((a*a)%M,b/2);
else
return (power((a*a)%M,b/2)*a)%M;
}
```
In this function when ... |
In(a*a)%M, a*a probably overflows before computing the remainder. And starting with 2, the overflow producing 0 doesn't surprise me. You need to work with a type able to represent (M-1)*(M-1), i.e. 1000000012000000036 whileintis commonly limited to 2147483647.long long(standard in C since 99 and C++ since 11, common e... |
Forint a, b, I know that when there is exactly one ofaandbis negative, the result ofa / banda % bis machine dependent. But do I always have(a / b * b) + a % b == awhenbis not zero?
|
C++11 §5.6[expr.mul]/4 specifies:
If the quotienta/bis representable in the type of the result,(a/b)*b + a%bis equal toa.
C11 §6.5.5/6 specifies the same with slightly different phrasing:
If the quotienta/bis representable, the expression(a/b)*b + a%bshall equala; otherwise, the behavior of botha/banda%bis undefine... |
I have implemented a bash like shell in c language. I support<>>>;|and&. My next task is to add a support for(and)basically a subshell. How can we implement a subshell. I can fork and put parent on wait, pass environment variables but I need to add support to commands like(ls | sort) ; ls(I admit that the command does... |
TO implement this we parse the command line and make a tree like structure. This can be done with the help oflexandyaccand as barmer suggested we can name each node assubshellpipelinesemicolon. After parsing the whole command line pass the pointer to the whole node to the main program. To run a subshellforkand then re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.