question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I'm looking for solution in the C programming language to remove this warning:
Comparison between signed and unsigned warning
Instead of just do acasttounsignedin the variable ofinttype, I thought as the following:
```
#if MAX_NAME >= INT_MAX
size_t name_size = 0;
#define INT_TYPE size_t
#else
int name_size = 0... |
Your example is flawed: however you put it you should always usesize_twhen comparing against the result ofsizeof. I.e. there's no reason to makename_sizeinto anint.
As a general note, just use the "natural" signedness for that variable. It boils down to one question: isname_sizesupposed to ever be negative ?
|
I want to print the value of EOF in C .
```
char ch =getchar() ;
printf("%d",ch) ;
```
this correctly prints the value -1 when I type in CTRL + Z (I am working in windows).
While.
```
char ch ;
scanf("%c",&ch) ;
printf("%d",ch) ;
```
incorrectly prints 126 .
What is the reason for this unusual behaviour ?
|
You haven't checked the return value from scanf. I'll bet it was zero: no patterns matched.
The value "126" is the uninitialized value ofch.
Edit: on closer inspection ofthe man pagethe return value should beEOF. Note that that's thereturnvalue, not the value written toch.
|
I define below data type:
```
typedef int MyInt;
```
Then I hope to define a new data type based on size of MyInt, something like below code, but I can't find a solution for it.
```
#if sizeof(MyInt) == 2
typedef long MyLong;
#else
typedef short MyLong;
#endif
```
Could anybody help?
|
It's not the preprocessor's job to evaluatesizeof, that's done by the compiler which is a later stage in the process. Evaluatingsizeofneeds deep C knowledge that the preprocessor simply doesn't have.
You could (in theory) consider the preprocessor as a separate step, that doestext onlytransforms, in effect converting... |
It is well known that asm() is a way to put assembly code into c code, but it is said in some resource that "unless you use the 'long form' of asm(), which correctly declares to the compiler the C-language effects of your assembly code, you leave yourself open to the substantial risk that a different compiler version,... |
The "long form" most likely refers toGNU Extended Asm, where the user can specify constraints, input, output registers, as well as a clobber list to help the optimizing compiler in register allocation.
|
We have the code:
```
int arr[3][4];
```
Soarris:
An array of 3 elements, and every element is an array of 4 int.An array of 4 elements, and every element is an array of 3 int.
which one is right and why? How does it work with higher dimensional array? I suppose this is concerning operator precedence and associati... |
Your first interpretation is correct.
Such declarations are best parsed using theRight Left rule, which you can readhereandhere
$8.3.4 from the C++ draft Standard:
...
Example: consider int x[3][5]; Here x is a 3 × 5 array of integers.
...
Note: It follows from all this that arrays in C++ are storedrow-wise(last ... |
I have a DEBUG_PRINT macro defined in the header file for a shared object that I wrote that looks like this:
lib_mylib.h:
```
#ifdef DEBUG
#define DEBUG_TEST 1
#else
#define DEBUG_TEST 0
#endif
#define DEBUG_PRINT(fmt, args...) \
do { if (DEBUG_TEST) fprintf(stderr, "%s:%d:%s(): " fmt, \
__F... |
The preprocessor is strictly sequential, macros have to be definedbeforethey are used or checked for.
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:Stringification of a macro value
I want to write a C macro that takes a "sequence of characters" (for example,#define macro(sequence)) and return the quoted string"sequence", so the macro should create"\"sequence\"". I know I can do#sequen... |
```
#include <stdio.h>
#define QUOTE(seq) "\""#seq"\""
int main(void)
{
printf("%s\n", QUOTE(sequence));
return 0;
}
```
|
In an interview I was asked to write an insert function for linked list in such a way that after the insertion, the element towards the head side of the inserted element should be greater and the tail side should be smaller when compared to inserted element.
I had implemented the following steps in my code:
initiall... |
Sort is anO(n log n)operation. If you read the question carefully they never say the list should be sorted, so don't do the sort operation. What you should do instead is start with a new list with only your element, then for each element of the original list append it either to the front (if greater than the new eleme... |
I was trying to print the address of the pointer variable not the address where it is pointing to, could anyone assist me in achieving that?
Below is what I am trying but it is showing warning which i am not able to resolve.
Thanks!
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* y;
printf("%p\n... |
Your secondprintf()should take a"%p\n"format, and strictly a cast:
```
printf("%p\n", (void *)&y);
```
The number of machines where the cast actually changes anything is rather limited.
|
I am looking for a way to determine if a certain file contains a certain string. It can be a system call or a C function, it doesn't matter.
I tried with grep, but it doesnt return anything
```
//name is the directory entry name
char grepcmd[150];
strcpy(grepcmd,"grep -c hello ");
strcat(grepcmd, name... |
You are doing well.statusshould be zero if your given file with namenamecontainshellostring. Otherwise it should be nonzero value.
|
I declared an array:
char * words[1000] = {NULL};
And now I have a series of forked child processes adding words to that array, but they are not affecting the parent program. How can I change that?
|
Hmm, for your edit-case: Dont use fork, use threads, because then everything runs in one address-space...And of course, then use mutexes to protect your words-array...
|
I'm making a Mac OSX program where I need to take a snapshot (image file) the currently active window in Photoshop.
How would I go about this?
|
I ended up using Applescript inside Xcode to find photoshop and saving a copy of the current file. Not the best solution but it works.
|
I have a DEBUG_PRINT macro defined in the header file for a shared object that I wrote that looks like this:
lib_mylib.h:
```
#ifdef DEBUG
#define DEBUG_TEST 1
#else
#define DEBUG_TEST 0
#endif
#define DEBUG_PRINT(fmt, args...) \
do { if (DEBUG_TEST) fprintf(stderr, "%s:%d:%s(): " fmt, \
__F... |
The preprocessor is strictly sequential, macros have to be definedbeforethey are used or checked for.
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:Stringification of a macro value
I want to write a C macro that takes a "sequence of characters" (for example,#define macro(sequence)) and return the quoted string"sequence", so the macro should create"\"sequence\"". I know I can do#sequen... |
```
#include <stdio.h>
#define QUOTE(seq) "\""#seq"\""
int main(void)
{
printf("%s\n", QUOTE(sequence));
return 0;
}
```
|
In an interview I was asked to write an insert function for linked list in such a way that after the insertion, the element towards the head side of the inserted element should be greater and the tail side should be smaller when compared to inserted element.
I had implemented the following steps in my code:
initiall... |
Sort is anO(n log n)operation. If you read the question carefully they never say the list should be sorted, so don't do the sort operation. What you should do instead is start with a new list with only your element, then for each element of the original list append it either to the front (if greater than the new eleme... |
I was trying to print the address of the pointer variable not the address where it is pointing to, could anyone assist me in achieving that?
Below is what I am trying but it is showing warning which i am not able to resolve.
Thanks!
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* y;
printf("%p\n... |
Your secondprintf()should take a"%p\n"format, and strictly a cast:
```
printf("%p\n", (void *)&y);
```
The number of machines where the cast actually changes anything is rather limited.
|
I am looking for a way to determine if a certain file contains a certain string. It can be a system call or a C function, it doesn't matter.
I tried with grep, but it doesnt return anything
```
//name is the directory entry name
char grepcmd[150];
strcpy(grepcmd,"grep -c hello ");
strcat(grepcmd, name... |
You are doing well.statusshould be zero if your given file with namenamecontainshellostring. Otherwise it should be nonzero value.
|
I declared an array:
char * words[1000] = {NULL};
And now I have a series of forked child processes adding words to that array, but they are not affecting the parent program. How can I change that?
|
Hmm, for your edit-case: Dont use fork, use threads, because then everything runs in one address-space...And of course, then use mutexes to protect your words-array...
|
I'm making a Mac OSX program where I need to take a snapshot (image file) the currently active window in Photoshop.
How would I go about this?
|
I ended up using Applescript inside Xcode to find photoshop and saving a copy of the current file. Not the best solution but it works.
|
In an interview I was asked to write an insert function for linked list in such a way that after the insertion, the element towards the head side of the inserted element should be greater and the tail side should be smaller when compared to inserted element.
I had implemented the following steps in my code:
initiall... |
Sort is anO(n log n)operation. If you read the question carefully they never say the list should be sorted, so don't do the sort operation. What you should do instead is start with a new list with only your element, then for each element of the original list append it either to the front (if greater than the new eleme... |
I was trying to print the address of the pointer variable not the address where it is pointing to, could anyone assist me in achieving that?
Below is what I am trying but it is showing warning which i am not able to resolve.
Thanks!
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* y;
printf("%p\n... |
Your secondprintf()should take a"%p\n"format, and strictly a cast:
```
printf("%p\n", (void *)&y);
```
The number of machines where the cast actually changes anything is rather limited.
|
I am looking for a way to determine if a certain file contains a certain string. It can be a system call or a C function, it doesn't matter.
I tried with grep, but it doesnt return anything
```
//name is the directory entry name
char grepcmd[150];
strcpy(grepcmd,"grep -c hello ");
strcat(grepcmd, name... |
You are doing well.statusshould be zero if your given file with namenamecontainshellostring. Otherwise it should be nonzero value.
|
I declared an array:
char * words[1000] = {NULL};
And now I have a series of forked child processes adding words to that array, but they are not affecting the parent program. How can I change that?
|
Hmm, for your edit-case: Dont use fork, use threads, because then everything runs in one address-space...And of course, then use mutexes to protect your words-array...
|
I'm making a Mac OSX program where I need to take a snapshot (image file) the currently active window in Photoshop.
How would I go about this?
|
I ended up using Applescript inside Xcode to find photoshop and saving a copy of the current file. Not the best solution but it works.
|
I am sending a long long to a byte array with other stuff to a java server. When I convert the long back at the java end its not what I am expecting. I have tested the java converter but I ObjectiveC I thought that with it been low level would be as simple as this.
```
uint8_t *data = alloca(sizeof(longlong));
memcpy... |
Maybe... Depend on the endianess... take a look here:http://en.wikipedia.org/wiki/Endianness
|
For my systems programming class, I'm trying to communicate between a parent and child process using a pipe. I have a large amount of text (>64kB) that I want to send to a child process using a pipe. The child process will periodically read the text.
While writing, how do I check if the pipe is full? Also, how do I re... |
Pipesare blocking (unless you set it to be non-blocking). That solves your both issues.
|
I attempted to make astructdeclarationstatic(so it can only be used within the files):
```
static typedef struct
{
int foo;
} MyStruct;
static MyStruct[5];
```
(This is in test_struct.c)
When I compiled the thing, I got this error:
```
test_struct.c:12: multiple storage classes in declaration of `MyStruct'
```
... |
You candeclare variables as static.
```
static MyStruct ms[5];
```
I usually do it like this,
```
typedef struct{
int foo;
} MyStruct;
static MyStruct myStruct[5];
```
|
I'm writing some methods in C that must run very efficiently, so I'd like to manually edit some of the assembly code that is automatically generated.
I know how to read the assembly code using gdb or "objdump -d myfile.o", but can anyone tell me how to edit this code? (Will probably just be minor tweaks.)
|
gcc have -S switch, which stops compilation on after assembly generation phase. Then you cound edit resulting file and manually call assembly (with gas, for example)
|
Sometimes, when I install programs, I see progress bar in console window (or other, dynamic changing text). It is displayed, and changing in the same row of string. When I useprintfor other function, I write next text, but I can't modify in console window already existing text. How can I do it through C?
|
The easiest way for this kind of effects is to use the caret return\rcharacter that lets you write over the previous line.
If you'd like to have direct access to the console's buffer (i.e. writing in specific X/Y position instead of line-by-line), then you're probably looking for a helper library likepdcurses.
|
I am trying to use sscanf to extract specific values of name and msg from a string{"username":"ece","says":"hello"}as following:
```
sscanf(data, "{"\username"\:"\%s"\,"\says"\:"\%s"\}", name, msg);
```
I need 'ece' in name and 'hello' in msg but I am getting ece","says":"hello" in name and msg remains empty.
|
The%sformat stops at the next white space. You need it to stop earlier, at the'"', so you need to use a character set,
```
sscanf(data, "{\"username\":\"%[^\"]\",\"says\":\"%s\"}", name, msg);
^^^^^^
read up to the next double quote
```
|
Specifically I am doing this
```
Word32 x = 18653184;
Word32 y;
Word16 shift = 269;
y = x >> shift;
```
I'd expect the result of this logical shift to be 0, but I am instead getting 2277. How does C define this type of operation?
|
Yes, it is undefined behavior, according to section 6.5.7 paragraph 3
... If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
|
I'm not able to use gotoxy() function in Visual Studio 2010. Is there any alternative for that?
|
Are you talking about command line applications or windows applications? You must remember that VC2008 is a windows specific development environment, so if you were learning programming on a linux/unix or an older dos system then things will not be the same.
The only way I know of under windows to change the position... |
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'd like to know how many element I... |
Try
```
int finding_number_element(int *a, int *b)
{
return (b - a);
}
```
if a and b will be pointers to the same array this should work.
|
On a mac running 10.8 i am trying to open a serial port.
ls /dev/cu* returns:
```
/dev/cu.Bluetooth-Modem /dev/cu.Bluetooth-PDA-Sync /dev/cu.usbserial-A1009TT7
```
i can see the port is there but when i try to open it i get Undefined error: 0(0). This is my code i use to open the port.
```
char *path = "/dev/... |
Whoops! You meant to type this:
```
file = open(path , O_RDWR | O_NOCTTY | O_NONBLOCK);
^^^^^^^
```
Also, there is no need to close a file descriptor that isn't open.
```
if (file == -1) {
printf(...);
// close(file); Completely unnecessary. It's not valid!
return -1;
}
```
|
I have a situation where I need to perform file IO but I'm sandboxed. So, I'm using shm_open with mmap, to return a file descriptor which I can happily read/write to/from in memory.
The problem I have is that a platform that I am porting to does not have shm_open. Does mmap require arg 5 to be a "file descriptor"? Or... |
You can use theMAP_ANONYMOUSflag to just map a piece of memory. This is basically the same as callingmalloc, and no data you write will be saved as it's all in memory.
|
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.
Given a static array how to change ... |
Usemalloc()to dynamically allocate the array and usememcpy()to copy the contents. Remembering tofree()what wasmalloc()d.
|
I made a stupid mistake (forgot semicolon, too much Python lately), but got an interesting error message from gcc: "expected ',' or ';' before 'if'".
I know those error messages provide just an "upper bound" for possible source code, but I'd like to know if there is any construct in C such that "if" token really come... |
After isn't necessarilyimmediately after. The error message is more: 'I've just hit an 'if' construct. At this point I was expecting either an end to the (previous) statement, or the next item in the list. One of those things must be before this 'if', so I'm letting you know'
|
If i have a large data file containing integers of an arbitrary length needing to be sorted by it's second field:
```
1 3 4 5
1 4 5 7
-1 34 56 7
124 58394 1384 -1938
1948 3848089 -14850 0
1048 01840 1039 888
//consider this is a LARGE file, the data goes on for quite some time
```
and i call upon qsort to be my weap... |
Any modern compiler will build identical code in these two cases, the difference is one of style and convenience only.
|
Currently working on a code I realized that it used to callmallocmultiple times (around 10 million calls) and allocated small chunks (around 10 bytes) every time.
I changed the code a little and instead of callingmalloc10 million times I now callmalloc10 times allocating a large chunk of memory (10 million bytes) eve... |
definitely. Becausemalloc()allocates some amount of bytes for meta-data. so if multiple malloc() leads to more meta-data.
Thislinkgives you more detail about how malloc allocates memory as well as metadata.
|
When I create a new database withsqlite3_open_v2(path, db3, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL), the created database will have-rw-r--r--even if the parent folder hasdrwxrwsr-x.
Is there any way I can create the database readable for groups withoutchmodon the database file?
|
SQLite creates its database file with0644permissions by default.
This can be changed by redefiningSQLITE_DEFAULT_FILE_PERMISSIONSduring compilation.
You also can create an empty file before callingsqlite3_open*.
|
```
int a = 10;
int *p = &a;
*p = 20; /* Is this a valid statement? */
```
I understand that if I doint *p;and then if I do*p = 10, it is invalid because I have not assigned any memory top. However, I was wonderingif initializing a pointer to some address allocates memory to that pointer or not?
|
I was wondering if initializing a pointer to some address allocates memory to it or not?
It does NOT allocate any memory. Becausepapoints to an already allocated memory
```
int a = 10; // a is statically allocated and value 10 is assigned.
int *p = &a; // p is pointed to address of a.
*p = 20; // at this point... |
Specifically I am doing this
```
Word32 x = 18653184;
Word32 y;
Word16 shift = 269;
y = x >> shift;
```
I'd expect the result of this logical shift to be 0, but I am instead getting 2277. How does C define this type of operation?
|
Yes, it is undefined behavior, according to section 6.5.7 paragraph 3
... If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
|
I'm not able to use gotoxy() function in Visual Studio 2010. Is there any alternative for that?
|
Are you talking about command line applications or windows applications? You must remember that VC2008 is a windows specific development environment, so if you were learning programming on a linux/unix or an older dos system then things will not be the same.
The only way I know of under windows to change the position... |
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'd like to know how many element I... |
Try
```
int finding_number_element(int *a, int *b)
{
return (b - a);
}
```
if a and b will be pointers to the same array this should work.
|
On a mac running 10.8 i am trying to open a serial port.
ls /dev/cu* returns:
```
/dev/cu.Bluetooth-Modem /dev/cu.Bluetooth-PDA-Sync /dev/cu.usbserial-A1009TT7
```
i can see the port is there but when i try to open it i get Undefined error: 0(0). This is my code i use to open the port.
```
char *path = "/dev/... |
Whoops! You meant to type this:
```
file = open(path , O_RDWR | O_NOCTTY | O_NONBLOCK);
^^^^^^^
```
Also, there is no need to close a file descriptor that isn't open.
```
if (file == -1) {
printf(...);
// close(file); Completely unnecessary. It's not valid!
return -1;
}
```
|
I have a situation where I need to perform file IO but I'm sandboxed. So, I'm using shm_open with mmap, to return a file descriptor which I can happily read/write to/from in memory.
The problem I have is that a platform that I am porting to does not have shm_open. Does mmap require arg 5 to be a "file descriptor"? Or... |
You can use theMAP_ANONYMOUSflag to just map a piece of memory. This is basically the same as callingmalloc, and no data you write will be saved as it's all in memory.
|
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.
Given a static array how to change ... |
Usemalloc()to dynamically allocate the array and usememcpy()to copy the contents. Remembering tofree()what wasmalloc()d.
|
I made a stupid mistake (forgot semicolon, too much Python lately), but got an interesting error message from gcc: "expected ',' or ';' before 'if'".
I know those error messages provide just an "upper bound" for possible source code, but I'd like to know if there is any construct in C such that "if" token really come... |
After isn't necessarilyimmediately after. The error message is more: 'I've just hit an 'if' construct. At this point I was expecting either an end to the (previous) statement, or the next item in the list. One of those things must be before this 'if', so I'm letting you know'
|
If i have a large data file containing integers of an arbitrary length needing to be sorted by it's second field:
```
1 3 4 5
1 4 5 7
-1 34 56 7
124 58394 1384 -1938
1948 3848089 -14850 0
1048 01840 1039 888
//consider this is a LARGE file, the data goes on for quite some time
```
and i call upon qsort to be my weap... |
Any modern compiler will build identical code in these two cases, the difference is one of style and convenience only.
|
Currently working on a code I realized that it used to callmallocmultiple times (around 10 million calls) and allocated small chunks (around 10 bytes) every time.
I changed the code a little and instead of callingmalloc10 million times I now callmalloc10 times allocating a large chunk of memory (10 million bytes) eve... |
definitely. Becausemalloc()allocates some amount of bytes for meta-data. so if multiple malloc() leads to more meta-data.
Thislinkgives you more detail about how malloc allocates memory as well as metadata.
|
When I create a new database withsqlite3_open_v2(path, db3, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL), the created database will have-rw-r--r--even if the parent folder hasdrwxrwsr-x.
Is there any way I can create the database readable for groups withoutchmodon the database file?
|
SQLite creates its database file with0644permissions by default.
This can be changed by redefiningSQLITE_DEFAULT_FILE_PERMISSIONSduring compilation.
You also can create an empty file before callingsqlite3_open*.
|
I'm not able to use gotoxy() function in Visual Studio 2010. Is there any alternative for that?
|
Are you talking about command line applications or windows applications? You must remember that VC2008 is a windows specific development environment, so if you were learning programming on a linux/unix or an older dos system then things will not be the same.
The only way I know of under windows to change the position... |
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'd like to know how many element I... |
Try
```
int finding_number_element(int *a, int *b)
{
return (b - a);
}
```
if a and b will be pointers to the same array this should work.
|
On a mac running 10.8 i am trying to open a serial port.
ls /dev/cu* returns:
```
/dev/cu.Bluetooth-Modem /dev/cu.Bluetooth-PDA-Sync /dev/cu.usbserial-A1009TT7
```
i can see the port is there but when i try to open it i get Undefined error: 0(0). This is my code i use to open the port.
```
char *path = "/dev/... |
Whoops! You meant to type this:
```
file = open(path , O_RDWR | O_NOCTTY | O_NONBLOCK);
^^^^^^^
```
Also, there is no need to close a file descriptor that isn't open.
```
if (file == -1) {
printf(...);
// close(file); Completely unnecessary. It's not valid!
return -1;
}
```
|
I have a situation where I need to perform file IO but I'm sandboxed. So, I'm using shm_open with mmap, to return a file descriptor which I can happily read/write to/from in memory.
The problem I have is that a platform that I am porting to does not have shm_open. Does mmap require arg 5 to be a "file descriptor"? Or... |
You can use theMAP_ANONYMOUSflag to just map a piece of memory. This is basically the same as callingmalloc, and no data you write will be saved as it's all in memory.
|
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.
Given a static array how to change ... |
Usemalloc()to dynamically allocate the array and usememcpy()to copy the contents. Remembering tofree()what wasmalloc()d.
|
I made a stupid mistake (forgot semicolon, too much Python lately), but got an interesting error message from gcc: "expected ',' or ';' before 'if'".
I know those error messages provide just an "upper bound" for possible source code, but I'd like to know if there is any construct in C such that "if" token really come... |
After isn't necessarilyimmediately after. The error message is more: 'I've just hit an 'if' construct. At this point I was expecting either an end to the (previous) statement, or the next item in the list. One of those things must be before this 'if', so I'm letting you know'
|
If i have a large data file containing integers of an arbitrary length needing to be sorted by it's second field:
```
1 3 4 5
1 4 5 7
-1 34 56 7
124 58394 1384 -1938
1948 3848089 -14850 0
1048 01840 1039 888
//consider this is a LARGE file, the data goes on for quite some time
```
and i call upon qsort to be my weap... |
Any modern compiler will build identical code in these two cases, the difference is one of style and convenience only.
|
Currently working on a code I realized that it used to callmallocmultiple times (around 10 million calls) and allocated small chunks (around 10 bytes) every time.
I changed the code a little and instead of callingmalloc10 million times I now callmalloc10 times allocating a large chunk of memory (10 million bytes) eve... |
definitely. Becausemalloc()allocates some amount of bytes for meta-data. so if multiple malloc() leads to more meta-data.
Thislinkgives you more detail about how malloc allocates memory as well as metadata.
|
When I create a new database withsqlite3_open_v2(path, db3, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL), the created database will have-rw-r--r--even if the parent folder hasdrwxrwsr-x.
Is there any way I can create the database readable for groups withoutchmodon the database file?
|
SQLite creates its database file with0644permissions by default.
This can be changed by redefiningSQLITE_DEFAULT_FILE_PERMISSIONSduring compilation.
You also can create an empty file before callingsqlite3_open*.
|
```
int a = 10;
int *p = &a;
*p = 20; /* Is this a valid statement? */
```
I understand that if I doint *p;and then if I do*p = 10, it is invalid because I have not assigned any memory top. However, I was wonderingif initializing a pointer to some address allocates memory to that pointer or not?
|
I was wondering if initializing a pointer to some address allocates memory to it or not?
It does NOT allocate any memory. Becausepapoints to an already allocated memory
```
int a = 10; // a is statically allocated and value 10 is assigned.
int *p = &a; // p is pointed to address of a.
*p = 20; // at this point... |
When running the following, it keeps printing the same memory address.
```
#include <stdio.h>
int array[5] = {2, 4, 6, 8, 10};
int *pointer;
int main()
{
pointer = array;
printf("%p:\t%d\n", pointer, *pointer);
return 0;
}
```
I don't know whether this is a problem, but I'm still curious t... |
Purely, a coincedence.You cannot rely on the address to be same in different runs.
|
i have a substring problem in c.it is not changing the substring properly.it has to find foo and replace it with other thing but it can not changes it.it just changes the 'o' part. please help out.
```
#include <stdio.h>
#include <string.h>
char *replace(char *s, char old, char newer)
{
char *p = &s[0];
while(*p)
{... |
```
char *replace(char *s, char *old, char *newer)
{
...
if(*p == *old){
*p = *newer;
old++; newer++;
}
...
puts(replace(mystr, "foo", "bars"));
```
These changes should fix the problem.
|
This question already has answers here:Closed10 years ago.
Possible Duplicate:C: create a pointer to two-dimensional array
When an array is defined, as
```
int k[100];
```
it can be cast to int*:
```
int* pk = k;
```
It there a pointer variable a multidimensional array can be cast to?
```
int m[10][10];
??? pm ... |
```
int m[10][20];
int (*pm)[20] = m; // [10] disappears, but [20] remains
int t[10][20][30];
int (*pt)[20][30] = m; // [10] disappears, but [20][30] remain
```
This is not a "cast" though. Cast is an explicit type conversion. In the above examples the conversion is implicit.
Not also that the pointer type remains ... |
As an example of implementation defined behavior in C. The C Standard says that the size of data types are implementation defined. So, saysizeof(int)is implementation defined.
Does this implementation defined behavior mean that thesize(int)is platform dependent or defined by compiler vendor or both?Once I compile my ... |
Yes, implementation defined means that it depends on the platform (Architecture + OS ABI + compiler).
And yes, implementation defined features can differ across different versions of the platform.
|
I have downloaded the MPDs "http://dash.edgesuite.net/adobe/hdworld_dash/HDWorld.mpd" and all related .m4s files.
I tried running it on VLC player. But the format is not recognized by VLC player.
I have downloaded this media segment usingwget(1 to 14 segments are available)http://dash.edgesuite.net/adobe/hdworld_dash... |
You need the initialization segment. It is often named "00" or "init" or doesn't have a sequence number like the other files, and often ends in ".mp4" rather than ".m4s". Then you just concatenate the files together. You can start anywhere in the sequence so long as you begin with the initialization segment.
For exam... |
I'm debugging a thread impersonating a currently logged on user in a Windows service process running underSYSTEMaccount. How could I determine the current impersonation level (as in whetherimpersonationordelegationwas used) either programmatically, or using Visual Studio debugger or other tools?
|
Simplest way is via Visual Studio$userpseudo variable.
|
I want to include a global .h file into my .cpp, but it is in C-style.
In it, global variables are defined like:
```
int a;
int b;
```
Which causes error.
How can I change it to be compatible with my .cpp file?
|
Remove the definition from the header file.Declare them asexternin the header file & define the variables in (exactly)one cpp file.Include the header file in whichever cpp file which wants to access the variables.
If you define a variable in header file, you will end up violating theOne definition ruleand encounter l... |
How to write below code in C? Also: is there any built in function for checking length of an array?
Python Code
```
x = ['ab', 'bc' , 'cd']
s = 'ab'
if s in x:
//Code
```
|
There is no function for checking length of array in C. However, if the array is declared in the same scope as where you want to check, you can do the following
```
int len = sizeof(x)/sizeof(x[0]);
```
You have to iterate through x and do strcmp on each element of array x, to check if s is the same as one of the el... |
If I try to establish a connection viaPQconnectdband it fails, is it ok to callPQresetonPGconn*to retry or does it only work if I've already been connected once?
|
If the connection attempt is failed because of some invalid connections options (error like invalid connection options) than calling the PQreset will also fail. But for cases where all arguments to the PQconnectdb were correct and connection was unsuccessful because of reasons like remote server was busy or not accept... |
while writing/reading of file in text mode, the new line character is translated in to carriage return and linefeed i.e \n to \r\n but in binary mode this doesn't happen.
Similarly, the ASCII value 26 will be written at the end of file in text mode but this doesn't happen in binary mode.
I know this question was ask... |
In a sense, binary mode is "raw": nothing is translated, since it has no basis for doing so. Whereas in text mode, the file is interpreted as text, and thus (for example) line endings get translated to the appropriate representation.
|
I have some lex parser rules, but I want to do something like this:
The list of the e-mails: (this is static text I want to output with printf)john@email.com, jessica@aol.com, mike@yahoo.com(all of them via lex rules)The list of websites:google.com, yahoo.com, stackoverflow.com(all of them via lex rules)The list of c... |
Have you considered collecting each type into its respective global array and printing them in the end whey you are done with yylex()
|
I need to find if a char array starts with "ADD". I know to use strcmp(), but I don't know how to get the first three characters. I really hate working with c-strings. How can I take a slice of a char array likechar buffer[1024]?
|
Usestrncmp("ADD", buffer, 3).
I am not sure what you mean by “slice” but any pointer insidebuffercould be considered a slice. For example ifbufferis a string that starts with"ADD"thenchar *slice = buffer + 3is the same string with"ADD"removed.Notethatsliceis then a part ofbufferand modifying the content of theslicewi... |
I have downloaded the MPDs "http://dash.edgesuite.net/adobe/hdworld_dash/HDWorld.mpd" and all related .m4s files.
I tried running it on VLC player. But the format is not recognized by VLC player.
I have downloaded this media segment usingwget(1 to 14 segments are available)http://dash.edgesuite.net/adobe/hdworld_dash... |
You need the initialization segment. It is often named "00" or "init" or doesn't have a sequence number like the other files, and often ends in ".mp4" rather than ".m4s". Then you just concatenate the files together. You can start anywhere in the sequence so long as you begin with the initialization segment.
For exam... |
I'm debugging a thread impersonating a currently logged on user in a Windows service process running underSYSTEMaccount. How could I determine the current impersonation level (as in whetherimpersonationordelegationwas used) either programmatically, or using Visual Studio debugger or other tools?
|
Simplest way is via Visual Studio$userpseudo variable.
|
I want to include a global .h file into my .cpp, but it is in C-style.
In it, global variables are defined like:
```
int a;
int b;
```
Which causes error.
How can I change it to be compatible with my .cpp file?
|
Remove the definition from the header file.Declare them asexternin the header file & define the variables in (exactly)one cpp file.Include the header file in whichever cpp file which wants to access the variables.
If you define a variable in header file, you will end up violating theOne definition ruleand encounter l... |
How to write below code in C? Also: is there any built in function for checking length of an array?
Python Code
```
x = ['ab', 'bc' , 'cd']
s = 'ab'
if s in x:
//Code
```
|
There is no function for checking length of array in C. However, if the array is declared in the same scope as where you want to check, you can do the following
```
int len = sizeof(x)/sizeof(x[0]);
```
You have to iterate through x and do strcmp on each element of array x, to check if s is the same as one of the el... |
If I try to establish a connection viaPQconnectdband it fails, is it ok to callPQresetonPGconn*to retry or does it only work if I've already been connected once?
|
If the connection attempt is failed because of some invalid connections options (error like invalid connection options) than calling the PQreset will also fail. But for cases where all arguments to the PQconnectdb were correct and connection was unsuccessful because of reasons like remote server was busy or not accept... |
while writing/reading of file in text mode, the new line character is translated in to carriage return and linefeed i.e \n to \r\n but in binary mode this doesn't happen.
Similarly, the ASCII value 26 will be written at the end of file in text mode but this doesn't happen in binary mode.
I know this question was ask... |
In a sense, binary mode is "raw": nothing is translated, since it has no basis for doing so. Whereas in text mode, the file is interpreted as text, and thus (for example) line endings get translated to the appropriate representation.
|
I have some lex parser rules, but I want to do something like this:
The list of the e-mails: (this is static text I want to output with printf)john@email.com, jessica@aol.com, mike@yahoo.com(all of them via lex rules)The list of websites:google.com, yahoo.com, stackoverflow.com(all of them via lex rules)The list of c... |
Have you considered collecting each type into its respective global array and printing them in the end whey you are done with yylex()
|
I want to include a global .h file into my .cpp, but it is in C-style.
In it, global variables are defined like:
```
int a;
int b;
```
Which causes error.
How can I change it to be compatible with my .cpp file?
|
Remove the definition from the header file.Declare them asexternin the header file & define the variables in (exactly)one cpp file.Include the header file in whichever cpp file which wants to access the variables.
If you define a variable in header file, you will end up violating theOne definition ruleand encounter l... |
How to write below code in C? Also: is there any built in function for checking length of an array?
Python Code
```
x = ['ab', 'bc' , 'cd']
s = 'ab'
if s in x:
//Code
```
|
There is no function for checking length of array in C. However, if the array is declared in the same scope as where you want to check, you can do the following
```
int len = sizeof(x)/sizeof(x[0]);
```
You have to iterate through x and do strcmp on each element of array x, to check if s is the same as one of the el... |
If I try to establish a connection viaPQconnectdband it fails, is it ok to callPQresetonPGconn*to retry or does it only work if I've already been connected once?
|
If the connection attempt is failed because of some invalid connections options (error like invalid connection options) than calling the PQreset will also fail. But for cases where all arguments to the PQconnectdb were correct and connection was unsuccessful because of reasons like remote server was busy or not accept... |
while writing/reading of file in text mode, the new line character is translated in to carriage return and linefeed i.e \n to \r\n but in binary mode this doesn't happen.
Similarly, the ASCII value 26 will be written at the end of file in text mode but this doesn't happen in binary mode.
I know this question was ask... |
In a sense, binary mode is "raw": nothing is translated, since it has no basis for doing so. Whereas in text mode, the file is interpreted as text, and thus (for example) line endings get translated to the appropriate representation.
|
I have some lex parser rules, but I want to do something like this:
The list of the e-mails: (this is static text I want to output with printf)john@email.com, jessica@aol.com, mike@yahoo.com(all of them via lex rules)The list of websites:google.com, yahoo.com, stackoverflow.com(all of them via lex rules)The list of c... |
Have you considered collecting each type into its respective global array and printing them in the end whey you are done with yylex()
|
I need to find if a char array starts with "ADD". I know to use strcmp(), but I don't know how to get the first three characters. I really hate working with c-strings. How can I take a slice of a char array likechar buffer[1024]?
|
Usestrncmp("ADD", buffer, 3).
I am not sure what you mean by “slice” but any pointer insidebuffercould be considered a slice. For example ifbufferis a string that starts with"ADD"thenchar *slice = buffer + 3is the same string with"ADD"removed.Notethatsliceis then a part ofbufferand modifying the content of theslicewi... |
With this struct
```
typedef struct tNode_t {
struct tNode_t **a;
} tNode;
```
I want to be able to haveapoint to an array to 5 pointers to tNodes
example main:
```
int main()
{
tNode t;
tNode (*alpha)[5];
t.a = alpha;
}
```
why doesn't this work?
|
This defines a pointer to an array of tNodes:
```
tNode (*alpha)[5];
```
This defines an array of pointers to tNodes:
```
tNode *alpha[5];
```
|
In some framebuffer configuration code I had seen these lines:
```
static unsigned int max_size = 0;
max_size = max(max_size, 8*(mi->xres * (mi->xres + mi->yres)));
}
max_size = PAGE_ALIGN(max_size);
```
What doesPAGE_ALIGNdo to andunsigned int? shouldn't it get an address?
```
mi is `struct fb_videomode *`
`... |
It rounds the size up to an exact multiple of the page size (often something like 4k, though implementation-dependent).
In this case, it's not applying to an absolute address, but instead to a size - which will likely become a difference between addresses.
|
I would like to check for certain characters in an array at certain positions.
The array starts with $$$$ then has eight characters then another $, eight more characters and finishes with $$$$. For examplechar my_array[50] = "$$$$01FF4C68$02543EFE$$$$";
I want to check that all the positions where there are supposed... |
Why complicate things?
```
if (my_array[0] != '$'
|| my_array[1] != '$'
|| my_array[2] != '$'
|| my_array[3] != '$'
|| my_array[12] != '$'
|| my_array[21] != '$'
|| my_array[22] != '$'
|| my_array[23] != '$'
|| my_array[24] != '$')
{
printf("Wrong!\n");
}
```
|
I'm writing an iOS app, and I'm noticing I have a couple ways to define a fixed width 16bit unsigned integer.
uint16_t - defined in stdint.hUInt16 - defined in MacTypes.h
As these are fixed width (and I'd assume same endian), what could possibly be Apple's reason to define their own version?
|
The "user-defined" types existed before the standard types became part of the standard.
I use the standard types everywhere, except when directly using an interface that specifies the "user-defined" types.
|
Suppose I have an array with indices 0..n-1. Is there a way to choose which cells each thread would handle? e.g. thread 0 would handle cells 0 and 5 , thread 1 would handle cells 1 and 6 and so on..
|
Have you looked at the schedule clause for the parallel for?
```
#pragma omp for schedule(static, 1)
```
should implement what you want, you can experiment with the schedule clause using the following simple code:
```
#include<stdio.h>
#include<omp.h>
int main(){
int i,th_id;
#pragma omp parallel for schedul... |
In C, you can usestrdupto succinctly allocate a buffer and copy a string into it. As far as I'm aware, however, there is no similar function for general memory. For example, I can't say
```
struct myStruct *foo = malloc(sizeof(struct myStruct));
fill_myStruct(foo);
struct myStruct *bar = memdup(foo, sizeof(struct ... |
You can implement it whith a simple function:
```
void* memdup(const void* mem, size_t size) {
void* out = malloc(size);
if(out != NULL)
memcpy(out, mem, size);
return out;
}
```
|
If I use a whole number in#define, whatdata typeis it considered to be insprintf()inC99?
```
#define NUMBER 100
sprintf(buf, "%i\n", NUMBER); // is it %i, %u, %lu ?
```
|
```
#define NUMBER1 100 /* int: use "%d" or "%i" in printf() */
#define NUMBER2 100U /* unsigned int: use "%u" in printf() */
#define NUMBER3 100L /* long int: use "%ld" or "%li" in printf() */
#define NUMBER4 100UL /* unsigned long int: use "%lu" in printf() */
/* C99 */
#define NUMBER5 100LL /* long long int: use "%... |
How can I know the seconds and microseconds between 1 January 1970 00:00:00 and now using timeval? Thanks.
```
struct timeval {
long tv_sec; /*seconds since 1/1/1970*/
long tv_usec; /*microseconds since tv_sec*/
};
```
|
you callgettimeofday()
```
struct timeval tv;
gettimeofday(&tv, NULL);
tv.tv_sec /* seconds */
tv.tv_usec /* microseconds */
```
Howevergettimeofday()is obsolete, the manual is recommendingclock_gettime(2)instead:
```
struct timespec tp;
clock_gettime(CLOCK_REALTIME, &tp);
tp.tv_sec /* seconds */
tp.tv_usec /* na... |
when running my code in borland c 3.1 it works fine, but when running it on c-free it crashes at this line:while(ptr1->pright)
{
ptr1=ptr1->pright;
}giving SIGSEGV, any logical reasons?
|
You're probably accessing memory outside the bounds of an array or which you didn't allocate. As such, you triggeredundefined behaviour, so pretty much anything can happen, including crashing or evenapparentlyworking fine.
|
Can you give an example of use oftm(I don't know how to initialize thatstruct) where the current date is written in this formaty/m/d?
|
How to usetmstructure
calltime()to get current date/time as number of seconds since 1 Jan 1970.calllocaltime()to getstruct tmpointer. If you want GMT them callgmtime()instead oflocaltime().Usesprintf()orstrftime()to convert the struct tm to a string in any format you want.
Example
```
#include <stdio.h>
#include <t... |
As it is time to study for finals, I have to cover some detailed information regarding loops.I am currently stuck on this question
```
int main(void) {
int x = 0;
int y = 0;
while (y < 10) {
x = 0;
while (x != y) {//
x = x + 3; // how many times will we do this statement?
}
printf(“x... |
This line causes a problem
```
x = 0;
while (x != y) {//
x = x + 3; // how many times will we do this statement?
}
```
wheny=1sincexwill continue to increase until it reaches the maximum integer value (it cant equal y unless some overflow wrapping occurs - this will result in an infinite loop).
|
hi I m trying to convert myjavacode toccode for better speed ,
and I want to generate a random number inc codeusingjni(android)
in java code,
```
public int getRandomNumberFor()
{
Random random ;
random = new Random();
return random.nextInt(0xFF);
}
```
I don't know what code work ... |
Change your code as using C Programming in NDK :
```
#include <stdio.h>
#include <stdlib.h>
JNIEXPORT jint JNICALL Java_com_imrantestndk_androiddemo_NativeLib_Randomnum
(JNIEnv * env, jobject this){
int n;
n = rand()%100 + 1;
return n;
}
```
Or
```
#include <stdio.h>
#include <stdlib.h>
#include <t... |
I'm writing an iOS app, and I'm noticing I have a couple ways to define a fixed width 16bit unsigned integer.
uint16_t - defined in stdint.hUInt16 - defined in MacTypes.h
As these are fixed width (and I'd assume same endian), what could possibly be Apple's reason to define their own version?
|
The "user-defined" types existed before the standard types became part of the standard.
I use the standard types everywhere, except when directly using an interface that specifies the "user-defined" types.
|
Suppose I have an array with indices 0..n-1. Is there a way to choose which cells each thread would handle? e.g. thread 0 would handle cells 0 and 5 , thread 1 would handle cells 1 and 6 and so on..
|
Have you looked at the schedule clause for the parallel for?
```
#pragma omp for schedule(static, 1)
```
should implement what you want, you can experiment with the schedule clause using the following simple code:
```
#include<stdio.h>
#include<omp.h>
int main(){
int i,th_id;
#pragma omp parallel for schedul... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.