question
stringlengths 25
894
| answer
stringlengths 4
863
|
|---|---|
Where can I find the code for malloc my gcc compiler is using at the moment? I actually want to write my own malloc function which will be a little different from the original one. I know I can use hooks et all, but I want to see the real code.
|
The POSIX interface of malloc isdefined here.
If you want to find out how the C library in GNU/Linux (glibc) implementsmalloc, go and get the source code fromhttp://ftp.gnu.org/gnu/glibc/or browsethe git repositoryand look atthemalloc/malloc.cfile.
There is also the base documentation of theMemory Allocator by Doug Leathat describes the theory of am(emory)alloc(ator) (read this carrefully, and then decide if you really need to implement your own malloc).
|
I want to use a byte variableito execute a bit of code 256 times. The line below loops indefinitely, is there a tidy alternative that would work?
```
for (i = 0; i < 255; i++){
```
Hopefully without using:
a 16 bit variable, (or any extra bits at all)nested loopswhile(1)break;statements
Thanks
|
```
i = 0;
do {
f(i);
} while(i++!=255);
```
|
I am debugging some code and there is l_pid = 0 always for setting file locks.. It seems odd to me.. Is this correct?Documentation doesnt say about 0 zero value ..
|
l_pidis only meaningful when getting the lock status withF_GETLK; when setting a lock, if it succeeds then you know what pid owns it. :) (And the buffer is returned unmodified it it fails.)
|
I have this function:
```
void receive_message(int sock, char buffer[]) {
int test = recv(sock, buffer, strlen(buffer), 0);
buffer[test] = '\0';
}
```
the third argument of the functionrecv()is not working. apparently i cannot usestrlen()because the buffer don't have a\0.sizeof()didn't help me either. i'm wishing i can do this without passing a third argument to my functionreceive_message().
thank you.
|
You're hoping in vain; C arrays don't have that much structure. You need to pass the size yourself.
|
This line isn't working as expected:
```
uartPushPos = (uartPushPos + 1) % UART_TX_BUFF_LENGTH;
```
However this below, which in theory does the same, does work:
```
//if (uartPushPos == UART_TX_BUFF_LENGTH - 1){
if (uartPushPos >= UART_TX_BUFF_LENGTH - 1){
uartPushPos = 0;
} else {
uartPushPos++;
}
```
UartPopPos is type char, and UART_TX_BUFF_LENGTH is a preprocessor variable set to 16.
Why does the second code segment work, but not the first?
If it makes much of a difference, I'm using the SourceBoost BoostC compiler for the PIC microcontroller 16f.
Thanks
|
They are different ifuartPushPosis less than 0, or if it is more than or equal toUART_TX_BUFF_LENGTH.
See alsoMod of negative number is melting my brain
|
I found a C source in these files with.wextensions. It seems like a mix of TeX code
and C Programming Language.Thisis an example of these sources.
How can I compile?
PS: Excuse me for the silly question but I didn't found any documentation
|
Use Knuth's CWEB, a literate-programming tool. You can download it fromhere.
|
I have warning:
```
note: expected ‘float (*)[100]’ but argument is of type ‘float (*)[100][100]’
```
My function looks like:
```
int readfile (float macierz_A[MAXSIZE][MAXSIZE], float macierz_B[MAXSIZE][MAXSIZE])
...
float A[MAXSIZE][MAXSIZE];
float B[MAXSIZE][MAXSIZE];
int r1;// = 3;
r1 = readfile(&A, &B);
```
Any idea?
|
Try to change this:
```
r1 = readfile(&A, &B);
```
Into this:
```
r1 = readfile(A, B);
```
Note that the & has been removed. Speaking in a very simple manner, you are passing a pointer to a multidimensional array, instead of the multidimensional array. (as you declared in the function declaration)
|
I have a very simple question regarding file write.
I have this program:
```
char buf[20];
size_t nbytes;
strcpy(buf, "All that glitters is not gold\n");
fd= open("test_file.txt",O_WRONLY);
write(fd,buf,strlen(buf));
close(fd);
```
What am confused is when I open the filetest_file.txtafter running this program I see some characters like^C^@^@^@^^^@after the line "All that glitters is not": Notice that portion of the buf is not written and those characters appear instead. Why is that so?
|
You're writing more than 19 chars in that buffer. Once you've done that, the behavior of your program is undefined. It could do whatever it wants.
Allocate a large enough buffer. It has to be able to fit all the letters plus a terminating0if you need to be able to treat it as a C string.
|
Dcraw contains a following algorithm to process image colors:https://gist.github.com/1047302.Is it a formal (named) image processing algorithm?
If not, what should I read to understand reasoning behind it?
|
It's not processing an image. It's generating a lookup table (curve[]) used to performgamma correction.
|
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed9 years ago.
I don't know if this is compiler specific but when I tried running the two expressions inDevC++
Wheni=c=b=0;i=i++ + ++cgives2whereasi=++i + c++gives1
Butb=i++ + ++candb=++i + ++cproduces the result1for both expressions.
I do know that incrementing a variable twice in the same expression results in an undefined value according to theCstandard specification but I'm curious how the compiler produces these output. Could someone please explain how and why?
|
i++ + ++c, thecis incremented (to 1), then0 + 1is stored ini, and finallyiis incremented, giving2.
++i + c++, theiis incremented (to 1), then1 + 0is stored ini, thencis incremented.
That's how I would understand what the compiler did, but as everyone else is saying, don't count on this behavior elsewhere.
|
I have the following snippet of C code:
```
#include <stdio.h>
void main(){
int a = 1308901095;
FILE *fp;
fp = fopen("file", "wb");
fwrite(&a, sizeof(int), 1, fp);
fclose(fp);
printf("Done\n");
}
```
This will write the "a" integer in file "file", in binary form.
How I can read this number in Python?
|
Try following.
```
from struct import *
f = open('file', 'rb')
print unpack('<i', f.read(4))[0]
f.close()
```
note that using '<' about your machine is little endian or not.
|
I am trying to implement classes implementing the wav playing, as explained inthis example. The relevant code part is here :
```
/* Setup for conversion */
wav_cvt.buf = malloc(wav_len * wav_cvt.len_mult);
wav_cvt.len = wav_len;
memcpy(wav_cvt.buf, wav_buf, wav_len);
/* We can delete to original WAV data now */
SDL_FreeWAV(wav_buf);
/* And now we're ready to convert */
SDL_ConvertAudio(&wav_cvt);
```
When a wav file finishes playing (I am not going to play it again), do I need to free the memory buffer that is malloc()-ed above? Or is it done automatically somewhere?
|
No, nothing is done automatically. You must free it.
|
I know .NET just introduced Async, but in Linux it is implemented at OS level, does Windows OS has equivalent or is it just simulated on .NET Framework level ?
|
Windows has several asynchronous I/O APIs. Overlapped I/O can be pretty much considered an extension of the regular I/O functions. And for high performance/scalability purposes, there's I/O Completion Ports.
(.NET's async has little to do with async I/O specifically. It's a language-level construct for doinganythingasynchronously)
|
How do I call utimes or futimes in a way that makes it ignore either the first or second times array argument.
i.e.
```
int utimes(const char *filename, const struct timeval times[2]);
struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* microseconds */
};
```
I remember figuring this out some time back. You had to set tv_sec to a special value to make it ignore the argument. Can anyone recall that or know how I do this?
|
Theutimesinterface is deprecated, and I don't know if it offers a way to do what you want. It was poorly standardized and the answer might vary between platforms. Instead you should useutimensatorfutimens:
http://pubs.opengroup.org/onlinepubs/9699919799/functions/utimensat.html
with the special value ofUTIME_OMIT.
|
I hear this a lot of times that: "inline functions in C expose internal data structures" and that is one of the reasons some people do not like them.
Can someone please explain, how?
Thanks in advance.
Lets say I have a program code.c and a function func(). I can 1) make func() inline - which will expose whatever I do with my data-structures in code.c 2) I can put func() in a library and provide that as a shared lib (which is not readable - I guess ?? :p) ---- Is this a correct analysis?
|
Since you put inline function definitions in a header file (unless used in a single cpp file), which would need to be included by consumers then I guess you are exposing the inner workings of your code.
But, since the alternative is usually macros, I doubt that is a good reason against them.
|
Just curious is there any technical limitation in having multiple return values for methods in languages like java, c, c++ or limitation is just by spec? In assembly language I understand callee can pop one value to register.
|
Because in the days of C there is/was a single register used to hold the return value.Because if you need more values, you can just return astruct, reference (in Java/C#), or pointer.Because you can use an out parameter.
Allowing multiple return values would add complexity, and it's simply worked around. There's no reason for it to be there. (Indeed, in C++ you can return atuple(from TR1, C++11, or boost) which effectively is multiple return values)
|
I am new to Linux kernel programming. I wish to develop a program to read USB drive information like its manufacturer name, capacity, etc. I know about descriptors and their attributes. But I don't understand how to enumerate USB drives connected to the system. I am looking for the function which initiates connection between kernel and USB port. How is it possible?
|
You don't need to program the kernel as such - in fact to read the device info you don't even need a device driver.
The USB system is different in the newer 2.6 kernels so a lot of the online tutorials may be out of date - but start herehttp://www.linux-usb.org/
If you do want to write a USB device driver see thisLinux journal tutorial
|
I'm implementing stack in C and I define pop function in C file:
```
int pop(int &x, int &y);
```
Xcode shows error (pointing on the first argument): Expected ')'
Any ideas why I have that problem? Thanks.
|
C doesn't have "pass by reference" like C++. To implement something like this,you need to use pointers:
```
int pop(int *x, int *y);
```
...and somewhere else, in a function...
```
int a, b;
int c = pop(&a, &b);
```
(It's hard to know exactly what syntax details to give without knowing more about what the arguments are meant to be.)
|
I am developing a C application using ncurses library in linux. my program cant distinguish between Alt and Esc keypresses. both return 27!
can you help me how I can distinguish between the two?
thank you
|
You need to incorporate a short delay after the^[in order to see if there are further characters incoming. If not, thenEschas been pressed.
|
I want to implement some custom library functions in Linux. For example, I want to implement my ownpthread_mutex_lock,pthread_mutex_unlock,mallocandfreefunctions. I've readLD_PRELOADcan be used to use your own custom functions, although I haven't got into the details.
But I have one question, I also want to use the original functions within my new implementations. What would be the trick to do that, as both would have the same names?
|
You could use thedlopenfunction to open the library you replace (or use RTLD_NEXT if it is already loaded, see comments), and then usedlsymfunction to find the address of the function in that library that you want to call.
|
I have been asked in an interview is it valid declaration on a machine which is not 16 bit??
Below is the declaration,
```
unsigned int zero = 0;
unsigned int compzero = 0xFFFF;
```
|
They are bothvaliddeclarations, yes, inasmuch as there's no syntax error.
However, if your intent is to get the complement of0(all bits inverted), you should use:
```
unsigned int zero = 0;
unsigned int compzero = ~zero;
```
With (for example) a 32-bitunsigned int,0xffffand~0are respectively:
```
0000 0000 0000 0000 1111 1111 1111 1111
1111 1111 1111 1111 1111 1111 1111 1111
```
|
I have a VPS (512 RAM max) on which I want to run a simple IRC bot.
I've written it in JAVA, but it turned out JVM is eating a tremendous amount of 144 MB ram.
The bot itself has a very low demand for memory, unlike JVM.
So the question is:
Is Java appropriate for this task? I'm not running any other java apps on this server so this seems to be an utter RAM waste.
Would it be better to just rewrite everything in c/c++ or is there a way to run small java programs with little JVM memory overhead?
Just to be sure we're not duplicating questions: -Xms and -Xmx are not going to help, see:Java seems to ignore -Xms and -Xmx options
|
the JVM is huge. write in C or C++ for a much smaller footprint.
or check out smaller VMs likehttp://jamvm.sourceforge.net/
|
Do these two statements compile equivalently: n % 2 == 0 and n & 1 == 0 ?
if not, is one more efficient?
|
No, they do not always give the same result. The C standard allows for ones' complement implementations, in which case they will give a different result for negativen.
|
I am passing my program inputs and I could see them in argv but getopt doesnt seem to have the argument that I expect.
This is how I run my prog: ./my_prog -X -f filename
```
<snip>
while ((opt = getopt(argc, argv, "Xf:eE:dD")) != EOF) {
switch (opt) {
case 'X':
case 'f':
if (optarg == NULL)
fput("no point of living", fp); << for debugging
</snip>
```
I always get optarg as null. WHY?
|
Your argument string does not have a : after the X (e.g. X:f) so optarg will always be null.
I'll also point out that generally in a switch statement you'll want a break after each case (generally, not always, but when parsing arguments usually), so:
```
switch ( ... ) {
case 'X': {
// do something
} break;
case 'f': {
// do something else
} break;
}
```
|
I have a void pointer calledptr. I want to increment this value by a number of bytes. Is there a way to do this?
Please note that I want to do this in-place without creating any more variables.
Could I do something likeptr = (void *)(++((char *) ptr));?
|
You cannot perform arithmetic on a void pointer because pointer arithmetic is defined in terms of the size of the pointed-to object.
You can, however, cast the pointer to achar*, do arithmetic on that pointer, and then convert it back to avoid*:
```
void* p = /* get a pointer somehow */;
// In C++:
p = static_cast<char*>(p) + 1;
// In C:
p = (char*)p + 1;
```
|
Problem Description
I'm writing module forAndroid (JAVA)that usenative code (C). InJAVAI have created Class"MyClass.java"and implement all functions and classes there, also I call loadLibrary function from that file.
Now I want to build something like dll in C only for Android JAVA in order to give it to other users and they can use my class and functions.
|
You probably want to create a library project that contains your Java and C stuff.http://developer.android.com/guide/developing/projects/index.html#LibraryProjects
Do you want it to be used at runtime or compile time?
|
how can I get the user name that auth by pam_ldap in C/c++?
I found "pam_get_user" API, but how can I get the pam_handle_t for this function?
Thanks
Dma
|
You get the handle by calling:
```
int pam_start(const char *service_name, const char *user,
const struct pam_conv *pam_conversation, pam_handle_t **pamh);
```
pamh- is an output parameter in above api.
Check more detailshere.
|
I am new to the cmake. I wrote a simple cmake file and ran it in the cmake GUI. But it is displaying as follows
Error in configuration files. Project Files may be invalid.
and then displaying
CMake Error: Error in cmake code at
C:/home/temp/Tutorial/CMakeLists.txt:1:
Parse error. Expected a newline, got identifier with text "project".
Configuring incomplete, errors occurred!
My CmakeList.txt has following :
```
cmake_minimum_required (VERSION 2.6)
project (Tutorial)
add_executable (Tutorial Tutorial.c)
```
Please help me.
|
What operating system are you on? Is it possible that you have the wrong kind of newline character in your file?
In all flavors of Windows (and DOS), the new line should be a carriage return (ASCII 13) and line feed (ASCII 10). On older Macs, the new line should be just a carriage return (ASCII 13). On Linux and Unix (including Mac OS X), the new line should be a line feed (ASCII 10).
|
Here is one program
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
unsigned char a=0x80;
printf("%d\n",a<<1);
}
```
The output of above is256Now here is one more version of above program
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
unsigned char a=0x80;
a=a<<1;
printf("%d\n",a);
}
```
The output of above is
```
0
```
As far as my understanding is I am not able to see any difference between the two?
i.e. why is output coming 256 in first one and 0 in second program what is the difference in statements in both?
|
On your platform,unsigned charis only 8 bits wide, soa << 1shifts the 1 out the left end when you assign it back to the narrowa. In theprintfcall, on the other hand,ais first promoted to an integer (which is wider than 8 bits on your platform) and thus the bit survives.
|
I'm finding it really annoying to have to disassemble large swathes of library code just to get enough context to see what is causing a crash. Is there any way that I can just hand objdump an address, and have it find the boundaries of the containing function for me?
EDIT: Better yet, can I have it disassemble an entire stack trace for me?
|
Something like this perhaps?
```
$ objdump -S --start-address=0x42 foo.o | awk '{print $0} $3~/retq?/{exit}'
```
It prints the dis-assembly listing starting from0x42till it finds aret(q), assuming theboundaryis marked byret(q)
|
Quoted fromngx_hash.c:
```
ngx_strlow(elt->name, names[n].key.data, names[n].key.len);
```
Which copies the lower case string toelt->name.
Hereeltis of typengx_hash_elt_t *:
```
typedef struct {
void *value;
u_short len;
u_char name[1];
} ngx_hash_elt_t;
```
As you seenameis only1char wide,IMO thengx_strlowwill cause buffer overflow,but it actually works with no problem,anyone can explain it?
|
Usually structure of this sort are defined so that the programmer (if she wanted len=100) can go:
```
ngx_hash_elt_t *X;
X = malloc(sizeof(ng_has_elt_t)+99);
```
In this case it is still valid and meaningful for the user and library to reference X.name because it is a pointer to the start of a string.
|
Are(bool)(i & 1)andi % 2 == 1always same whereiisint?
Note: saying always I mean for all platforms (even when a byte is 16 bit) and for all standards of C and C++.
Edit:
For all standards of C and C++ whereboolexist.
|
No.
1s' complement representation ofint, the representation of -1 is1 ... 10, so they differ.
Anyway,i % 2can be negative for negativei(indeed it's required to be in C99 when it's not 0), and hence not equal to 1 for negative odd numbers.
|
I found these work types of code:
```
hash_init.key = &hash_key_lc;
```
And
```
ls->handler = init_connection;
```
Here bothhash_key_lcandinit_connectionare functions,but one is with&the other not,why?
UPDATE
so they are the same thing,but what's the rational??
|
This is identical to the following question:In C, what is the difference between `&function` and `function` when passed as arguments?
The accepted answer there:
There is no difference. For evidence
see theC99 specification(section
6.7.5.3.8)."A declaration of a parameter as
‘‘function returning type’’ shall be
adjusted to ‘‘pointer to function
returning type’’, as in 6.3.2.1."
|
I want to start learning about creating apps/games on the iPad 2. I cannot find hardly anything about iPad 2 although I have found lots of resources for iPad 1 development. Basically, I want to ask if I was to create an iPad 1 application, can it be deployed onto iPad 2 for testing/debugging/release no questions asked?
Also, am I able to use other frameworks which allow me to use Java, C# or C++? if so, can you recommend anything?
Thanks very much,
Jamie.
|
There is not much difference between iPad 1 and 2. You should target both devices (as long as you don't need the few extras on iPad 2 like camera for example).
All iPad 1 software will run on iPad 2.
Edit: No native Java or C# on iOS, although there might be some projects making them work - but it's rather "hackyish". C++ is of course just fine, as is C.
|
I'm currently developing a C app in which I'll need to hash user's passwords. I know scrypt is currently one of the best methods to "hash" passwords (memory-bound, slow), but I can't seem to find a simple cross-platform C library that would do it for me.
And, since I'm neither a C expert or a cryptography/hashing expert, I'm afraid doing it myself will induce some obvious flaws in the system (it's easy to get these things wrong).
So, is there a C library that can do that, or, if not, other libraries that would implement similar solutions ? (bcrypt would work, although not as good as scrypt, ...)
|
Google says yes:scrypt_1.1.6.orig.tar.gz
(the relevant files seem to be in thelibsubfolder)
|
I have an image which captures 8 bit. I'm looking to convert the 8 bit values to 16 bit. I used the following
```
short temp16 = (short)val[i] << 8 ;
```
wherevalis an array of 8 bit samples.
The above statement makes noisy.
Can anybody suggest a method for 8bit to 16bit conversion?
|
Pure bitshifting won't give you pure white. 0xff << 8 == 0xff00, not 0xffff as expected.
One trick is to use val[i] << 8 + val[i] and remember proper datatypes (size, signedness). That way you get 0x00 -> 0x0000 and 0xff -> 0xffff.
|
And what is the best way to look up these pragma information in the internet? Google search comes up with a lot of noise (mainly the occurrence of the pragma in various source code repositories)
|
From what I can tell, and based on documentation fromApple(under the "Marking Symbols for Weak Linking" section),weak_importwhen used as an attribute specifies that a symbol is weakly-linked, either in a framework or something else. I don't know how it applies as a pragma, but I wouldguessit specifies that every symbol in that translation unit is weakly-linked.
|
When declaring an enum as shown below, do all C compilers set the default values asx=0,y=1, andz=2on both Linux and Windows systems?
```
typedef enum {
x,
y,
z
} someName;
```
|
Yes. Unless you specify otherwise in the definition of the enumeration, the initial enumerator always has the value zero and the value of each subsequent enumerator is one greater than the previous enumerator.
|
im trying to separate non-alphanumeric and alphanumeric from a string in C.this is my current code,but if i use this,it will detect all alphanumeric only,while at non-alphanumeric it will return null.so i cant detect at what index are all the non-alphanumeric at.
```
char data[] = "http://www.google.com";
char key[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
char *find;
find = strpbrk(data,key);
while(find != NULL){
printf("%c",*find);
find = strpbrk(find+1,key);
}
```
The output will be httpwwwgooglecom.Thats is what i partially want. i also trying to find where are all the non-alphanumeric at.
|
Have a look at the Cisalphafamily of routines.
|
I know it is a little bit off topic but I believe I can get the answer anyway here. What does "psz" stand for inpszBufferor the similar variable in C/C++ system library? I saw a lot of variables prefixed with "psz" and it looks like a pattern.
Thanks!
|
This isHungarian notation.psznormally stands for "(p)ointer to (s)tring, (z)ero-terminated".
|
strdup(null) dumps core.
Tried in on ubuntu and freeBSD both.
why? Shouldn't it return null?
```
char *b = NULL;
a = strdup(b);
```
This will dump core on strdup call.
|
That's quite ok.
Thedocumentationimplies that it's argument must be string, if it's something else, such as a null pointer, it's anyones guess what'll happen. In essence, you get undefined behavior when passing a NULL pointer to strdup.
It's quite normal for functions to yield undefined behavor if you pass them something you're not supposed to. Many standard C function such as strcpy, strlen does not accept null pointers either.
|
Beforeboost::shared_ptr, was it considered a bad practice to return a heap allocated pointer from a function, since the caller will be required to remember tofree()that object?
Or, was it considered "normal"?
|
I don't consider it bad practice, so long as your API also provides an equivalentXXX_free(orXXX_close,XXX_clearup, or whatever) function, that the client code can call when finished with the pointer.
That way, you have a consistent, symmetrical API, in the sense that responsibility for the lifetime of a heap object is maintained in one place.
This approach is also amenable to more-complex resource freeing. For example, if the pointer that gets returned is to a dynamically-allocated struct that in turn has members that point to dynamically-allocated memory, the entire cleanup procedure can be hidden/abstracted from the client code.
|
I'm finding it really annoying to have to disassemble large swathes of library code just to get enough context to see what is causing a crash. Is there any way that I can just hand objdump an address, and have it find the boundaries of the containing function for me?
EDIT: Better yet, can I have it disassemble an entire stack trace for me?
|
Something like this perhaps?
```
$ objdump -S --start-address=0x42 foo.o | awk '{print $0} $3~/retq?/{exit}'
```
It prints the dis-assembly listing starting from0x42till it finds aret(q), assuming theboundaryis marked byret(q)
|
Quoted fromngx_hash.c:
```
ngx_strlow(elt->name, names[n].key.data, names[n].key.len);
```
Which copies the lower case string toelt->name.
Hereeltis of typengx_hash_elt_t *:
```
typedef struct {
void *value;
u_short len;
u_char name[1];
} ngx_hash_elt_t;
```
As you seenameis only1char wide,IMO thengx_strlowwill cause buffer overflow,but it actually works with no problem,anyone can explain it?
|
Usually structure of this sort are defined so that the programmer (if she wanted len=100) can go:
```
ngx_hash_elt_t *X;
X = malloc(sizeof(ng_has_elt_t)+99);
```
In this case it is still valid and meaningful for the user and library to reference X.name because it is a pointer to the start of a string.
|
Are(bool)(i & 1)andi % 2 == 1always same whereiisint?
Note: saying always I mean for all platforms (even when a byte is 16 bit) and for all standards of C and C++.
Edit:
For all standards of C and C++ whereboolexist.
|
No.
1s' complement representation ofint, the representation of -1 is1 ... 10, so they differ.
Anyway,i % 2can be negative for negativei(indeed it's required to be in C99 when it's not 0), and hence not equal to 1 for negative odd numbers.
|
I found these work types of code:
```
hash_init.key = &hash_key_lc;
```
And
```
ls->handler = init_connection;
```
Here bothhash_key_lcandinit_connectionare functions,but one is with&the other not,why?
UPDATE
so they are the same thing,but what's the rational??
|
This is identical to the following question:In C, what is the difference between `&function` and `function` when passed as arguments?
The accepted answer there:
There is no difference. For evidence
see theC99 specification(section
6.7.5.3.8)."A declaration of a parameter as
‘‘function returning type’’ shall be
adjusted to ‘‘pointer to function
returning type’’, as in 6.3.2.1."
|
I want to start learning about creating apps/games on the iPad 2. I cannot find hardly anything about iPad 2 although I have found lots of resources for iPad 1 development. Basically, I want to ask if I was to create an iPad 1 application, can it be deployed onto iPad 2 for testing/debugging/release no questions asked?
Also, am I able to use other frameworks which allow me to use Java, C# or C++? if so, can you recommend anything?
Thanks very much,
Jamie.
|
There is not much difference between iPad 1 and 2. You should target both devices (as long as you don't need the few extras on iPad 2 like camera for example).
All iPad 1 software will run on iPad 2.
Edit: No native Java or C# on iOS, although there might be some projects making them work - but it's rather "hackyish". C++ is of course just fine, as is C.
|
I'm currently developing a C app in which I'll need to hash user's passwords. I know scrypt is currently one of the best methods to "hash" passwords (memory-bound, slow), but I can't seem to find a simple cross-platform C library that would do it for me.
And, since I'm neither a C expert or a cryptography/hashing expert, I'm afraid doing it myself will induce some obvious flaws in the system (it's easy to get these things wrong).
So, is there a C library that can do that, or, if not, other libraries that would implement similar solutions ? (bcrypt would work, although not as good as scrypt, ...)
|
Google says yes:scrypt_1.1.6.orig.tar.gz
(the relevant files seem to be in thelibsubfolder)
|
I have an image which captures 8 bit. I'm looking to convert the 8 bit values to 16 bit. I used the following
```
short temp16 = (short)val[i] << 8 ;
```
wherevalis an array of 8 bit samples.
The above statement makes noisy.
Can anybody suggest a method for 8bit to 16bit conversion?
|
Pure bitshifting won't give you pure white. 0xff << 8 == 0xff00, not 0xffff as expected.
One trick is to use val[i] << 8 + val[i] and remember proper datatypes (size, signedness). That way you get 0x00 -> 0x0000 and 0xff -> 0xffff.
|
And what is the best way to look up these pragma information in the internet? Google search comes up with a lot of noise (mainly the occurrence of the pragma in various source code repositories)
|
From what I can tell, and based on documentation fromApple(under the "Marking Symbols for Weak Linking" section),weak_importwhen used as an attribute specifies that a symbol is weakly-linked, either in a framework or something else. I don't know how it applies as a pragma, but I wouldguessit specifies that every symbol in that translation unit is weakly-linked.
|
When declaring an enum as shown below, do all C compilers set the default values asx=0,y=1, andz=2on both Linux and Windows systems?
```
typedef enum {
x,
y,
z
} someName;
```
|
Yes. Unless you specify otherwise in the definition of the enumeration, the initial enumerator always has the value zero and the value of each subsequent enumerator is one greater than the previous enumerator.
|
im trying to separate non-alphanumeric and alphanumeric from a string in C.this is my current code,but if i use this,it will detect all alphanumeric only,while at non-alphanumeric it will return null.so i cant detect at what index are all the non-alphanumeric at.
```
char data[] = "http://www.google.com";
char key[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
char *find;
find = strpbrk(data,key);
while(find != NULL){
printf("%c",*find);
find = strpbrk(find+1,key);
}
```
The output will be httpwwwgooglecom.Thats is what i partially want. i also trying to find where are all the non-alphanumeric at.
|
Have a look at the Cisalphafamily of routines.
|
I know it is a little bit off topic but I believe I can get the answer anyway here. What does "psz" stand for inpszBufferor the similar variable in C/C++ system library? I saw a lot of variables prefixed with "psz" and it looks like a pattern.
Thanks!
|
This isHungarian notation.psznormally stands for "(p)ointer to (s)tring, (z)ero-terminated".
|
strdup(null) dumps core.
Tried in on ubuntu and freeBSD both.
why? Shouldn't it return null?
```
char *b = NULL;
a = strdup(b);
```
This will dump core on strdup call.
|
That's quite ok.
Thedocumentationimplies that it's argument must be string, if it's something else, such as a null pointer, it's anyones guess what'll happen. In essence, you get undefined behavior when passing a NULL pointer to strdup.
It's quite normal for functions to yield undefined behavor if you pass them something you're not supposed to. Many standard C function such as strcpy, strlen does not accept null pointers either.
|
I found these work types of code:
```
hash_init.key = &hash_key_lc;
```
And
```
ls->handler = init_connection;
```
Here bothhash_key_lcandinit_connectionare functions,but one is with&the other not,why?
UPDATE
so they are the same thing,but what's the rational??
|
This is identical to the following question:In C, what is the difference between `&function` and `function` when passed as arguments?
The accepted answer there:
There is no difference. For evidence
see theC99 specification(section
6.7.5.3.8)."A declaration of a parameter as
‘‘function returning type’’ shall be
adjusted to ‘‘pointer to function
returning type’’, as in 6.3.2.1."
|
I want to start learning about creating apps/games on the iPad 2. I cannot find hardly anything about iPad 2 although I have found lots of resources for iPad 1 development. Basically, I want to ask if I was to create an iPad 1 application, can it be deployed onto iPad 2 for testing/debugging/release no questions asked?
Also, am I able to use other frameworks which allow me to use Java, C# or C++? if so, can you recommend anything?
Thanks very much,
Jamie.
|
There is not much difference between iPad 1 and 2. You should target both devices (as long as you don't need the few extras on iPad 2 like camera for example).
All iPad 1 software will run on iPad 2.
Edit: No native Java or C# on iOS, although there might be some projects making them work - but it's rather "hackyish". C++ is of course just fine, as is C.
|
I'm currently developing a C app in which I'll need to hash user's passwords. I know scrypt is currently one of the best methods to "hash" passwords (memory-bound, slow), but I can't seem to find a simple cross-platform C library that would do it for me.
And, since I'm neither a C expert or a cryptography/hashing expert, I'm afraid doing it myself will induce some obvious flaws in the system (it's easy to get these things wrong).
So, is there a C library that can do that, or, if not, other libraries that would implement similar solutions ? (bcrypt would work, although not as good as scrypt, ...)
|
Google says yes:scrypt_1.1.6.orig.tar.gz
(the relevant files seem to be in thelibsubfolder)
|
I have an image which captures 8 bit. I'm looking to convert the 8 bit values to 16 bit. I used the following
```
short temp16 = (short)val[i] << 8 ;
```
wherevalis an array of 8 bit samples.
The above statement makes noisy.
Can anybody suggest a method for 8bit to 16bit conversion?
|
Pure bitshifting won't give you pure white. 0xff << 8 == 0xff00, not 0xffff as expected.
One trick is to use val[i] << 8 + val[i] and remember proper datatypes (size, signedness). That way you get 0x00 -> 0x0000 and 0xff -> 0xffff.
|
And what is the best way to look up these pragma information in the internet? Google search comes up with a lot of noise (mainly the occurrence of the pragma in various source code repositories)
|
From what I can tell, and based on documentation fromApple(under the "Marking Symbols for Weak Linking" section),weak_importwhen used as an attribute specifies that a symbol is weakly-linked, either in a framework or something else. I don't know how it applies as a pragma, but I wouldguessit specifies that every symbol in that translation unit is weakly-linked.
|
When declaring an enum as shown below, do all C compilers set the default values asx=0,y=1, andz=2on both Linux and Windows systems?
```
typedef enum {
x,
y,
z
} someName;
```
|
Yes. Unless you specify otherwise in the definition of the enumeration, the initial enumerator always has the value zero and the value of each subsequent enumerator is one greater than the previous enumerator.
|
im trying to separate non-alphanumeric and alphanumeric from a string in C.this is my current code,but if i use this,it will detect all alphanumeric only,while at non-alphanumeric it will return null.so i cant detect at what index are all the non-alphanumeric at.
```
char data[] = "http://www.google.com";
char key[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
char *find;
find = strpbrk(data,key);
while(find != NULL){
printf("%c",*find);
find = strpbrk(find+1,key);
}
```
The output will be httpwwwgooglecom.Thats is what i partially want. i also trying to find where are all the non-alphanumeric at.
|
Have a look at the Cisalphafamily of routines.
|
I know it is a little bit off topic but I believe I can get the answer anyway here. What does "psz" stand for inpszBufferor the similar variable in C/C++ system library? I saw a lot of variables prefixed with "psz" and it looks like a pattern.
Thanks!
|
This isHungarian notation.psznormally stands for "(p)ointer to (s)tring, (z)ero-terminated".
|
strdup(null) dumps core.
Tried in on ubuntu and freeBSD both.
why? Shouldn't it return null?
```
char *b = NULL;
a = strdup(b);
```
This will dump core on strdup call.
|
That's quite ok.
Thedocumentationimplies that it's argument must be string, if it's something else, such as a null pointer, it's anyones guess what'll happen. In essence, you get undefined behavior when passing a NULL pointer to strdup.
It's quite normal for functions to yield undefined behavor if you pass them something you're not supposed to. Many standard C function such as strcpy, strlen does not accept null pointers either.
|
Beforeboost::shared_ptr, was it considered a bad practice to return a heap allocated pointer from a function, since the caller will be required to remember tofree()that object?
Or, was it considered "normal"?
|
I don't consider it bad practice, so long as your API also provides an equivalentXXX_free(orXXX_close,XXX_clearup, or whatever) function, that the client code can call when finished with the pointer.
That way, you have a consistent, symmetrical API, in the sense that responsibility for the lifetime of a heap object is maintained in one place.
This approach is also amenable to more-complex resource freeing. For example, if the pointer that gets returned is to a dynamically-allocated struct that in turn has members that point to dynamically-allocated memory, the entire cleanup procedure can be hidden/abstracted from the client code.
|
I'm making a trie and I need someone to tell me what's wrong with this code:
```
typedef struct node
{
struct node *letters[26]={0};
} node;
```
I want to make it so that in every reference of a node struct, the pointers are all null...
Your help would be greatly appreciated :) Thanks
|
You can't initialize a type. You can only initialize objects
```
typedef struct node {
struct node *letters[26];
} node;
node mynode = {0}; /* {{0}} or even {{0, 0, 0, 0, ...}} */
```
|
My server is creating a IPV6 socket.
On client I am creating a IPV4 socket.
Now, In the connect API on client side I am passing the socket descriptor of IPV4 and IPV6 address structure.
```
INET_connect( sock,(SocketAddress *)in6_addr,(int)sizeof( sockaddr_in6 ) ) == 0 )
```
where
```
struct sockaddr_in6 in6_addr;
```
I am getting error in connection. Is it due to this or some other reason ?
Please note that my server is IPV6(having an IPV6 address)
|
You must use an IPV6 socket to connect to an IPV6 address, or use a tunneling service which will translate traffic from IPV4 addresses to and from IPV6 addresses.
|
```
#include <stdio.h>
#include <unistd.h>
int main()
{
while(1)
{
fprintf(stdout,"hello-out");
fprintf(stderr,"hello-err");
sleep(1);
}
return 0;
}
```
The output of above on my machine is
```
hello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-errhello-err
```
I had to kill the program to stop it.
Is it the correct and expected behavior.
Or it is wrong.This was an interview question hence I am posting here.
|
This is the expected output:
The program loops forever because of thewhile (1)loop.stdoutis line-buffered (by default), so it only flushes to the console when a new-line character ('\n') is printed. As you aren't printing any new-line characters, you never see any of thehello-outtext.Howeverstderris not line-buffered (by default), so it updates the console on every newfprintf()call.
|
Suppose i have a device that passes the minimum requirements for android OS , now can i program the bootloader and all and run android OS in it?
the device is : LG gt350i
i wouldnt want to run android 3.0 , perhaps 1.6 or 2.1.
|
Since the code is open source, you can port it to anything you want, if you have the development tools for your device and can write drivers for it's peripherals. Unfortunately companies usually don't provide that tools for users (you can develop an app for their OS, but you can't change the OS itself), nor hardware spec that would allow you to do so.
|
Given a number, how can I create a unique key from that number. This key should never be repeated when given different number. and when the same number is provided it should give back the same key that it generated earlier, i need this in my application. pls can you suggest any algorithm
Edited : sorry guys i changed the Q when you guys were answering the Q i thought the above Q be a better way of asking, my Q is in my B-tree i am storing the ipaddress (src ip and dst ip) of ipv4 i am generating the key for that using the destination ip, for eg: if i have a address 172.28.6.100 i generate a key using the last two bytes as 600 (6*100) now i have to store even the ipv6 address how can i generate a key for that i need to generate a uniqe key for each address.
|
```
unsigned generate_key(int x) { return x; }
```
Always returns a different hash for a different input. This is anideal perfect hash function.
|
How can I remove the dot at the end of a line in C? This is my current code but it eliminates all dots, even in the middle of the word.
```
char *pc;
pc = strtok(acData, " .\n");
```
|
If your strings are of this format:word word word.Thenpc[strlen(pc) - 1]corresponds to\0andpc[strlen(pc) - 2]to the., so by doingpc[strlen(pc) - 2] = '\0';it will remove the..
If your strings contain\nthen you should dopc[strlen(pc) - 3] = '\0';.
|
For a 32 bit integer, how do I set say k low order bits in C?
|
Assuming you want to set theklowest bits of a 32-bit integerx, I believe this will work:
```
if( k > 0 ) {
x |= (0xffffffffu >> (32-k))
}
```
|
I found that in C language but I don't know other language it need to initialize an array to 0 or not.
```
for (i = 0; i < MAXSIZE; i++) {
a[i] = 0;
}
```
Is there a reason for doing this?
In what cases do I need to initialize an array to 0 and in what cases do I not?
|
The reason you do this is because the array would contain garbage values (the values previously stored at that memory location). Zeroing out is good practice because zero is a value that, when used incorrectly, causes problems that are easy to find and debug (NULL dereference and such). On the other hand, garbage values may give you the impression that your program works, only to have it crash in some unrelated part of the code because your incorrect usage of the garbage value clobbered some other memory location.
|
as I understood, In the next code:
```
int main () {
FILE * f1;
f1 = fopen("f1.txt","a");
for (i =0 ; i<10;i++) fprintf(f1,"%d ",i);
fclose(f1);
f1 = fopen("f1.txt","a");
for (i =0 ; i<10;i++) fprintf(f1,"%d ",i);
fclose(f1);}
```
I will get in File f1, the next serial:0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9. I didn't understand why. When I close the file, and open it again, it doesn't remember the end file. I expected that the second loop will override the text that was there before, and I will get just0 1 2 3 4 5 6 7 8 9. So - what happened?
|
It's because you open the file in mode "a", which stands for append. The new text gets added to the end of the file.
If you want to write over what's already there, replace the second fopen with:
```
f1 = fopen("f1.txt", "w");
```
"w" stands for write, and will replace what's already there with your new text.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:When do we need to use posix_memalign instead of malloc ?
When would you need "sizebytes of memory such that the allocation's base address is an exact multiple ofalignment" over just a simplemalloc()?
I believe it ismemalign()under Linux andposix_memalign()under Mac OS X/BSD.
|
One of the most common use cases is when working with SIMD code (SSE, AltiVec, AVX, Neon, etc) where you typically need all buffers to be aligned on a SIMD vector boundary (16 byte or 32 byte alignment).
Another common alignment requirement is virtual memory page alignment (4 kB typically).
|
I am not sure what is going on. Something related with buffering. The ... code ...
```
if (data->inbound){
//fwrite(buf, res, 1, stdout); //data->inbound);
char tmp[SOAP_BUFLEN+1];
memset(tmp,0,SOAP_BUFLEN+1);
if(len>0) {
memcpy(tmp, buf, minim(SOAP_BUFLEN,len) );
tmp[minim(SOAP_BUFLEN,len)] = '\0';
printf("%s\n",tmp);
//printf("-----------------\n");
}
```
when I use fwrite I see the output with no problems. When I use memcpy I see duplicate entries in the output? Do I need to fflush something?
At the end of the printf statement I see a portion of the tmp to be repeated.
|
You are using different length values for fwrite vs memcpy. Based on the code (and commented out code) here, memcpy uses the lesser oflenorSOAP_BUFLEN. fwrite usesres * 1. So I'd betlen != res.
|
Following program gives error
```
#include<stdio.h>
int main ()
{
int a=10,b;
a>=5?b=100:b=200;
printf("\n%d",b);
}
```
the error is
```
ka1.c: In function ‘main’:
ka1.c:5: error: lvalue required as left operand of assignment
```
now if I replace the line
```
a>=5?b=100:b=200;
```
by
```
a>=5?b=100:(b=200);
```
and then compile then there is no error.
So I wanted to know what is wrong with
```
a>=5?b=100:b=200;
```
|
The ternary operator (?:) hashigher precedencethan the assignment operator (=). So your original statement is interpreted as:
```
((a >= 5) ? (b = 100) : b) = 200;
```
Write it like this instead:
```
b = (a >= 5) ? 100 : 200;
```
This is idiomatic C. (The brackets around the condition are not really necessary, but they aid readability.)
|
I'm debugging my C program using dbx on Solaris, and I'd like to be able to see the contents of a data structure.
It's a local data structure in the function that's in scope, so typing "dump" shows a pointer to the structure. However, I'd like to look at the contents of various fields within it. How can I do that?
|
Generally the 'print' command offers the best functionality for this kind of thing.
If your local pointer variable is called 'p', then use "print *p". The argument to print can be any language expression, for example "print p->buf" or "print p->buf[3]"
|
I am getting a warning for the below code.
```
//someother class
#define EVENT_ID_DESCRIPTION_LEN 64
struct FILE_DESCRIPTIONS
{
uint32_t uFileID;
uint32_t uDescriptionLen;
int8_t szDescription[FILE_ID_DESCRIPTION_LEN];
};
//defined inside a function of someother class
int8_t chTemp[EVENT_ID_DESCRIPTION_LEN + 1];
strncpy(chTemp,pMsg->st.aDescriptions[nIndex].szDescription,EVENT_ID_DESCRIPTION_LEN);
```
warning: pointer targets in passing argument 1 of '_builtin__strncpy_chk' differ in signedness
The value from which i'm storing from is also uint8_t and that gets stored onto is also uint8_t.what might be the cause of this warning.
Thanks in advance.
|
Actually, your code is definingint8_t(signed int) and notuint8_t(unsigned int) as you think. Did you spotted it?
You have to change your variable to:
```
uint8_t chTemp[EVENT_ID_DESCRIPTION_LEN + 1];
```
|
Iserrnoon MSVC thread-safe?
According to the answers inthis questionPOSIX requires thaterrnois thread-safe. But MSVC is probably not POSIX compliant andMSDNdoes not tell anything about thread-safety. MSDN contradictory mentions thaterrnois declared asextern int errno;, but also as#define errno (*_errno())
|
Although MSVC is definitely not POSIX compliant,errnois implemented in the MSVC runtime (at least as of MSVC2008) in a threadsafe manner.
Although the documentation states that it isextern int errnoit's actually implemented as a#defineto a function which allows thread-safety to be imposed. If you step through this function in the disassembly window, it is clear that thread local storage is used.
Sadly I can't point to any official documentation that confirms this but such is life!
|
How do I change the location where .obj, .exe files are generated in visual studio?
I want these files to always be in a folder on the desktop
|
In the project properties, under Configuration Properties, you can set the Output directory and the intermediate directory.
|
I have a function which returns address as following
```
struct node *create_node(int data)
{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp->data=data;
temp->next=NULL;
printf("create node temp->data=%d\n",temp->data);
return temp;
}
```
where struct node is
```
struct node {
int data;
struct node *next;
};
```
How can I see in printf("") the address stored in temp?
UPDATEIf I check the adressed in gdb the addresses are coming in hex number format i.e.
0x602010 where as same address inprintf("%p",temp)is coming in a different number which is different from what I saw in gdb print command.
|
Use the pointer address format specifier%p:
```
printf("Address: %p\n", (void *)temp);
```
|
Is there a software/website where I can submit my C, C++ and Java codes and get statistics like the program execution time, memory used ? I'm interested in doing a comparision of the same code in different languages and getting an estimate of which data structures/operations are better suited for which language.
|
Do it yourself. On a *nix machine (e.g. Linux and OSX) just run from the terminal:
```
time java YourJavaProgram
```
or
```
time ./YourCProgram
```
On Windows, you canwrite a little batch scriptto do the equivalent.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:What should we do to prepare for 2038?
What is year 2038 problem?
How to find out if our code has that problem and solve it?
|
In C the standard 4-byte format assumes that the beginning of time is January 1, 1970, at 12:00:00 a.m. This value is 0.The maximum value of time before it rolls over to a negative (and invalid) value is 2,147,483,647, which translates into January 19, 2038. On this date, any C programs that use the standard time library will start to have problems with date calculations.To correct it simply recompile the programs with a new version of the library that uses 8-byte values for the storage format.
|
In21.6.7.1,21represents the some segment,6represents some lane inside that segment and so on and so forth. The individual values need to be extracted.
One way to represent this is string, any other way which is better and more convenient than string?
|
A structure with a four fields? An array of 4 elements, can also be an option.
|
I'm using C. How can I print the values of a member of an instance of a structure? Is it possible? At least is it possible in case of a structure declared as global variable (not a dynamically allocated one)?
|
```
set print objects on
p structVar
p *pointerToStructVar
```
Or, more explicitly:
```
p structVar.member
p pointerToStructVar->member
```
|
hi I'm programming a microcontroller using MikroC, and I have this variable which is less than 1024 (2^10bit) and I needed to convert thatint value;tounsigned char value8bits;and put the least significant bits in theunsigned char value2bits;
I was actually thinking of using >> bit shifting don't know how yet? so what do you think ?
|
```
10bitvar = 956;
8bitvar = (10bitvar >> 2) & 0xff;
2bitvar = (10bitvar & 0x03);
10bitvar = 1 1 1 0 1 1 1 1 1 0
(10bitvar >> 2) = ? ? 1 1 1 0 1 1 1 1
& & & & & & & & &
0xff = 1 1 1 1 1 1 1 1
----------------
8bitvar 1 1 1 0 1 1 1 1
10bitvar = 1 1 1 0 1 1 1 1 1 0
& & & & & & & & &
0x03 = 0 0 0 0 0 0 1 1
----------------
2bitvar 0 0 0 0 0 0 1 0
```
|
I am trying to access/proc/net/devfile with-r--r--r-- 1 root root 0privileges usingpopen. The code is as fairly as:
```
main(){
FILE *f;
f=popen("/proc/net/dev","r");
pclose(f);}
```
logged in as a root,after compiling & running the program, I get this:
sh: /proc/net/dev: Permission denied.
Can you please help me through this problem?
thank you
|
I think you're looking at this the wrong way, popen is to open a pipe from an application./proc/net/devis not an application but is a file. Try looking at fopen instead.
```
f=fopen("/proc/net/dev", "r");
fclose(f);
```
|
When run following code after compiling on gcc,I get segmentation fault.
```
#include <stdio.h>
#include <string.h>
int main(void)
{
struct emp
{
char *n;
int age;
};
struct emp e1={"David",23};
struct emp e2=e1;
strupr(e2.n);
printf("%s\n%s\n",e1.n,e2.n);
return(0);
}
```
|
String literals like"David"cannot be altered, which is what you're doing when you callstrupr. You should copy the string (e.g. withstrdup) before.
|
Well the title pretty much sums it up. I want to use something like asc("0") in C++, and want to make the program platform independent so don't want to use 48! Any help appreciated.
|
You can simply use single-quotes to make a character constant:
```
char c = 'a';
```
The character typeisa numeric type, so there is no real need forascandchrequivalents.
Here's a small example that prints out the character values of a string:
```
#include <stdio.h>
int main(int argc, char **argv) {
char str[] ="Hello, World!";
printf("string = \"%s\"\n", str);
printf("chars = ");
for (int i=0; str[i] != 0; i++)
printf("%d ", str[i]);
printf("\n");
return 0;
}
```
The output is:
```
string = "Hello, World!"
chars = 72 101 108 108 111 44 32 87 111 114 108 100 33
```
|
Sorry about this basic question, but why0x11is17in decimal(print(%d, 0x11)=17?
I search information about the way to convert from hex to dec, but it doesn't talk about this sort of numbers.
|
Just like "11" in base ten means "1 ten" and "1 one", "11" in base 16 (i.e. hex) means "1 sixteen" and "1 one" - or 17 in base 10.
|
Is there a software/website where I can submit my C, C++ and Java codes and get statistics like the program execution time, memory used ? I'm interested in doing a comparision of the same code in different languages and getting an estimate of which data structures/operations are better suited for which language.
|
Do it yourself. On a *nix machine (e.g. Linux and OSX) just run from the terminal:
```
time java YourJavaProgram
```
or
```
time ./YourCProgram
```
On Windows, you canwrite a little batch scriptto do the equivalent.
|
This question already has answers here:Closed12 years ago.
Possible Duplicate:What should we do to prepare for 2038?
What is year 2038 problem?
How to find out if our code has that problem and solve it?
|
In C the standard 4-byte format assumes that the beginning of time is January 1, 1970, at 12:00:00 a.m. This value is 0.The maximum value of time before it rolls over to a negative (and invalid) value is 2,147,483,647, which translates into January 19, 2038. On this date, any C programs that use the standard time library will start to have problems with date calculations.To correct it simply recompile the programs with a new version of the library that uses 8-byte values for the storage format.
|
In21.6.7.1,21represents the some segment,6represents some lane inside that segment and so on and so forth. The individual values need to be extracted.
One way to represent this is string, any other way which is better and more convenient than string?
|
A structure with a four fields? An array of 4 elements, can also be an option.
|
I'm using C. How can I print the values of a member of an instance of a structure? Is it possible? At least is it possible in case of a structure declared as global variable (not a dynamically allocated one)?
|
```
set print objects on
p structVar
p *pointerToStructVar
```
Or, more explicitly:
```
p structVar.member
p pointerToStructVar->member
```
|
hi I'm programming a microcontroller using MikroC, and I have this variable which is less than 1024 (2^10bit) and I needed to convert thatint value;tounsigned char value8bits;and put the least significant bits in theunsigned char value2bits;
I was actually thinking of using >> bit shifting don't know how yet? so what do you think ?
|
```
10bitvar = 956;
8bitvar = (10bitvar >> 2) & 0xff;
2bitvar = (10bitvar & 0x03);
10bitvar = 1 1 1 0 1 1 1 1 1 0
(10bitvar >> 2) = ? ? 1 1 1 0 1 1 1 1
& & & & & & & & &
0xff = 1 1 1 1 1 1 1 1
----------------
8bitvar 1 1 1 0 1 1 1 1
10bitvar = 1 1 1 0 1 1 1 1 1 0
& & & & & & & & &
0x03 = 0 0 0 0 0 0 1 1
----------------
2bitvar 0 0 0 0 0 0 1 0
```
|
I am trying to access/proc/net/devfile with-r--r--r-- 1 root root 0privileges usingpopen. The code is as fairly as:
```
main(){
FILE *f;
f=popen("/proc/net/dev","r");
pclose(f);}
```
logged in as a root,after compiling & running the program, I get this:
sh: /proc/net/dev: Permission denied.
Can you please help me through this problem?
thank you
|
I think you're looking at this the wrong way, popen is to open a pipe from an application./proc/net/devis not an application but is a file. Try looking at fopen instead.
```
f=fopen("/proc/net/dev", "r");
fclose(f);
```
|
When run following code after compiling on gcc,I get segmentation fault.
```
#include <stdio.h>
#include <string.h>
int main(void)
{
struct emp
{
char *n;
int age;
};
struct emp e1={"David",23};
struct emp e2=e1;
strupr(e2.n);
printf("%s\n%s\n",e1.n,e2.n);
return(0);
}
```
|
String literals like"David"cannot be altered, which is what you're doing when you callstrupr. You should copy the string (e.g. withstrdup) before.
|
Well the title pretty much sums it up. I want to use something like asc("0") in C++, and want to make the program platform independent so don't want to use 48! Any help appreciated.
|
You can simply use single-quotes to make a character constant:
```
char c = 'a';
```
The character typeisa numeric type, so there is no real need forascandchrequivalents.
Here's a small example that prints out the character values of a string:
```
#include <stdio.h>
int main(int argc, char **argv) {
char str[] ="Hello, World!";
printf("string = \"%s\"\n", str);
printf("chars = ");
for (int i=0; str[i] != 0; i++)
printf("%d ", str[i]);
printf("\n");
return 0;
}
```
The output is:
```
string = "Hello, World!"
chars = 72 101 108 108 111 44 32 87 111 114 108 100 33
```
|
Sorry about this basic question, but why0x11is17in decimal(print(%d, 0x11)=17?
I search information about the way to convert from hex to dec, but it doesn't talk about this sort of numbers.
|
Just like "11" in base ten means "1 ten" and "1 one", "11" in base 16 (i.e. hex) means "1 sixteen" and "1 one" - or 17 in base 10.
|
In the next code:
```
int i = 1;
fork();
i=i*2;
fork();
i=i*2;
fork();
i=i*2;
printf("%d\n", i);
```
Why8,8,8,8,8,8,8,8is printed, and not1,2,2,4,4,8,8,8? fork() duplicate the process, and print the i before each fork. What I miss?
|
Given the code shown, you should be seeing eight lots of 6 (you wrotei = i + 2;instead ofi = i * 2;for the last computation.
Since each process follows the same code path, each process will produce the same result.
To get the result you expected, you'd have to track whether eachfork()yielded the parent or child process:
```
int i = 1;
if (fork())
{
i=i*2;
if (fork())
{
i=i*2;
if (fork())
i=i*2; // + --> *
}
}
printf(|%d\n", i);
```
I'm assuming there are no problems with thefork()operation. It is also interesting to note that you could invert any or all of the conditions and end up with the same result.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.