question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
This question already has answers here:With arrays, why is it the case that a[5] == 5[a]?(20 answers)Closed9 years ago.
I am using Ubuntu 12.04lts with the GCC compiler. This program gives the result 10. Could you anybody please describe why this program gives the result like this?
```
#include <stdio.h>
void main(... |
arr[0]gets internally expanded to*(arr+0). Similarly0[arr]gets expanded to*(0+arr)which points to the same thing. Hence you see 10.
In general for an array or a pointera,a[b]always means*(a+b)whereais the starting address of the array or pointer andbis the offset. Thus,a[b]andb[a]are equivalent.
|
I would like to produce assemblies like the one in the answer of this questionUsing GCC to produce readable assembly?
for simple test code: test.c
```
void main(){
int i;
for(i=0;i<10;i++){
printf("%d\n",i);
}
}
```
gcc command :gcc -g test.c -o test.o
objdump command:objdump -d -M intel -S test.o
But... |
Right now you're creating an executable file and not an object file. The executable file of course contains lot of extra sections.
If you want to create an object file, use the-cflag to GCC.
|
I need to get the file from the terminal, I know the command will look like:
```
./a.out < fileName.txt
```
I'm not sure how to use fgets() in my program to use the file requested from the terminal.
|
Using redirection sends the contents of the input file to stdin, so you need to read from stdin inside your code, so something like (error checking omitted for clarity)
```
#include <stdio.h>
#define BUFFERSIZE 100
int main (int argc, char *argv[])
{
char buffer[BUFFERSIZE];
fgets(buffer, BUFFERSIZE , stdin... |
I found an implementation for pthreads on Windowshere, but I couldn't get it to work right. Can anyone help me to install pthreads ? Like where to put DLLs, .lib, and .h files?
Also, as an environment I'm not using Visual Studio, but Codeblocks with Mingw.
I usually develop on Linux, but this project has to be on Wi... |
The .dll can go in any directory listed in your PATH environment
variable.
The .lib file can go in any directory listed in your LIB environment
variable.
The .h files can go in any directory listed in your INCLUDE
environment variable.
Also see theFAQspage of the link you shared .
Read Q6, Q7, Q8.
|
In what .dll file are thestdiofunctions implemented? I want to test my stack-language's FFI with basic c functions, but I cannot seem to find the correct .dll toGetModuleHandle, to then get function addresses withGetProcAddress...
|
If you are creating Windows apps, and want a complete set of libraries for accessing these functions, download the Windows SDKHERE
I always keep a copy on my dev machine. There are all kinds of things that come up with Windows programming that just require having access to Microsoft's highly monopolized interfaces t... |
I am writing a php extension( i am newbie) and now i encounter a weird problem:
Is there any way to evaluate php code in string INSIDE a php extension ?
for example bellow if zname would be "echo 'hello';" it will print hello
not echo 'hello';
thanks in advance
```
PHP_FUNCTION(hello_greetme)
{
zval *zname;
... |
```
int eval_php_code(char *code) {
int ret = 0;
zend_try {
ret = zend_eval_string(code, NULL, (char *)"" TSRMLS_CC);
} zend_catch {
} zend_end_try();
return ret == FAILURE;
}
```
This should work for you.
|
This question already has answers here:With arrays, why is it the case that a[5] == 5[a]?(20 answers)Closed9 years ago.
I am using Ubuntu 12.04lts with the GCC compiler. This program gives the result 10. Could you anybody please describe why this program gives the result like this?
```
#include <stdio.h>
void main(... |
arr[0]gets internally expanded to*(arr+0). Similarly0[arr]gets expanded to*(0+arr)which points to the same thing. Hence you see 10.
In general for an array or a pointera,a[b]always means*(a+b)whereais the starting address of the array or pointer andbis the offset. Thus,a[b]andb[a]are equivalent.
|
I would like to produce assemblies like the one in the answer of this questionUsing GCC to produce readable assembly?
for simple test code: test.c
```
void main(){
int i;
for(i=0;i<10;i++){
printf("%d\n",i);
}
}
```
gcc command :gcc -g test.c -o test.o
objdump command:objdump -d -M intel -S test.o
But... |
Right now you're creating an executable file and not an object file. The executable file of course contains lot of extra sections.
If you want to create an object file, use the-cflag to GCC.
|
I need to get the file from the terminal, I know the command will look like:
```
./a.out < fileName.txt
```
I'm not sure how to use fgets() in my program to use the file requested from the terminal.
|
Using redirection sends the contents of the input file to stdin, so you need to read from stdin inside your code, so something like (error checking omitted for clarity)
```
#include <stdio.h>
#define BUFFERSIZE 100
int main (int argc, char *argv[])
{
char buffer[BUFFERSIZE];
fgets(buffer, BUFFERSIZE , stdin... |
I found an implementation for pthreads on Windowshere, but I couldn't get it to work right. Can anyone help me to install pthreads ? Like where to put DLLs, .lib, and .h files?
Also, as an environment I'm not using Visual Studio, but Codeblocks with Mingw.
I usually develop on Linux, but this project has to be on Wi... |
The .dll can go in any directory listed in your PATH environment
variable.
The .lib file can go in any directory listed in your LIB environment
variable.
The .h files can go in any directory listed in your INCLUDE
environment variable.
Also see theFAQspage of the link you shared .
Read Q6, Q7, Q8.
|
In what .dll file are thestdiofunctions implemented? I want to test my stack-language's FFI with basic c functions, but I cannot seem to find the correct .dll toGetModuleHandle, to then get function addresses withGetProcAddress...
|
If you are creating Windows apps, and want a complete set of libraries for accessing these functions, download the Windows SDKHERE
I always keep a copy on my dev machine. There are all kinds of things that come up with Windows programming that just require having access to Microsoft's highly monopolized interfaces t... |
I am writing a php extension( i am newbie) and now i encounter a weird problem:
Is there any way to evaluate php code in string INSIDE a php extension ?
for example bellow if zname would be "echo 'hello';" it will print hello
not echo 'hello';
thanks in advance
```
PHP_FUNCTION(hello_greetme)
{
zval *zname;
... |
```
int eval_php_code(char *code) {
int ret = 0;
zend_try {
ret = zend_eval_string(code, NULL, (char *)"" TSRMLS_CC);
} zend_catch {
} zend_end_try();
return ret == FAILURE;
}
```
This should work for you.
|
I am looking for a peace of code to check if the argument I pass to my program is a directory or not. So far I found this:
```
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
struct stat buf;
stat(argv[1],&buf);
... |
Use:
```
if(S_ISDIR(buf.st_mode))
printf(" Its a directoy\n");
else
printf("Its a file\n");
```
afterstat(argv[1],&buf);call
|
This question builds up on my previous question:Difference Between *list and **list. I decided to split them into two questions to make it less confusing, clear, and fair for people answering.
I have this code:
```
typedef struct A
{
char c[100];
}A;
listSize = 5000;
A *list = malloc(listSize * sizeof(*list));... |
```
A** p = malloc(listSize * sizeof(A*));
int i;
for(i = 0; i < listSize; ++i) {
p[i] = &list[i];
}
```
|
I have this code:
```
#include <stdio.h>
int main()
{
int arr[10] = {0};
int *p1_arr = arr;
int (*p2_arr)[10] = arr; // Line 7, Shows Warning here
...
return 0;
}
```
On compiling ongccusinggcc -g -Wall LengthofArray.c, it shows following warning:
```
gcc: LengthOfArray.c:7: [Warning] as... |
... if int (*p2_arr)[10] is apointer to an array of size 10...
Asp2_arrpoints to an array of size 10, you need to assign anaddressof an array of size 10:
```
int (*p2_arr)[10] = &arr;
```
|
I'm not sure if I said it right.
```
pthread_create(..., ..., &some, ...);
...is the same as:
pthread_create(..., ..., some, ...);
```
I'm learning threads, if you could give a website or a video that makes it really simple, it would be great. Threads - locks, condition variables, etc. Thanks!
|
Yes becausefunction name is pointing to a memory location. In simple words it is a memory address, so you pass it likefooor&foo, both are the same.
Example Code:
```
#include <stdio.h>
int foo(){
printf("hello world");
}
int (*fuu)();
int main (void)
{
fuu = foo;
fuu();
return 0;
}
```
Hope this... |
When does Lua gc memory allocated in C with
```
void *lua_newuserdata (lua_State *L, size_t size);
```
?
When there is no reference in Lua pointing to it anymore or do I have to take care about deleting it?
|
Memory allocated withlua_newuserdatais freed when there are no references to itinsideLua. This is how garbage collection works. There are important consequences:
No need to free that memory in your C program. No need to worry about freeing it at all.Don't free that memory.Don't store a pointer to that memory in your ... |
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions concerning problems with code you've written mustdescribe the specific problem— andinclude valid codeto reproduce it — in the question itself. SeeSSCCE.orgfor guidance.Closed9 years ago.Improve this question
I... |
For the samearr, the macro will either work or it won't.
The likely problem is that thearrin the loop is apointerrather than anarray. The macro does not work with pointers, it only works with arrays.
|
Which of the following declaration is the standard and preferred?
```
int x = 7;
```
or
```
int x(7);
```
|
```
int x(7);
```
isnotthevalidway of declaring & initializing a variable in C;
I suggest you to get a good book for learning C and use a good compiler.
|
I need to implement a set of functions providing various set operations such as create set, add element to set, etc. I am new to programming, however, I know how to write a function but my problem with this task is that I need to use pointers and I have no idea how to for example write a function to create a set with ... |
Sets can be stored in various data structures such as, but not limited to, a linked list. You then need to abstract away set operations to add, remove, test for membership of elements. I advise you to read data structure related literature and do some related exercises before undertaking this small project.
|
I have a problem with this function :
```
dirp = opendir(ruta);
if (dirp != NULL){
while ((direntp=readdir(dirp)) != NULL) {
stat(ruta, &estructura);
```
Sorry for my English ... i hope that you can understand me
--------------------------------------------------------------------... |
It's because you get the information fromstatfor thedirectory, the one you pass toopendir.
You have to use that directory as a base, and then append the filenames you get fromreaddir.
|
Afternoon All,
I've written a chunk of code which isn't working correctly. What I'm trying to do is pass an array as an argument to a function so when I return from the function I can continue using the array. My below code gives me a SEG fault or an 'Illegal Instruction' Error, it's random. If someone could give some... |
It will be more correctto declare the function the following way specifying the third parameter
```
void getFile (FILE *file, struct message *sMsg, size_t n );
```
and call it as
```
getFile( file, sMsg, nodeCount );
```
|
I have this code:
```
#include <stdio.h>
int main()
{
int arr[10] = {0};
int *p1_arr = arr;
int (*p2_arr)[10] = arr; // Line 7, Shows Warning here
...
return 0;
}
```
On compiling ongccusinggcc -g -Wall LengthofArray.c, it shows following warning:
```
gcc: LengthOfArray.c:7: [Warning] as... |
... if int (*p2_arr)[10] is apointer to an array of size 10...
Asp2_arrpoints to an array of size 10, you need to assign anaddressof an array of size 10:
```
int (*p2_arr)[10] = &arr;
```
|
I'm not sure if I said it right.
```
pthread_create(..., ..., &some, ...);
...is the same as:
pthread_create(..., ..., some, ...);
```
I'm learning threads, if you could give a website or a video that makes it really simple, it would be great. Threads - locks, condition variables, etc. Thanks!
|
Yes becausefunction name is pointing to a memory location. In simple words it is a memory address, so you pass it likefooor&foo, both are the same.
Example Code:
```
#include <stdio.h>
int foo(){
printf("hello world");
}
int (*fuu)();
int main (void)
{
fuu = foo;
fuu();
return 0;
}
```
Hope this... |
When does Lua gc memory allocated in C with
```
void *lua_newuserdata (lua_State *L, size_t size);
```
?
When there is no reference in Lua pointing to it anymore or do I have to take care about deleting it?
|
Memory allocated withlua_newuserdatais freed when there are no references to itinsideLua. This is how garbage collection works. There are important consequences:
No need to free that memory in your C program. No need to worry about freeing it at all.Don't free that memory.Don't store a pointer to that memory in your ... |
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions concerning problems with code you've written mustdescribe the specific problem— andinclude valid codeto reproduce it — in the question itself. SeeSSCCE.orgfor guidance.Closed9 years ago.Improve this question
I... |
For the samearr, the macro will either work or it won't.
The likely problem is that thearrin the loop is apointerrather than anarray. The macro does not work with pointers, it only works with arrays.
|
Which of the following declaration is the standard and preferred?
```
int x = 7;
```
or
```
int x(7);
```
|
```
int x(7);
```
isnotthevalidway of declaring & initializing a variable in C;
I suggest you to get a good book for learning C and use a good compiler.
|
I need to implement a set of functions providing various set operations such as create set, add element to set, etc. I am new to programming, however, I know how to write a function but my problem with this task is that I need to use pointers and I have no idea how to for example write a function to create a set with ... |
Sets can be stored in various data structures such as, but not limited to, a linked list. You then need to abstract away set operations to add, remove, test for membership of elements. I advise you to read data structure related literature and do some related exercises before undertaking this small project.
|
I have a problem with this function :
```
dirp = opendir(ruta);
if (dirp != NULL){
while ((direntp=readdir(dirp)) != NULL) {
stat(ruta, &estructura);
```
Sorry for my English ... i hope that you can understand me
--------------------------------------------------------------------... |
It's because you get the information fromstatfor thedirectory, the one you pass toopendir.
You have to use that directory as a base, and then append the filenames you get fromreaddir.
|
Afternoon All,
I've written a chunk of code which isn't working correctly. What I'm trying to do is pass an array as an argument to a function so when I return from the function I can continue using the array. My below code gives me a SEG fault or an 'Illegal Instruction' Error, it's random. If someone could give some... |
It will be more correctto declare the function the following way specifying the third parameter
```
void getFile (FILE *file, struct message *sMsg, size_t n );
```
and call it as
```
getFile( file, sMsg, nodeCount );
```
|
I need to implement a set of functions providing various set operations such as create set, add element to set, etc. I am new to programming, however, I know how to write a function but my problem with this task is that I need to use pointers and I have no idea how to for example write a function to create a set with ... |
Sets can be stored in various data structures such as, but not limited to, a linked list. You then need to abstract away set operations to add, remove, test for membership of elements. I advise you to read data structure related literature and do some related exercises before undertaking this small project.
|
I have a problem with this function :
```
dirp = opendir(ruta);
if (dirp != NULL){
while ((direntp=readdir(dirp)) != NULL) {
stat(ruta, &estructura);
```
Sorry for my English ... i hope that you can understand me
--------------------------------------------------------------------... |
It's because you get the information fromstatfor thedirectory, the one you pass toopendir.
You have to use that directory as a base, and then append the filenames you get fromreaddir.
|
Afternoon All,
I've written a chunk of code which isn't working correctly. What I'm trying to do is pass an array as an argument to a function so when I return from the function I can continue using the array. My below code gives me a SEG fault or an 'Illegal Instruction' Error, it's random. If someone could give some... |
It will be more correctto declare the function the following way specifying the third parameter
```
void getFile (FILE *file, struct message *sMsg, size_t n );
```
and call it as
```
getFile( file, sMsg, nodeCount );
```
|
I am working with JSON strings for the first time and I have a Monday deadline so I don't have time to get into the nitty gritty of JSON.
I get this returned from the API:
```
["10","11","12","13","14","15","112","113"]
```
I need to convert it to some thing like:
```
string[0] = 10;
string[1]= 11;
```
etc...
C... |
JSONArray arr = new JSONArray(yourJSONresponse);
List list = new ArrayList();
for(i = 0; i < arr.length; i++){
list.add(arr.getJSONObject("name"));
}
|
I just started learning the C prog. language after using Java for a while.
I'm currently trying to use the ternary If in the following way:
(currIndex == 0) ? return 1:currIndex--;
I know thisisn'tthe traditional assignment form:
max =(a > b)?a:b
Is what I'm trying to do possible? if not, what's the reason?
(My ... |
If, as you say, you return a value anyway, then yes that's not going to be a problem, besides the problem that you actually can't do it that way (returnis not allowed there). To solve it,andmake the code easier to follow, you can do this instead:
```
if (curindex == 0)
return 1;
--curindex;
/* Rest of code */
`... |
In a typical C program, I break down it into several components:
```
// main.c
#include 'part-a.h'
#include 'part-b.h'
main () {
// ...
}
// part-a.h
#include 'part-c.h'
// ...
```
I want to export the whole project as one file including every dependencies recursively (excluding standard libraries), how could I do... |
gcc -Eplus all the other option you normally use to compile, without-c. This will produce preprocessor output. It's the best you can get, AFAIK there's no way to only expand#includedirectives. But you can use some preprocessor library (GCC and Boost have ones) to write your own tool.
http://www.boost.org/doc/libs/1_5... |
I'm trying to append the contents of a file myfile.txt to the end of a second file myfile2.txt in c. I can copy the contents, but I can't find a way to append. Here's my code:
```
FILE *pFile;
FILE *pFile2;
char buffer[256];
pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", r+);
if(pFile==NULL) {
perro... |
Open with append:
```
pFile2 = fopen("myfile2.txt", "a");
```
then just write topFile2, no need tofseek().
|
Last night, my friend tell me a situation as following shows:
in c/c++ ,we write two lines code like this:
```
int a = 0;
printf("%d\n", 1 << -1);
printf("%d\n", 1 << (a-1));
```
It is amazing there are two different results, previous is 0, and the other is -2147483648.
We do not know why, and anyone can give me a... |
Having a negative operand on the right hand side of a left-shift operator is undefined behavior in C. You shouldn't be amazed at any results from doing it.
|
I'm modifying a linux filesystem and I would like to know if there a way to get astruct file *from an absolute pathname? Specifically the struct defined inlinux/fs.h.
|
I know this is a little late, but for anyone looking for an answer to this I used theopenfunction on the pathname.
|
I have to reuse this piece of code in the same function but it wont work because the res1->nextPtr is already at the end of the linked list. Is there a way to reset it to the "Head" of the linked list?
```
do
{
res1 = res1->nextPtr;
}while(res1 != NULL);
```
|
```
LIST *head = res1;
LIST *list = head;
while (list) {
//do something
list = list->nextPtr;
};
list= head;
//again traverse over list
```
if your res1 is NULL your do-while will segfault.
|
I'm trying to append the contents of a file myfile.txt to the end of a second file myfile2.txt in c. I can copy the contents, but I can't find a way to append. Here's my code:
```
FILE *pFile;
FILE *pFile2;
char buffer[256];
pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", r+);
if(pFile==NULL) {
perro... |
Open with append:
```
pFile2 = fopen("myfile2.txt", "a");
```
then just write topFile2, no need tofseek().
|
Last night, my friend tell me a situation as following shows:
in c/c++ ,we write two lines code like this:
```
int a = 0;
printf("%d\n", 1 << -1);
printf("%d\n", 1 << (a-1));
```
It is amazing there are two different results, previous is 0, and the other is -2147483648.
We do not know why, and anyone can give me a... |
Having a negative operand on the right hand side of a left-shift operator is undefined behavior in C. You shouldn't be amazed at any results from doing it.
|
I'm modifying a linux filesystem and I would like to know if there a way to get astruct file *from an absolute pathname? Specifically the struct defined inlinux/fs.h.
|
I know this is a little late, but for anyone looking for an answer to this I used theopenfunction on the pathname.
|
I have to reuse this piece of code in the same function but it wont work because the res1->nextPtr is already at the end of the linked list. Is there a way to reset it to the "Head" of the linked list?
```
do
{
res1 = res1->nextPtr;
}while(res1 != NULL);
```
|
```
LIST *head = res1;
LIST *list = head;
while (list) {
//do something
list = list->nextPtr;
};
list= head;
//again traverse over list
```
if your res1 is NULL your do-while will segfault.
|
This question already has answers here:Is there a standard function in C that would return the length of an array?(7 answers)array_length in C(14 answers)Closed9 years ago.
Can someone help me figure this out?
I think this is not possible... Unless i pass another parameter with the size? I'm looking to avoid it.
Ho... |
You can not do that as a function. You can do it as a macro though.
```
#define SIZEOF_ARRAY(array) (sizeof(array) / sizeof(*array))
```
|
I was writing a program to input multiple lines from a file.
the problem is i don't know the length of the lines, so i cant use fgets cause i need to give the size of the buffer and cant use fscanf cause it stops at a space token
I saw a solution where he recommended using malloc and realloc for each character taken a... |
You can usegetline(3). It allocates memory on your behalf, which you should free when you are finished reading lines.
|
This question already has answers here:Using Boolean values in C(18 answers)Closed9 years ago.
I have an integer called "count" which increments when a certain condition is met. So I wanted to ask what happens if you write this condition:
```
if(count % 2)
{
return even_bit;
}
else
{
return odd_bit;
}
```
... |
If an expression evaluates to0, it will be interpreted asFALSE- for any non-zero value, it will be interpreted asTRUE. In other words,
```
if(count % 2)
```
is equivalent to
```
if(count % 2 != 0)
```
So your code is "backwards". If the statement is true,countis odd and you most likely would want to return theodd_... |
i'm trying to use the convert terminal command in a C program using system function, this is the code piece
```
\#include <stdlib.h>
...
system("cd /Users/myUser/Desktop/photos/pgm;for i in *.jpg; do convert $i
-compress none -scale 32x24! $i.pgm; done;")
```
But I cant run the convert command, this is the pro... |
Check the full path toconvertusingwhich convert.
Then exchange the full path in your C program.
|
I want to list a folder but when I want to print the filename only \n are print
```
void liste_folder(void)
{
DIR *dir;
struct dirent *test;
dir = opendir(".");
while (readdir(dir) != NULL)
{
test = malloc(sizeof(*test));
printf("%s\n", test->d_name);
free(test);
}
}
i... |
You're allocating memory fortest, but that doesn't fill it with the directory info.readdirallocates the memory for thedirentstructure for you, so it isn't even necessary. Assign the return-value ofreaddirtotestinstead:
```
while((test = readdir(dir)) != NULL){
printf("%s\n", test->d_name);
// the man page say... |
Anyone who's used PIN? How would you identify a function exactly (in presence of method overloading)? I can see PIN provides RTN_Name() function, which would return the function name, but surely that's no enough… so what else would you use? Would using RTN_Address() in conjunction with RT_Name() suffice?
Many thanks ... |
Ok I just found out about name mangling! Apparently C/C++ usesname mangling, and so it seems that even usingRTN_Name()should suffice then!
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed9 years ago.Improve this question
```
for(;a- > 64;)
```
I am receiving the followingerrorin the above line:
expected primary-expression be... |
Your compile complains because
```
for(;a- > 64;)
```
isinvalid syntax. Valid is (depends on what you are actually trying to achieve):
```
for(;a-- > 64;)
```
or
```
for(;a > 64;)
```
|
In xcode 5 I get this warning:
"implicit declaration of function free is invalid in c99"
How should I free my c structures if I can't use the function free()?
|
You should include<stdlib.h>.
|
I can't quite wrangle indent to do what I want. The first thing is that it changes functions to look like:
```
double
func1() {
```
When I would want them to look like:
```
double func1() {
```
That is the main item to get resolved. The other thing it's doing is making things look like:
```
long int hi = 100;
... |
```
add -npsl
replace -bad with -nbad
```
|
I want toenumerate logon sessions on a remote host(citrix terminal server). What I found so far isLsaEnumerateLogonSessions() / LsaGetLogonSessionData(), but you can't call it remotely.I read some docs about RPC, but if I understood it right, you need an extra application on the remote host that executes your function... |
Other options include the WTS APIs:WTSEnumerateSessionsEx. If you want to be Citrix specific you can also use theXenApp PowerShell SDK.
|
I was writing a program to input multiple lines from a file.
the problem is i don't know the length of the lines, so i cant use fgets cause i need to give the size of the buffer and cant use fscanf cause it stops at a space token
I saw a solution where he recommended using malloc and realloc for each character taken a... |
You can usegetline(3). It allocates memory on your behalf, which you should free when you are finished reading lines.
|
This question already has answers here:Using Boolean values in C(18 answers)Closed9 years ago.
I have an integer called "count" which increments when a certain condition is met. So I wanted to ask what happens if you write this condition:
```
if(count % 2)
{
return even_bit;
}
else
{
return odd_bit;
}
```
... |
If an expression evaluates to0, it will be interpreted asFALSE- for any non-zero value, it will be interpreted asTRUE. In other words,
```
if(count % 2)
```
is equivalent to
```
if(count % 2 != 0)
```
So your code is "backwards". If the statement is true,countis odd and you most likely would want to return theodd_... |
i'm trying to use the convert terminal command in a C program using system function, this is the code piece
```
\#include <stdlib.h>
...
system("cd /Users/myUser/Desktop/photos/pgm;for i in *.jpg; do convert $i
-compress none -scale 32x24! $i.pgm; done;")
```
But I cant run the convert command, this is the pro... |
Check the full path toconvertusingwhich convert.
Then exchange the full path in your C program.
|
I want to list a folder but when I want to print the filename only \n are print
```
void liste_folder(void)
{
DIR *dir;
struct dirent *test;
dir = opendir(".");
while (readdir(dir) != NULL)
{
test = malloc(sizeof(*test));
printf("%s\n", test->d_name);
free(test);
}
}
i... |
You're allocating memory fortest, but that doesn't fill it with the directory info.readdirallocates the memory for thedirentstructure for you, so it isn't even necessary. Assign the return-value ofreaddirtotestinstead:
```
while((test = readdir(dir)) != NULL){
printf("%s\n", test->d_name);
// the man page say... |
Anyone who's used PIN? How would you identify a function exactly (in presence of method overloading)? I can see PIN provides RTN_Name() function, which would return the function name, but surely that's no enough… so what else would you use? Would using RTN_Address() in conjunction with RT_Name() suffice?
Many thanks ... |
Ok I just found out about name mangling! Apparently C/C++ usesname mangling, and so it seems that even usingRTN_Name()should suffice then!
|
I have a register which 31 bit wide ,Now I am confused between two number that could be used as last address 31 bit scheme .
Would 0x7fff-fffc or 0x80000000 be the last address can be used in 31 scheme.
|
Addresses start at zero. So0x7FFFFFFFif you are addressing bytes.0x7FFFFFFCif you are addressing 32-bit words.
|
In The Art of Multiprocessor Programming, p215, the authors say that in C, you could "steal" a bit from a pointer, and using bit-wise operators extract some flag (a mark) and the pointer from a single word. I don't know how this is done, so an example would help me.
|
Make sure the pointee objects are aligned in memory so that all your pointers are even numbers. The last bit is then free for storing a single boolean flag. (This cannot be done completely portably. so you need knowledge of the platform.)Move the pointers around as integers of typeuintptr_t. These can easily be manipu... |
I have a function:
```
int exploreDIR (char stringDIR[], char arguments[6][100])
{
/*stuff...*/
execv(filePath, arguments);
}
```
However, I get thewarning: passing argument 2 of ‘execv’ from incompatible pointer type
If execv expectschar* const argv[]for its second argument, why do I receive this wa... |
You are are passing a pointer (*) looking like this:
```
*
`-> aaaa...aaaabbbb...bbbbcccc...cccc
```
It points to memory containing severalchar[100]arrays.
The function expects an argument looking like this:
```
*
`->***
||`-> cccc...cccc
|`-> bbbb...bbbb
`-> aaaa...aaaa
```
It wants a pointer pointing t... |
I am trying to implement a server with multiple commands. Most commands work so far except that I want the server to send a warning to the client when the client writes an argument to the quit command. (I.E. quit xyz) and lets the user try again rather than exiting the server. Unfortunately the server quits whether th... |
I would just use:
```
...
}
while(!done);
```
There is no point checkingcmd.
|
When using theC interface to LLVM, how do I determine whether twoLLVMTypeRefs represent the same type?
|
IIUC, if the two types were created in the sameLLVMContextit should be the same pointer, since types are uniqued in LLVM. C API functions usewrapto "convert" C++TypetoLLVMTypeRef, which just usesreinterpret_caston the pointer.
|
The code:
```
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
int main(int argc, char** argv){
omp_set_dynamic(0);
omp_set_num_threads(4);
#pragma omp paralell
{
printf("%d\n", omp_get_thread_num());
}
}
```
The output:
```
0
```
Shouldn't the output be some permutation of 0... |
Writingomp_set_dynamic(0);you indicate that the runtime will not dynamically adjust the number of threads. The argument of this function should be nonzero to avail the dynamic adjustment of num. of threads. Also you misspelledparallelin the code.
|
I have a register which 31 bit wide ,Now I am confused between two number that could be used as last address 31 bit scheme .
Would 0x7fff-fffc or 0x80000000 be the last address can be used in 31 scheme.
|
Addresses start at zero. So0x7FFFFFFFif you are addressing bytes.0x7FFFFFFCif you are addressing 32-bit words.
|
In The Art of Multiprocessor Programming, p215, the authors say that in C, you could "steal" a bit from a pointer, and using bit-wise operators extract some flag (a mark) and the pointer from a single word. I don't know how this is done, so an example would help me.
|
Make sure the pointee objects are aligned in memory so that all your pointers are even numbers. The last bit is then free for storing a single boolean flag. (This cannot be done completely portably. so you need knowledge of the platform.)Move the pointers around as integers of typeuintptr_t. These can easily be manipu... |
I read bMonth from user;
```
time_t timestamp = time(NULL);
tm* birthday = localtime(×tamp);
birthday->tm_mon = bMonth-1;
// now the tm_mon is set corectly
time_t birthStamp = mktime(birthday);
// now the tm_mon is 0
```
Why mktime changes the values?
|
mktime
A call to this function automatically adjusts the values of the
members of timeptr if they are off-range or -in the case of tm_wday
and tm_yday- if they have values that do not match the date described
by the other members.
|
This question already has answers here:Comma in C/C++ macro(8 answers)Closed9 years ago.
```
#include <type_traits>
using namespace std;
template<class T, class = typename enable_if<is_same<T, char>::value>::type> // OK
struct A {};
#define ENABLE_IF(expr) class = typename enable_if<expr>::type
template<class T, ... |
is_same<T, char>::value
there is a comma in middle, thus the preprocessor consider it as two arguments to the macro,
is_same<T,andchar>::value
|
I am attempting to write the clipboard contents to a file, but for some reason the program is freezing.
```
FILE *fp;
fp = fopen("tmp.code","w");
fprintf(fp,getclip()); /*writes*/
fclose(fp);
char* getclip(){
HANDLE clip;
if (OpenClipboard(NULL)){
clip = GetClipboardData(CF_TEXT);
CloseClip... |
The functiongetclip()returns anint, andfprintfexpects pointer to char. It is trying to access an invalid memory position: you're returning aHANDLEasintand thenfprintfinterprets that as a memory address to read characters from.
Please look at your compiler errors and warnings and fix your code.
|
I read bMonth from user;
```
time_t timestamp = time(NULL);
tm* birthday = localtime(×tamp);
birthday->tm_mon = bMonth-1;
// now the tm_mon is set corectly
time_t birthStamp = mktime(birthday);
// now the tm_mon is 0
```
Why mktime changes the values?
|
mktime
A call to this function automatically adjusts the values of the
members of timeptr if they are off-range or -in the case of tm_wday
and tm_yday- if they have values that do not match the date described
by the other members.
|
I've seen a lot of the minimal requirements that an ANSI C compiler must support like 31 arguments to a function, and most of the numbers seem to make some kind of sense.
However, I cannot see the reasoning for supporting at least 509 characters in a source line. 511 or 512 would make more sense, but 509 seems kind ... |
This perhaps is to take account of possibleCR+LF+'\0'characters and have a string representation of each line still fit into 512 bytes of memory.
|
I'm using Curl in C, but I don't want to echo the webpage code:
```
CURL *curl;
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, "www.example.com");
curl_easy_perform(curl);
curl_easy_cleanup(curl);
```
Is there any Curl option for this?
|
I found a good solution for this problem:
```
size_t function(void *ptr, size_t size, size_t nmemb, FILE *stream) {
return fwrite(ptr, size, nmemb, stream);
}
```
...
```
FILE *outfile;
outfile = fopen("test", "w");
CURL *curl;
curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_URL, "www.example.com");
c... |
I'm writing a simple function in C, that returns a number of "1" in byte (bit by bit).
Here is my code, the compiler tells: "expected expression before "=" token" in line where "for" starts.
```
#include <stdio.h>
#include <stdlib.h>
int return_num_of_1(unsigned char u);
int main()
{
printf("Hello world!\n");
... |
```
for (counter = 0; u; u << = 1)
```
The compilation problem is here. You should be using operator <<= without spaces. If you put a space in-between, the compiler reads that as two separate operators: '<<' and '='.
You got a couple of other problems there as well, removing the space fixes the compilation.
|
I have to maintain a chunk of source code on Linux with gcc which has the following function prototype:
```
int foo(const void*, ...)
```
I have to pass an integer into this function. I know that this is a bad idea but at this stage, I'm not allowed to modify the source code.
i.e I have to callfoo(n)(nis defined as... |
You could useintptr_t, but it is optional and may not be available instdint.h:
```
intptr_t n = 1;
foo((void*)n);
```
|
This question already has answers here:Need help understanding how \n, \b, and \r will render printf output(2 answers)Closed9 years ago.
Can anyone tell me how i got theoutput:haifor the following code?
```
int main()
{
printf("\nab");
printf("\bsi");
printf("\rha");
return 0;
}
```
|
They work as they should!!
\n=> Newline, Go to Vertically next position in the same column\b=> BackSpace, Go to one position backwards\r=> Carriage Return, Same as Home Key in Keyboard
Elaborate Explanation:
\r:
Move cursor to Home position in the same row.
\b:
Move cursor one position backwards on same row, if ... |
I just come across the statement in embedded c (dsPIC33)
```
sample1 = sample2 = 0;
```
Would this mean
```
sample1 = 0;
sample2 = 0;
```
Why do they type it this way? Is this good or bad coding?
|
Remember that assignment is done right to left, and that they are normal expressions. So from the compilers perspective the line
```
sample1 = sample2 = 0;
```
is the same as
```
sample1 = (sample2 = 0);
```
which is the same as
```
sample2 = 0;
sample1 = sample2;
```
That is,sample2is assigned zero, thensample1... |
Question was too long. Here's the solution.
Solution:
When trying to get 'just' the line without any special characters such as \n or \r
then loop through the string (char* type) until you hit either the \r or \n so that it is slightly cross-compatible between Windows and other Linux machines.
Possible code:
```
f... |
When reading from a file, fgets reads up to the \n line terminator (which it includes).
Under Windows, a line read from a text file ends in \r\n.
Under Unix, a line read from a text file ends in just \n.
So under Windows, you'd expect the string read by fgets to be 1 byte longer.
|
If I call a function in C and pass in a struct (not by pointers nor references for those c++ readers), it copies the object. If I pass in a struct with an array in it, it copies the array (as stated by professor in class). But what happens if I pass in a struct that contains a circular reference back to the object. Ho... |
It copies the struct, and the pointer inside the copied struct contains the address of the original object.
|
Is it possible to use concatenation in a for loop? My code snippet is like this:
```
#define CONCATE(a, b) a ## b
#define CALL_SEARCH(n, x, y) search(n, arg1, arg2, x, y)
...
int i;
for (i = 1; i (less than or equal to) number; ++i)
{
results = CALL_SEARCH(CONCATE(f, i), tol, max_tries);
}
```
What I want to do ... |
CONCATENATEcreates "fi", not "f1". You wantfto be an array and useias an index on it.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do... |
Busybox does not contain a TCP/IP stack. It makessystem callsto the operating system to do networking operations.
Here is a good starting place to read about the kernel side of things:Anatomy of the Linux networking stack.
|
```
void empty() { }
```
will be compiled to
```
push ebp
mov ebp, esp
ret
```
How do I declare the function so that it has no "decoration" code? just plainret.
If that is not possible, is this possible to define completely assembler function inside the.Cfile? It is possible to define assembler function in the.asmf... |
Declare the function with the__declspec(naked)modifier.
|
Say I have a loop
```
for(int i = 0; i < 1000; i++){
sum += i;
}
```
And if I use OpenMP to speed up it, how is this for loop mapped to 4 different cores?
I know it uses fork and join, I mean is it like i=0 for core 0, i=1 for core 1 and etc or i=0 for core 0, i=249 for core 1, i = 499 for core 2 etc.
Thanks,
... |
According tothis presentationit depends on the compiler implementation rather than the OpenMP spec, but the compiler would probably use i=0 for core 0, i=249 for core 1, etc.
Also make sure you are a reduction variable forsum, otherwise you have a race condition in your example.
|
I need to clear 2 arrays before i execute a function a 2nd time.
They are initially setup globally as :-
```
NSString *allAnswers[10];
int used[6];
```
What would be needed to clear/reset these before running the function again?
Thanks.
|
You can loop through those items, resetting their values to whatever you want.
```
for (NSInteger i = 0; i < 10; i++)
allAnswers[i] = nil;
for (NSInteger i = 0; i < 6; i++)
used[i] = 0;
```
If using Objective-C, you might want to consider usingNSMutableArrayin the future rather than C-language arrays like t... |
is this valid C code ? Is possible to have switch in switch ?
```
switch (i){
case 1:
switch(c){
case 1:
c = 0;
break;
case 3:
c = 5;
break;
}
case 2:
// another code
}
```
|
Yes, to have switch in switch is valid.
§ 6.4.2The switch statement
4Switch statements can be nested; a case or default label is associated with the smallest switch enclosing
it.
|
For some reason that I can't comprehend ,this program keeps looping when I execute it in theCMD.
```
#include <stdio.h>
int main() {
char array [] = {'b','f','r','o','a','u','v','t','o','\0'};
int grootteArray = sizeof(array);
int grootteChar = sizeof(char);
int lengteArray = grootteArr... |
Your counter variable remains the same after each loop. You need to increase it by assigning the new value:
```
for (i=0; i<lengteArray+1; i=i+2) //change to this
```
|
If I call a function in C and pass in a struct (not by pointers nor references for those c++ readers), it copies the object. If I pass in a struct with an array in it, it copies the array (as stated by professor in class). But what happens if I pass in a struct that contains a circular reference back to the object. Ho... |
It copies the struct, and the pointer inside the copied struct contains the address of the original object.
|
Is it possible to use concatenation in a for loop? My code snippet is like this:
```
#define CONCATE(a, b) a ## b
#define CALL_SEARCH(n, x, y) search(n, arg1, arg2, x, y)
...
int i;
for (i = 1; i (less than or equal to) number; ++i)
{
results = CALL_SEARCH(CONCATE(f, i), tol, max_tries);
}
```
What I want to do ... |
CONCATENATEcreates "fi", not "f1". You wantfto be an array and useias an index on it.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking us torecommend or find a tool, library or favorite off-site resourceare off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead,describe the problemand what has been do... |
Busybox does not contain a TCP/IP stack. It makessystem callsto the operating system to do networking operations.
Here is a good starting place to read about the kernel side of things:Anatomy of the Linux networking stack.
|
```
void empty() { }
```
will be compiled to
```
push ebp
mov ebp, esp
ret
```
How do I declare the function so that it has no "decoration" code? just plainret.
If that is not possible, is this possible to define completely assembler function inside the.Cfile? It is possible to define assembler function in the.asmf... |
Declare the function with the__declspec(naked)modifier.
|
Is it allowed to add Includes in C++ headers? like in this example.
```
#ifndef SOMEH_H
#define SOMEH_H
#include <fstream>
int funcofsomekind(){
ofstream myfile;
myfile.open ("Stackoverflow.stack");
myfile << "wolololol";
myfile.close();
}
#endif
```
|
You certainly add#include <something.h>in your header, and it is often done if necessary.
However, it is considered very bad idea to put any code in headers (like you did). At the very least, including function twice via header in different source files will lead to duplicate function definition at linking time.
|
Hi I'm trying to convert DELAY from milliSeconds into microSeconds and store it in a double. But when I use the below code it produces the output 0.000000 On a calculator it works as the desired outcome I'm after if 500 is the DELAY is 0.500000 so I can use it with 'struct timeval'.
```
#define DELAY 500
double nu... |
This:
```
(DELAY / 1000);
```
is integer arithmetic, and evaluates to zero whenDELAYis less than 1000, change to:
```
(DELAY / 1000.0);
```
|
I am using#define ENABLE_FLAGinside C++ code and correspondingly trying to include a section of code, whileENABLE_FLAGis defined.
My question is, the particular set of code inside
```
#ifdef ENABLE_FLAG
....setofcode....
#endif
```
is evaluated during runtime through#ifdefcheck or compiler itself sees theENABLE_FLA... |
#ifdefand all those other things you see with a#as the first character on the line are "C preprocessor directives." These are handled even before compilation proper. So there will be no runtime decision made at all--the enabled/disabled block of code is decided at the earliest part of the build process.
|
Is it allowed to add Includes in C++ headers? like in this example.
```
#ifndef SOMEH_H
#define SOMEH_H
#include <fstream>
int funcofsomekind(){
ofstream myfile;
myfile.open ("Stackoverflow.stack");
myfile << "wolololol";
myfile.close();
}
#endif
```
|
You certainly add#include <something.h>in your header, and it is often done if necessary.
However, it is considered very bad idea to put any code in headers (like you did). At the very least, including function twice via header in different source files will lead to duplicate function definition at linking time.
|
Hi I'm trying to convert DELAY from milliSeconds into microSeconds and store it in a double. But when I use the below code it produces the output 0.000000 On a calculator it works as the desired outcome I'm after if 500 is the DELAY is 0.500000 so I can use it with 'struct timeval'.
```
#define DELAY 500
double nu... |
This:
```
(DELAY / 1000);
```
is integer arithmetic, and evaluates to zero whenDELAYis less than 1000, change to:
```
(DELAY / 1000.0);
```
|
I am using#define ENABLE_FLAGinside C++ code and correspondingly trying to include a section of code, whileENABLE_FLAGis defined.
My question is, the particular set of code inside
```
#ifdef ENABLE_FLAG
....setofcode....
#endif
```
is evaluated during runtime through#ifdefcheck or compiler itself sees theENABLE_FLA... |
#ifdefand all those other things you see with a#as the first character on the line are "C preprocessor directives." These are handled even before compilation proper. So there will be no runtime decision made at all--the enabled/disabled block of code is decided at the earliest part of the build process.
|
Probably obvious, but even my clever "how to c" book doesn't really help me here. I just started with C programming, so sorry if the answer eludes me.
I usefopen("%s.txt", "w+")in order to save a textfile. However I have no idea how the user can input a string for %s. I tried it with scanf and other variations. But n... |
```
#include<string.h>
char filename[255];
FILE *fp;
scanf("%s",filename);
strcat(filename,".txt");
fp=fopen(filename,"w+");
```
|
I'm debugging my C code
and I want to know the value of a chars array.
the problem is that it is seen like this:
0x63d7c4c8 "\327\220\327\250\327\225\327\236"
how can I convert to Hebrew chars, via eclipse debug window?
|
```
bash ~ $ printf "\327\220\327\250\327\225\327\236\n"
ארומ
bash ~ $
```
Not sure you can change it in the debug window, but take a lookhere.
|
This question already has answers here:C++ : why bool is 8 bits long?(7 answers)Closed9 years ago.
Forbool, it's 8 bit while has only true and false, why don't they make it single bit.
And I know there'sbitset, however it's not that convenient, and I just wonder why?
|
The basic data structure at the hardware level of mainstream CPUs is a byte. Operating on bits in these CPUs require additional processing, i.e. some CPU time.
The same holds forbitset.
|
I'm trying to make a macros that calculates 2nand 2n - 1. That would be:
```
#define b(n) (2 << (n))
#define a(n) ((b(n))-1)
```
However for some reason this cast it asint, but I'm willing to useunsigned long int. Does anyone know how to solve this? I have thought about using inline functions, however I don't fully ... |
OP wantsunsigned long int, then use that type in your macro
```
#define b(n) (1UL<<((unsigned)(n)))
```
When OP used(2 << (n)), the result is typeint, as2is anint. Operator<<with anintandunsignedresults inint. Instead useunsignedthroughout.
Further, to emulatepower(2,n), certainly the OP wanted to use1shifted l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.