question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
This question already has answers here:Closed11 years ago.
Possible Duplicate:objective c difference between id and void *
While reading through NSZone.h in the Foundation framework I ran across a comment mentioning something being "more like a c style pointer than an id style object". I realized I don't understand ... |
A C pointer can point at anything - objects, structures, raw bytes, strings, ...
A 'id' pointer is pointing at an instance of an Objective-C object. 'id' is untyped, so it could be pointing at an instance of any class. Something like NSObject* is typed; you know what kind of object it is pointing at.
|
I have an array of structs that I have defined in a header file:
```
struct table {
otherStruct *list[16];
}
```
Now I want to be able to resize this array, change the size of the array, or dynamically allocate an array that can replace (or join) the original list in "table" once a condition is met. How can I a... |
MakelistanotherStruct **:
```
struct table {
otherStruct **list;
}
```
Now you canmallocit to be as big as you want andreallocat will.
|
Example code 1:
```
const int N=100000;
for(int j=0;j<N;j++){
arr1[j] += a1[j];
arr2[j] += a2[j];
}
```
Example code 2:
```
for(int j=0;j<N;j++){
arr1[j] += a1[j];
}
for(int j=0;j<N;j++){
arr2[j] += a2[j];
}
```
I need to calculate the running time of these block of code. Is there any tool(benchma... |
If you're running under a system that includes it you can just execute it undertime:
```
$ time ./benchmark1
```
and
```
$ time ./benchmark2
```
|
This question already has answers here:Closed11 years ago.
Possible Duplicate:How do I write a short literal in C++?
I can usellto represent a long long number, I can useuto represent a unsigned number, etc.
Is there a number suffix forshorttype?
|
The C++ standard only gives these integer suffixes (2.13.1)
```
unsigned-suffix: one of
u U
long-suffix: one of
l L
long-long-suffix: one of
ll LL
```
so no, there is no suffix for shorts.
|
Can someone explain to me how less, vi and curses programs manage graphics output? Can they change individual characters on the screen or do they have to literary clear and redraw the screen whenever something changes?
It would be really neat if someone could hack a tiny less clone together, without all the boilerpla... |
There exist specialEscape Codesthat, when sent to the terminal, instruct the terminal to reposition the cursor without disrupting what's already being displayed.
|
I used thesystem("pause")withstdio.hand it worked without error. When I looked at the stdio functions,system()is in stdlib. How come it worked, and here is the code?
```
#include <stdio.h>
int main() {
printf("Hello World\n" );
system("pause");
return 0;
}
```
|
The answer is that it's an implicit declaration. If the compiler doesn't see a prototype for a function, it assumes it was declared like:
```
int system();
```
If you turn up the warning level on your compiler, you'll likely see that this causes a warning. Implicit declarations are generally undesirable, but in this... |
I have a third party .so that was generated on a 64bit machine. I'd like to use this same .so on a 32bit machine. Anyone know how to do the conversion? I tried:
```
objcopy "--input-target=elf64-x86-64" "--output-target=elf32-i386" 64bit.so 32bit.so
```
but I'm still getting "File format not recognized" from gcc.... |
You can't.
You need to get 32bit version of this 3rd part library or recompile it from its sources
|
Running Mac OS 10.7.2 and trying to runlibfaketimeand nothing happen. I installed and ran exactly as directed only the time and date stay exactly as are set in the system? Is anyone else able to successfully run this on OSX?
```
$ date
Mon Jan 30 21:05:09 CST 2012
$ LD_PRELOAD=./libfaketime.so.1 FAKETIME="-15d" dat... |
Everything on OSX is prefixed DYLD, not LD. And they change the names a bit.. I think what you want is:
```
DYLD_INSERT_LIBRARIES
```
This is a colon separated list of dynamic libraries to load before the ones specified in the program. This lets you test new modules of existing dynamic shared libraries that ar... |
I need some fast method to update key/value type data or alternatively an arbitrary amount of "counters" system-wide on Linux. The systems in question are Ubuntu 10.04, RHEL 4.8 and RHEL 5.x.
Now, I am aware of memcached, but it seems to be more suited for long-running processes, such as FastCGI processes. Unfortunat... |
You could use a simpleDBM-like database, for exampleGDBM.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
May beBoomerangcan be of some help.
|
My code in netbeans is as follows:
```
int main(int argc, char** argv) {
int a = 2;
int b;
printf("b = ");
scanf("%d", &b);
printf("\n%d",a+b);
return (EXIT_SUCCESS);
}
```
The problem is when I run this, the first thing it waits for is the user input, it doesn't show "b = ". As soon as I in... |
printfis buffered onstdout... therefore you won't see the output until there is either an end-of-line placed in the buffer, the buffer is filled to its max capacity, or the buffer is explicitly flushed usingfflush.
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed9 years ago.Improve this question
Using the standard i... |
You could usetoupper. If you need to check to see if the input character is lower case first, you can useislowerto test it.
|
I'm currently programming in C with win32 API.I would like to know how can I permanently delete or cancel a mutex and semaphore.How can I do that, I haven't found anything about it in MSDN till now.Thanks!
|
You have tocloseall handles that are opened to that mutex / semaphore.
If you don't own some of them, you can not.
|
Ive narrowed the issue down to a few lines of code but im having trouble identifying what is illegal about the function call causing a "Access violation writing location" I was hoping someone better with C could help me out?
The input the code is breaking on is
```
vn 0.185492 -0.005249 0.982604
```
I want to assig... |
You forgot the&beforevn[normCount].vn3.
By the way, what is the point ofline[1] == 'n' && line[1] != 't'?
|
Some time ago a friend of mine told me not to usereallocbecause it's unsafe, but he couldn't tell me why, so I made some research on the subject and the nearest references to my doubt were:
FirstSecond
I want to know if I can continue to usereallocin my code or if it's unsafe is there any other way to reallocate mem... |
It's perfectly safe to userealloc. It is the way to reallocate memory in a C program.
However you should always check the return value for an error condition. Don't fall into this common trap:
```
p = realloc(p, new_size); // don't do this!
```
If this fails,reallocreturnsNULLand you have lost access top. Instead d... |
I don't know what I am doing wrong... but here is the snippet of code that is being executed:
```
if (fork() == 0)
{
// child
int fd = open(fileName, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
dup2(fd, 1); // make stdout go to file
execvp("ls","ls");
close(fd);
... |
My guess is that the execvp doesn't work but since you don't handler errors you don't see it.
Try this:
```
char *const args[] = {"ls", NULL};
execvp(args[0], args);
/* If this is reached execvp failed. */
perror("execvp");
```
Alternatively you can use compound literals:
```
execvp("ls", (char *[]){"ls", NULL})... |
If I'm writing abstract data types in C, are the functions written to perform actions on these data types and exposed in the interface (.h files) calledfunctions,methods, or something yet completely different? I can't seem to find a constructive answer anywhere. Ismethoda C++ specific term?
|
Is method a C++ specific term?
A "method" is an object-oriented programming term, and refers to a function that is part of the namespace of an object. So you can create methods for objects in languages like C++, Java, Objective-C, etc. In C on the otherhand, you still have stand-alone functions, not methods.
Keep i... |
Already declared is an array such as:
```
char ma[10][20];
```
The address of a specific element is gotten using:
```
p = &ma[1][18];
```
Which element willppoint to afterp++;?
|
Adding 1 to a address of member of array, get the address of the next member. since p is the address ofma[1][18], which is member of the arrayma[1],p+1is the address ofma[1][19]. (And of course,p++;is likep=p+1;)
Edit: I assumed, of course, that p ischar*. If it's something else, the answer can be other.
|
i would like to have one identifier responsible for several values for one time. if i had one this is what i could do:
```
if (myVariable == IDENTIFIER)//instead of if(myVariable == 5 || myVariable == 7) if i need A LOT of values
[myObject doSomething];
```
Is there a possibility to implement it somehow?
|
I think the closest you can come is by using bitmasks, so that you represent the set of allowable values with a mask that has all of the values set:
```
const int ALL_VALUES = (1 << 5) | (1 << 7);
if ((1 << myVariable) & ALL_VALUES)
[myObject doSomething];
```
Above, bit-wise AND is used to compute the intersectio... |
This is the first time I'm coding C in Windows and a weird bug is driving me crazy.
I'm trying to open a .txt file using fopen, and it keeps giving me the "file doesn't exist" error (it also gave me the "no permission" error, once).
My code is as follows (doesn't get any simpler than that):
```
FILE *file;
if((fil... |
I bet you have the Windows "hide extensions"bugfeature turned on. So the file which is really called "file.txt" appears in your Explorer as "file". And if it appeared to be "file.txt" in the Explorer, it would have to be named "file.txt.txt" on the hard drive.
|
I'm currently programming in C with win32 API.I would like to know how can I permanently delete or cancel a mutex and semaphore.How can I do that, I haven't found anything about it in MSDN till now.Thanks!
|
You have tocloseall handles that are opened to that mutex / semaphore.
If you don't own some of them, you can not.
|
Ive narrowed the issue down to a few lines of code but im having trouble identifying what is illegal about the function call causing a "Access violation writing location" I was hoping someone better with C could help me out?
The input the code is breaking on is
```
vn 0.185492 -0.005249 0.982604
```
I want to assig... |
You forgot the&beforevn[normCount].vn3.
By the way, what is the point ofline[1] == 'n' && line[1] != 't'?
|
Some time ago a friend of mine told me not to usereallocbecause it's unsafe, but he couldn't tell me why, so I made some research on the subject and the nearest references to my doubt were:
FirstSecond
I want to know if I can continue to usereallocin my code or if it's unsafe is there any other way to reallocate mem... |
It's perfectly safe to userealloc. It is the way to reallocate memory in a C program.
However you should always check the return value for an error condition. Don't fall into this common trap:
```
p = realloc(p, new_size); // don't do this!
```
If this fails,reallocreturnsNULLand you have lost access top. Instead d... |
I don't know what I am doing wrong... but here is the snippet of code that is being executed:
```
if (fork() == 0)
{
// child
int fd = open(fileName, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
dup2(fd, 1); // make stdout go to file
execvp("ls","ls");
close(fd);
... |
My guess is that the execvp doesn't work but since you don't handler errors you don't see it.
Try this:
```
char *const args[] = {"ls", NULL};
execvp(args[0], args);
/* If this is reached execvp failed. */
perror("execvp");
```
Alternatively you can use compound literals:
```
execvp("ls", (char *[]){"ls", NULL})... |
If I'm writing abstract data types in C, are the functions written to perform actions on these data types and exposed in the interface (.h files) calledfunctions,methods, or something yet completely different? I can't seem to find a constructive answer anywhere. Ismethoda C++ specific term?
|
Is method a C++ specific term?
A "method" is an object-oriented programming term, and refers to a function that is part of the namespace of an object. So you can create methods for objects in languages like C++, Java, Objective-C, etc. In C on the otherhand, you still have stand-alone functions, not methods.
Keep i... |
Already declared is an array such as:
```
char ma[10][20];
```
The address of a specific element is gotten using:
```
p = &ma[1][18];
```
Which element willppoint to afterp++;?
|
Adding 1 to a address of member of array, get the address of the next member. since p is the address ofma[1][18], which is member of the arrayma[1],p+1is the address ofma[1][19]. (And of course,p++;is likep=p+1;)
Edit: I assumed, of course, that p ischar*. If it's something else, the answer can be other.
|
i would like to have one identifier responsible for several values for one time. if i had one this is what i could do:
```
if (myVariable == IDENTIFIER)//instead of if(myVariable == 5 || myVariable == 7) if i need A LOT of values
[myObject doSomething];
```
Is there a possibility to implement it somehow?
|
I think the closest you can come is by using bitmasks, so that you represent the set of allowable values with a mask that has all of the values set:
```
const int ALL_VALUES = (1 << 5) | (1 << 7);
if ((1 << myVariable) & ALL_VALUES)
[myObject doSomething];
```
Above, bit-wise AND is used to compute the intersectio... |
This is the first time I'm coding C in Windows and a weird bug is driving me crazy.
I'm trying to open a .txt file using fopen, and it keeps giving me the "file doesn't exist" error (it also gave me the "no permission" error, once).
My code is as follows (doesn't get any simpler than that):
```
FILE *file;
if((fil... |
I bet you have the Windows "hide extensions"bugfeature turned on. So the file which is really called "file.txt" appears in your Explorer as "file". And if it appeared to be "file.txt" in the Explorer, it would have to be named "file.txt.txt" on the hard drive.
|
Here i want to make one file and write some data in this file with c program.
How can i write this data with new line character also. same as like this.
And in 3rd line i want to put one variable value instead if"BD_ADDR"
Can Any body Please Explain me the way how can i achieve this.
```
filename = "asound.conf"
``... |
Withfopen(),fprintf(), andfclose().
Don't forget error validation!
|
C language has a data-typefloat. Some machines have a floating point processor that carries out all the floating point computations. My question is: Could there be some machines without a floating point processor? How do such machines use floating point?
|
Many small controllers do not have floating point units. In that case, there is a floating point software library.
In the mid-1980s, we considered ourselves blessed if our system had an 8087, the FPU for the 8086 and 8088. Unfortunately our software had to work correctly if an 8087 was present or not. That meant t... |
I have the following in my file.h:
```
#define SetSP(sp) asm("movq %0,%%rsp": : "r" (sp) )
```
However, in my file.c file, when I try using it for example:
```
SetSp(lwp_ptable[lwp_procs].sp);
```
I get an implicit declaration of function SetSp, when I compile file.c. I have #include "file.h" in file.... |
Your define isSetSP, while you use it asSetSp, note the case difference in letterp. Welcome to case sensitive language...
|
I'm taking a look at an application that defines a large set of constant arrays. What really confuses me is the use of two pound signs next to each other in a macro. For example:
```
#define r0(p,q,r,s) 0x##p##q##r##s
```
What do those two pound signs mean?
|
##provides a way toconcatenate actual argumentsduring macro expansion.
|
I am finding that usingassert(...)makes my code shorter and easier to read, as opposed to lengthyif..else..blocks. However, are there goodtechnicalreasons not to useassert(...)in shipping code, when it does the same thing as testing areturnvalue while using less code?
|
Having readthis articleI will share my beliefs aboutassert:
Yes it's fine to useassertwhen something absolutely should meet the condition you are asserting.Many languages allow you to raise custom errors when asserting, C not having "Exceptions" may produce errors that are a little harder to diagnose without directly... |
Can I set a small program that I wrote as my login shell? Instead of a regular login shell like bash? I tried googling but could not find any useful information. Any pointer is appreciated.
|
```
chsh -s /usr/bin/foo someuser
```
Or usevipwto edit/etc/passwd(just don't edit it directly).
|
I'm writing a C program that accepts input one line at a time from the user. However, after the user enters the line of input, I want to either clear the line they typed from stdout, or prefix it. The former is ideal, but the latter would be acceptable for my purposes. Is there a way to do this? Tell me if I need to b... |
You cannot in C portably clear a line after a new line was issued.
On most POSIX systems you can use ncurses library to position the cursor and clear any line.
|
How do you link 2 c library files, to a c++ file?
Right now I am doing this:
```
> gcc -c file1.c (this works fine)
> gcc -c file2.c ( this works fine)
> g++ -c myc++file.cpp (this works fine)
> g++ -o program myc++file.o file1.o file2.o
```
-> I get an error on this last one saying that their is a undefined re... |
Is this functionstatic?
Did you useextern "C"inmyc++file.cpp?
if the answers isnoandyes, show us some code.
(By the way, try to check usingnmif that function is really infile2.o)
|
For integer values, it is pretty straightforward the difference in little endian and big endian representation.
But it is not clear for me how a little endian float differs from a big endian float.
And finally, I would like to know which is more commonly used.
|
Endianness just is a property of the bytes that make up a value that's composed from multiple bytes. Since a floating point number takes up 4 or 8 bytes endianness tells you in which order to read them. This isexactlythe same as with integer values.
|
Closed.This question is seeking recommendations for books, tools, software libraries, and more. It does not meetStack Overflow guidelines. It is not currently accepting answers.We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answer... |
I'd guess both of those use theVisualizer plugin SDK.
|
If I have a string like:
```
const char* mystr = "Test Test Bla Bla \n Bla Bla Test \n Test Test \n";
```
How would I use the newline character '\n', to split the string into an array of strings?
I'm trying to accomplish in C, the thingstring.Split()does in C# or boost's string algorithmsplitdoes in C++ .
|
Try to use thestrtokfunction. Be aware that it modifies the source memory so you can't use it with a string literal.
```
char *copy = strdup(mystr);
char *tok;
tok = strtok(copy, "\n");
/* Do something with tok. */
while (tok) {
tok = strtok(NULL, "\n");
/* ... */
}
free(copy);
```
|
I'd like to get a list of available devices (their IP address or hostname should be fine) connected to my local network. I've got some examples in C#, but I couldn't find any sample using C/C++. I'm familiar with the BSD socket API, just to clarify.
I have a "stub" kind of idea: maybe I should determine the range of ... |
You can also e.g. send an ICMP echo request packet to 224.0.0.1. This is a special all-nodes multicast address every node should respond to (except if a firewall rule or network policy setting prevents it).
|
The following code works with GCC's C compiler, but not with the C++ compiler. Is there a "shortcut" to achieve the same result in C++?
```
int array[10] = {
[1] = 1,
[2] = 2,
[9] = 9
};
```
EDIT:
Humm, I found this, clarifies everything.http://eli.thegreenplace.net/2011/02/15/array-initialization-with-e... |
This form of initialization is only defined in the C99 standard. It doesnotapply to C++. So, you'll have to assign your elements one-by-one:
```
int array[10] = { 0 };
array[1] = 1;
array[2] = 2;
array[9] = 9;
```
|
I ran this simple program, but when I convert frominttodouble, the result is zero. Thesqrtof the zeros then displays negative values. This is an example from an online tutorial so I'm not sure why this is happening. I tried in Windows and Unix.
```
/* Hello World program */
#include<stdio.h>
#include<math.h>
main... |
Maybe this?
```
int number;
double dblNumber = (double)number;
```
|
Im usingstrtokand getting a little confused.
I have an array holding a lot of strings and I want to tokenize the strings into a temporary array. When i perform the strtok it stored the first token in the temporary array, but also changed the original arrays value. So im pretty confused.
```
char cmdTok[10] , *cmd = ... |
Do thestrtokon a copy of the string.
```
char *copy = strdup(commands[0]);
cmd = strtok(copy, " \n");
/* ... */
free(copy);
```
If you don't have / want to usestrdup:
```
char *copy = malloc(strlen(commands[0]) + 1);
strcpy(copy, commands[0]);
/* ... */
```
|
What does the statement
```
WidthT getwidth(void);
```
mean? To me, this says thatgetwidthis called and is of typeWidthT. Is this correct?
|
The statement you're giving is a declaration that;
There exists a function called getWidth that takes no parameters and
returns something of type WidthT.
It's called a forward declaration and is usually used to tell the code following it to assume that the function exists somewhere else and will work to call.
|
I've seen a lot of console apps (that run on windows) having some dialog boxes and widgets inside them. Say for example:
A there are a lot more. Now my question: Is there any library (in C) for creating dialogs and widgets in a Win32 Console App?
UPDATE: Seen pdcurses, but it lacks libraries from the real ncurses ... |
you can use ncurses, please check the following question from stackoverflow.com:Is ncurses available for windows?
there is alsoPDCursesthat support Win32
you can also use the old libraryTurbo vision, I have never tested it on win32.
|
GCC gives a warningimplicit declaration of function foowhen you usefoo()before its declaration. Is there any GCC flag that would make treat this warning aserrorand stop compilation? Sometime it would save you some debugging work...
|
-Werrorwill treatallwarnings as errors. You can be more specific with-Werror-implicit-function-declaration
|
int:
The 32-bit int data type can hold integer values in the range of
−2,147,483,648 to 2,147,483,647. You may also refer to this data type
as signed int or signed.
unsigned int:
The 32-bit unsigned int data
type can hold integer values in the range of 0 to 4,294,967,295. You
may also refer to this data type si... |
Hehe. You have an implicit cast here, because you're tellingprintfwhat type to expect.
Try this on for size instead:
```
unsigned int x = 0xFFFFFFFF;
int y = 0xFFFFFFFF;
if (x < 0)
printf("one\n");
else
printf("two\n");
if (y < 0)
printf("three\n");
else
printf("four\n");
```
|
I have two strings, e.g.:
str1 = "aaabbbcccdddeee"str2 = "aaabbbccc"
How to do something likestr1 - str2to get thedddeeesubstring?
|
Ifstr2is guaranteed to be a prefix ofstr1, then this will suffice:
```
const char *str3 = &str1[strlen(str2)];
```
which is equivalent to this: (as @James points out in the comments)
```
const char *str3 = str1 + strlen(str2);
```
Of course,str3is just a pointer into one of the original strings. If the contents o... |
Is there any flow chart generator plugin for eclipse indigo v3.7, that automatically generates the flow chart for the C/C++ code? Please help.
|
Doxygenhttp://www.doxygen.orgis very good :)
|
Currently I am debugging an embedded application in Eclipse IDE. I've got some registers to inspect, mosly ony one bit from it. Is there any way to tell Eclipse to watch only one bit in chosen register?
|
Easiest solutions are usually the best. You can always create another variable just for debugging purposes
```
myDebugVar = (mainVar & MASK_THAT_EXTRACTS_YOUR_BIT) >> SOME_SHIFT;
```
Now watch your new 'myDebugVar' and you are done.
|
Is there any specific way to convert jpeg images to black and white using C? I converted a .bmp image to black and white using C by simply extracting the headers (which in .bmp file is 54 bytes in length) and converting the RGB to the respective gray level using the formula.
But how to do that in jpeg file?
|
If you can afford to link a library, I highly recommend OpenCV for this task:http://opencv.willowgarage.com/
|
What does the statement
```
WidthT getwidth(void);
```
mean? To me, this says thatgetwidthis called and is of typeWidthT. Is this correct?
|
The statement you're giving is a declaration that;
There exists a function called getWidth that takes no parameters and
returns something of type WidthT.
It's called a forward declaration and is usually used to tell the code following it to assume that the function exists somewhere else and will work to call.
|
I've seen a lot of console apps (that run on windows) having some dialog boxes and widgets inside them. Say for example:
A there are a lot more. Now my question: Is there any library (in C) for creating dialogs and widgets in a Win32 Console App?
UPDATE: Seen pdcurses, but it lacks libraries from the real ncurses ... |
you can use ncurses, please check the following question from stackoverflow.com:Is ncurses available for windows?
there is alsoPDCursesthat support Win32
you can also use the old libraryTurbo vision, I have never tested it on win32.
|
GCC gives a warningimplicit declaration of function foowhen you usefoo()before its declaration. Is there any GCC flag that would make treat this warning aserrorand stop compilation? Sometime it would save you some debugging work...
|
-Werrorwill treatallwarnings as errors. You can be more specific with-Werror-implicit-function-declaration
|
int:
The 32-bit int data type can hold integer values in the range of
−2,147,483,648 to 2,147,483,647. You may also refer to this data type
as signed int or signed.
unsigned int:
The 32-bit unsigned int data
type can hold integer values in the range of 0 to 4,294,967,295. You
may also refer to this data type si... |
Hehe. You have an implicit cast here, because you're tellingprintfwhat type to expect.
Try this on for size instead:
```
unsigned int x = 0xFFFFFFFF;
int y = 0xFFFFFFFF;
if (x < 0)
printf("one\n");
else
printf("two\n");
if (y < 0)
printf("three\n");
else
printf("four\n");
```
|
I have two strings, e.g.:
str1 = "aaabbbcccdddeee"str2 = "aaabbbccc"
How to do something likestr1 - str2to get thedddeeesubstring?
|
Ifstr2is guaranteed to be a prefix ofstr1, then this will suffice:
```
const char *str3 = &str1[strlen(str2)];
```
which is equivalent to this: (as @James points out in the comments)
```
const char *str3 = str1 + strlen(str2);
```
Of course,str3is just a pointer into one of the original strings. If the contents o... |
Is there any flow chart generator plugin for eclipse indigo v3.7, that automatically generates the flow chart for the C/C++ code? Please help.
|
Doxygenhttp://www.doxygen.orgis very good :)
|
Currently I am debugging an embedded application in Eclipse IDE. I've got some registers to inspect, mosly ony one bit from it. Is there any way to tell Eclipse to watch only one bit in chosen register?
|
Easiest solutions are usually the best. You can always create another variable just for debugging purposes
```
myDebugVar = (mainVar & MASK_THAT_EXTRACTS_YOUR_BIT) >> SOME_SHIFT;
```
Now watch your new 'myDebugVar' and you are done.
|
Is there any specific way to convert jpeg images to black and white using C? I converted a .bmp image to black and white using C by simply extracting the headers (which in .bmp file is 54 bytes in length) and converting the RGB to the respective gray level using the formula.
But how to do that in jpeg file?
|
If you can afford to link a library, I highly recommend OpenCV for this task:http://opencv.willowgarage.com/
|
What is the equivalent of cin.peek() for C programming? I need to scan files for '/r' and '/r/n' (these are the end of line markers for DOS files) so I need to "peek" ahead to the next character if the current character is a '/r'
Thanks!
|
There isungetc(), which allows you to push characters back (as if they were not already read), when you've peeked at them.
http://www.zyba.com/reference/computing/c/stdio.h/ungetc.php
|
I was checking outclock() on cplusplus.com. Their example involves making the process wait for a second and then output a line, in a loop until 10 seconds have ellapsed. I need to do something similar in the homework assignment I'm working on. What I was wondering was this: if I just send my program into a loop, isn't... |
Yes, using a system call or library function likesleep()is much better. Thatclock()example is just meant to just show how to correctly call the function and interpret its return value, not to illustrate the best way to make a program wait.
|
I am receiving this error while compiling a C program in MinGW. As far as I know, I thought 'intptr_t' was a type in the C99 standard. Am I not including a file?
|
You need to includestdint.h.
Note thatintptr_tanduintptr_tare indeed C99 types but they are optional.
|
I am trying to do
```
memset(&idt_entries, 0, sizeof(idt_entry_t)*256);
```
which produces
error: cannot convert 'idt_entry_t (*)[256] {aka idt_entry_struct ()[256]}' to 'u8int{aka unsigned char*}' for argument '1' to 'void memset(u8int*, u8int, u32int)'
If it helps, it is C code wraped inextern "C" {...}.
Thanks... |
Are you compiling this as C++?
Add a cast.
memset ((u8int*)idt_entries, 0, sizeof(idt_entry_t)*256);
|
I'm using "Visual Studio 2010" on "Windows 7 32bit", and I'm working on my "debug" build.
In my program I use fopen to access a file using this code:
```
FILE *f = fopen("simple_test.asm", "r");
```
When I run (F5) it returns a NULL pointer.
When I use full path it works well.
The strange thing is, when I open the... |
The current directory for Visual Studio 2010 might not be the directory that has simple_test.asm.
As simple as that.
|
I created a generic vector:
```
typedef struct vector_t
{
int max; /* max number of elements */
int size; /* number of elements present into the array */
void **data; /* array of elements */
};
```
I'd like to know if in standard Ansi-C exists a function for searching a specific element if the array ... |
If your data isn't sorted, then "searching" would be just be a for loop that goes through the elements and compares with the search value. If you're going to be searching often, then you should probably sort your data. There are standard functions for doing the sorting, like qsort()
|
why do I get results 6, and then 8 by from the following code? I searched through the posts but cannot find an exact match of my question. Thanks.
```
#include <stdio.h>
void getSize(const char *str)
{
printf("%d\n", sizeof(str)/sizeof(char));
}
int main()
{
char str[]="hello";
printf("%d\n"... |
In yourgetSize()function,stris a pointer. Thereforesizeof(str)returns thesize of a pointer. (which is 8 bytes in this case)
In yourmain()function,stris an array. Thereforesizeof(str)returns thesize of the array.
This is one of the subtle differences between arrays and pointers.
|
This is my struct:
```
struct example {
int c=0;
char buf[10];
}
```
I have a struct of this type allocated inmain()
```
...
struct example *ex=malloc(sizeof(*ex));
...
```
and passed to a thread by
```
...
pthread_create(&id[i], NULL, t_func, ex);
...
```
pthread_create is called into a child of main.
... |
In C you can assign objects of structure type:
```
struct example *extmp = args;
struct example local_copy = *extmp;
```
|
Why output is giving 3 , expecting -3. How to handle such preprocessing in c?
```
#include<stdio.h>
#include<math.h>
#define sq(x) ((x<0)?sqrt(-x):sqrt(x))
int main()
{
int x;
x=sq(-9);
printf("%d\n",x);
return 0;
}
```
|
because your # define "sq" checks if its a negative number and turns it into a positive number before calculating a square root
its doing sqrt(-x) which is sqrt(-(-9)) ( taking the negative of a negative is the positive)
so its doing sqrt(9)
|
I'd like my application to have portable access to the configuration files installed duringmake install(dist_sysconf_DATA). Is it possible to access$(sysconfdir)via config.h?
|
It is, but you should not do this according to official voices (as in, I am not gonna search the manual for it now) so as to continue supporting overriding it for specific objects to be built.
```
make CPPFLAGS="-USYSCONFDIR -DSYSCONFDIR=/blah" thisoneobject.o
```
Hence, what one is supposed to do:
```
AM_CPPFLAGS ... |
I think that's what clip are used for but I can't find any example to do this.
I need to:
Limit the region by setting a new clipmask (altering the GC)DrawSet the GC back to its previous state
|
You can do it by usingXSetClipRectangles()referencedhereandXSetClipMask()referencedhere
So:
```
Display dpy; //This is your display, we'll assume it is a valid Display
GC gc; //This is your GC, we'll assume it is a valid GC
XRectangle recs[]; //This is an array containing the clipping regions you want.
int recs_n; /... |
We know that when a function is called a block of memory is pushed into the stack and when the function finishes its job the block of memory which was pushed earlier is now popped out.
Is it correct in all the circumstances. Even if the function contains declaration of static variables? If yes then how do the static v... |
Static local variables don't live on the stack, they live in the same memory as a global variable. .bss is memory where global variables that are uninitialized will reside. .data could hold variables declared with an initial value.
|
I have written a program which I run after connecting to the box over SSH. It has some user interaction such as selecting options after being prompted, and usually I wait for the processes it carries out to finish before logging out which closes the terminal and ends the program. But now the process is quite lengthy... |
You can run a program in the background by following the command with "&"
wget -m www.google.com &
Or, you could use the "screen" program, that allows you to attach-deattach sessions
screen wget -m www.google.com(PRESS CTRL+D)screen -r (TO RE ATTACH)
http://linux.die.net/man/1/screen
|
How is the function declaration different from the function prototype?
I'm posting this question in reference tothis answeron a question.
|
AFunction declarationmay/maynot not include the function arguments.While aFunction Prototypemustinclude the function arguments.
FromWikipedia:Consider the following function prototype:
```
int fac(int n);
```
This prototype specifies that in this program, there is a function namedfacwhich takes a single integer arg... |
I'm writing code on a GPU enabled machine, but my code needs to be portable to computers without a GPU. So I wrote 2 functions, one that uses only the CPU and one that uses CPU+GPU.
I'm for a conditional compliance code, for example:
```
if (COMPUTER_HAS_GPU)
//Run CPU+GPU code
else
//Run CPU only code
`... |
You can usecudaGetDeviceCount()
For Example:
```
int devices = 0;
cudaError_t err = cudaGetDeviceCount(&devices);
if (devices > 0 && err == cudaSuccess)
{
// Run CPU+GPU code
}
else
{
// Run CPU only code
}
```
|
I have a large code written in C, but I did not write all of it myself. I wish to create an overview of the call structure in the code for reference. That is: I wish to know what (non-standard) functions are called by the different functions in the code, and thus create a hierarchy or a tree of the different functions... |
Doxygen does that too, it has to be enabled though.
|
I am trying to learn C, and I wonder why this doesn't work?
```
#include <stdio.h>
int main(int argc, char *argv[])
{
char testvar[] = argv[0];
//do something with testvar
return 0;
}
```
|
You could do this instead:
```
char *testvar = argv[0];
```
Or maybe:
```
char *testvar = strdup(argv[0]);
/* Remember to free later. */
```
Aspmgnotes,strdupisn't standard. Implementing it using malloc + memcpy is a nice exercise.
Or even:
```
char testvar[LENGTH];
if (strlen(argv[0]) >= LENGTH)
fprintf(std... |
1) Can I create a link list in C with out using pointers (and without using structure) ?
2) Java doesn't use pointers then how linked list are implemented in Java ?
|
I don't see how it would be possible.Java does have pointers. They're just called references in Java, but they're basically the same thing. Every variable pointing to an object is a reference, or pointer, to the object. If the variable is null, and you try to dereference it, you get a NullPointerException.
|
I'm reading an analogue value from a Pin on a µC.
I want to check periodically if the value has changed more thanx.
Here, I am using theabs()function, but I want to keep it simple.
Can you help me?
```
int algVal= 0;
int oldVal = 0
while(1){
algVal = getAlgVal();
if(abs(algVal - oldVal) > x)
{
doStuff(... |
That sounds like a fantastic approach, and would probably be very nice in terms of runtime performance,abs()for integers is cheap. If in doubt, read the generated assembly of course.
|
I have been working on project, to make a website which read files(c/c++ text file) and compile the code written on it.
How can I use compiler which is on my server?
|
If$_POST['CODE']contains the cpp code. You can do the following.
```
$code = do_sanitizing($_POST['CODE']);
$filename = "cfile".time().".c";
// put the contents in a file
file_put_contents($filename, $code);
// compile it
$output = system("/usr/bin/gcc $filename 2>&1");
echo $output;
```
Note:This type of compiling... |
what does the (int *) do in the following code?
```
int *ptr = (int *) malloc(10 * sizeof (int));
```
i'm new to C and i've seen the above code with and without the (int *) so im wondering what it does.
|
That means "cast avoid*pointer into aint*pointer" -malloc()returnsvoid*and you ask the compiler to treat thatvoid*as if it wasint*. This construct aroundmalloc()is only needed in C++ code, and istotally unneeded and even evil in Cbecause it can cause rather subtle yet devastating errors.
|
I just want to know why this piece of code giving me segfault.
```
if(argc < 2){
printf("\n Please mention the file name");
exit(1);
}
FILE* fp;
if((fp = fopen(argv[1],"r")) == NULL){
printf("\n can't open file");
exit(1);
}
char* str;
fgets(str,80,fp);
printf("\n this is the output %s",str);
```
If ... |
You're not allocating any memory; you're just declaring achar *. Eitherchar str[100]will work, or:
```
char *str = malloc(100);
```
That will allocate memory for your string. Otherwise, you're just reading fromfgets()into memory that isn't yours, and causing a segmentation fault.
If you do this, make sure to callfr... |
I want to do hardware interaction using "C" Program. I have heard that using Printer's port I can create a C Program which can control a "Bulb" or "Tube Light" to on or off. Which means if I press any key from my Keyboard ( Suppose "1" ) then Bulb will be on and from another key I want to off it. How can I achieve thi... |
Seehttp://logix4u.net/parallel-port. Since (you say) you’re using Windows 98, theirTutorial on Parallel Port Interfacingwill be directly applicable.
If you want to write programs that can be used on later versions of Windows, see also theirInpout32.dll for Windows 98/2000/NT/XP, which claims to be compatible with th... |
I am learning(just finished) C+Algorithms and am a newbie. I wanted to know if the POSIX Linux API is used on a Mac. Linux has functions like pread pwrite readv writev nftw symlink pipe popen posix_self sigprocmask sigaction (system calls). Does the Mac have the same API?? I heard that OS-X is based on a BSD kernel so... |
The Wikipedia article on POSIXhas a section dedicated to compliance. Short answer: yeah, it's going to have all the POSIX functionality you're likely to come up against. And it will probably have more (e.g. a lot of BSD apis that might not actually be POSIX)
|
I have a double link list that stores some information. When I try and return one of the values inside the link list, I get the warning: function returns address of local variable.
This is my return statement:
```
return curr_val->value;
```
value is of typeconst void*.
Method signature is like:void *get_val(int ... |
The problem is likely that you have assigned the address of a stack-allocated variable tovalue. You need to usenewormallocto get memory for variables you intend to have continue to exist beyond the current stack frame.
|
I am running a Ruby gem which relies on a C extension (not a call to system).The C code makes several calls to printf.I want to silence the output of these calls.Changing Ruby's STDOUT (example) or STDERR does not prevent the text from being output.
Is it possible to do this without modifying the C code? If so, how?
|
Someone originally commented on my post suggesting to useIO.reopen. This worked for me. The person has unfortunately since deleted his/her comment, so I'm posting the more detailed function I used in the end:
```
def silence_stdout(log = '/dev/null')
old = $stdout.dup
$stdout.reopen(File.new(log, 'w'))
yield
... |
If I have image dataimgAandimgB, then I'd like to computeimgCas follows:
```
for (int i = 0; i < numPixelsInA; i++) {
imgC[i] = max(0, imgA[i]-imgB[i]);
}
```
I can see no way to do this in openCV without writing code that is essentially like the above. Curious if I'm missing something.
As a caveat to the abov... |
With the newer C++ stylecv::Matstructure you can do simple arithmetic such as this on the matrices directly.
```
cv::Mat A, B, C;
A = getImageA();
B = getImageB();
C = A - B;
```
Alternatively the subtract function may be of use, seehere.
|
I am getting the following warning for two lines of my code.
```
initialization discards qualifiers from pointer target type
```
The two lines are the sources of the warning.
```
function (const char *input) {
char *str1 = input;
char *str2 = "Hello World\0";
}
```
I think the first line gives an error because... |
You need to declare it const:
```
const char *str1 = input;
```
|
suppose this code:
```
main()
{
int *x;
*x = 3;
printf("%d %d %d\n", *x, &x, x);
// output 3 5448392 2293524
}
```
if*xis the value;&xthe addres; what does mean that value ofx?
|
*xis the value (correct)xis the address of the value.EDITIn your case, this address is uninitialized, so it is not pointing anywhere in particular (thanks Keith Nicholas for mentioning this).&xis the address of the [pointer thatshouldcontain the] address of the value.
(it's worth pointing out that your program may cr... |
I am using mingw32-make to compile a project to Windows, which depends on a project called libevent2. I keep receiving this error -
```
util.h:69:25: fatal error: sys/socket.h: No such file or directory
```
Obviously a file from the Linux API is trying to be included, which won't work on Windows. Upon further invest... |
You should use_WIN32and may also want to check for__CYGWIN__
```
#if defined _WIN32 || defined __CYGWIN__
```
|
I have two strings:
```
prettyCoolString
CoolString
```
I want to only get the part that sayspretty. I looked through the C string functions, but I cannot find out how to find the position of CoolString in prettyCoolString.
In Java, I can just find where CoolString appears in prettyCoolString, but with C, all I can... |
Try something like this:
```
char *source = "prettyCoolString";
char *find = "CoolString";
char dest[LENGTH];
char *p = strstr(source, find);
strncpy(dest, source, p - source);
```
|
I am writing an API that uses sockets. In the API, I allocate memory for various items. I want to make sure I close the sockets and free the memory in case there is a signal such as Ctrl-C. In researching this, it appears free() is not on the safe function list (man 7 signal) thus, I can't free the memory inside a ... |
Alternatively, don't catch the signal and just let the OS handle the cleanup as it's going to do during process cleanup anyway. You're not releasing any resources that aren't tied directly to the process, so there's no particular need to manually release them.
|
I'm trying to use this function in a C program that needs to be able to compile in Linux and Windows. At first I tried using strtok_r, but then when I compiled on windows, it complained about the function not existing and said it would assume it's an extern function, but then failed. I then used strtok_s and it compil... |
strtok_sis simply the Windows version ofstrtok_rwhich is standard everywhere else.
One (common I would think) way to make a program portable when it comes to functions likestrtok_s/strtok_ris to use the preprocessor:
```
#if defined(_WIN32) || defined(_WIN64)
/* We are on Windows */
# define strtok_r strtok_s
#endif... |
I have a large code written in C, but I did not write all of it myself. I wish to create an overview of the call structure in the code for reference. That is: I wish to know what (non-standard) functions are called by the different functions in the code, and thus create a hierarchy or a tree of the different functions... |
Doxygen does that too, it has to be enabled though.
|
I am trying to learn C, and I wonder why this doesn't work?
```
#include <stdio.h>
int main(int argc, char *argv[])
{
char testvar[] = argv[0];
//do something with testvar
return 0;
}
```
|
You could do this instead:
```
char *testvar = argv[0];
```
Or maybe:
```
char *testvar = strdup(argv[0]);
/* Remember to free later. */
```
Aspmgnotes,strdupisn't standard. Implementing it using malloc + memcpy is a nice exercise.
Or even:
```
char testvar[LENGTH];
if (strlen(argv[0]) >= LENGTH)
fprintf(std... |
1) Can I create a link list in C with out using pointers (and without using structure) ?
2) Java doesn't use pointers then how linked list are implemented in Java ?
|
I don't see how it would be possible.Java does have pointers. They're just called references in Java, but they're basically the same thing. Every variable pointing to an object is a reference, or pointer, to the object. If the variable is null, and you try to dereference it, you get a NullPointerException.
|
I'm reading an analogue value from a Pin on a µC.
I want to check periodically if the value has changed more thanx.
Here, I am using theabs()function, but I want to keep it simple.
Can you help me?
```
int algVal= 0;
int oldVal = 0
while(1){
algVal = getAlgVal();
if(abs(algVal - oldVal) > x)
{
doStuff(... |
That sounds like a fantastic approach, and would probably be very nice in terms of runtime performance,abs()for integers is cheap. If in doubt, read the generated assembly of course.
|
I have been working on project, to make a website which read files(c/c++ text file) and compile the code written on it.
How can I use compiler which is on my server?
|
If$_POST['CODE']contains the cpp code. You can do the following.
```
$code = do_sanitizing($_POST['CODE']);
$filename = "cfile".time().".c";
// put the contents in a file
file_put_contents($filename, $code);
// compile it
$output = system("/usr/bin/gcc $filename 2>&1");
echo $output;
```
Note:This type of compiling... |
what does the (int *) do in the following code?
```
int *ptr = (int *) malloc(10 * sizeof (int));
```
i'm new to C and i've seen the above code with and without the (int *) so im wondering what it does.
|
That means "cast avoid*pointer into aint*pointer" -malloc()returnsvoid*and you ask the compiler to treat thatvoid*as if it wasint*. This construct aroundmalloc()is only needed in C++ code, and istotally unneeded and even evil in Cbecause it can cause rather subtle yet devastating errors.
|
I just want to know why this piece of code giving me segfault.
```
if(argc < 2){
printf("\n Please mention the file name");
exit(1);
}
FILE* fp;
if((fp = fopen(argv[1],"r")) == NULL){
printf("\n can't open file");
exit(1);
}
char* str;
fgets(str,80,fp);
printf("\n this is the output %s",str);
```
If ... |
You're not allocating any memory; you're just declaring achar *. Eitherchar str[100]will work, or:
```
char *str = malloc(100);
```
That will allocate memory for your string. Otherwise, you're just reading fromfgets()into memory that isn't yours, and causing a segmentation fault.
If you do this, make sure to callfr... |
I want to do hardware interaction using "C" Program. I have heard that using Printer's port I can create a C Program which can control a "Bulb" or "Tube Light" to on or off. Which means if I press any key from my Keyboard ( Suppose "1" ) then Bulb will be on and from another key I want to off it. How can I achieve thi... |
Seehttp://logix4u.net/parallel-port. Since (you say) you’re using Windows 98, theirTutorial on Parallel Port Interfacingwill be directly applicable.
If you want to write programs that can be used on later versions of Windows, see also theirInpout32.dll for Windows 98/2000/NT/XP, which claims to be compatible with th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.