question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
which is the best way to write cust... |
Redis supports 'custom commands' via LUA scripts executed using eval(). Seehttp://redis.io/commands/eval
|
I'm new to shared memory and ive come up with the following code:
```
int main()
{
int perm=S_IRWXU|S_IRWXG|S_IRWXO;
int fd=shmget(IPC_PRIVATE,1024,IPC_CREAT|perm);
if(fd<0)
{
printf("error");
_exit(0);
}
int* sum=(int*)shmat(fd,0,0);
if(*sum==1)
{
printf("error\n");
_exit(0);
}
... |
Assuming the OP's issue occurs on Cygwin, the following paragraph from Cygwin'sImplementation Noteshelps:
The XSI IPC functions semctl, semget, semop, shmat, shmctl, shmdt, shmget, msgctl, msgget, msgrcv and msgsnd are only available when cygserver is running.
|
ARCforbidsObjective-Cobjects instructs orunions.
Unless you add__unsafe_unretainedwhich means its not managed.
I was wonder what people are using in place ofstructs now if anything?
Or are you retaining everything manually?
|
It's very simple - if you want to add an object inside a struct, you are doing it wrong. Whenever you need a struct to hold an obj-c object, convert the struct into an obj-c object.
|
I have a following loop in C:
```
for (i = 0, j = nvert-1; i < nvert; j = i++) {
//do something
}
```
I want to write this loop in python. I know that in Python the loop uses therange(start,end)format, so I think I should make this somehow as follows:
```
for i in range(0,nvert):
for j in range(???):
#d... |
You don't need the second loop. You can simply include it into the loop:
```
j = nvert - 1
for i in range(0, nvert):
# do stuff
j = i
```
notethat you can simply userange(nvert)instead ofrange(0, nvert)
|
During the program compilation there are three main stages:
Preprocessing (all#include,#define, etc. are replaced)Compilation (producing object files)Linking (object files are linked to executable)
My question regards to thetypedef. As I can see in preprocessed file output, thetypedefed typed are not replaced by the... |
As I can see in preprocessed file output, the typedefed typed are not replaced by the actual types.
No, they are not, because they are just an alias of a type.
When it happens? Is it possible to get already replaced types?
That is an implementation detail, but since the typedefs are needed to compile, then it is do... |
The compiler showed the following warnings for the following code segment. Please help me correct it.
if((tmp_n = (struct dot *)shmat(shm_net, NULL, 0)) == (int *) -1) { }warning: comparison of distinct pointer types lacks a cast [enabled by default]
Its a C program, this code segment is for attaching a shared memor... |
Try this one
```
if((tmp_n = (struct dot *)shmat(shm_net, NULL, 0)) == (void *) -1) { }
```
and look at theman-page, it states:
```
Return Value
On success shmat() returns the address of the attached shared memory segment;
on error (void *) -1 is returned, and errno is set to indicate the cause of the error.
```
|
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
I'm just learning about shared memory so far everything I've learnt has confused me.Can some one pleas tell... |
you can use shmat() method to access shared memory,
the shmat() syntex is
```
void *shmat(int shmid, const void *shmaddr, int shmflg);
```
this will return a pointer.
If you want to use it as array then allocate as shown below
```
datatype array[size];
datatype* array = (datatype*)shmat(shmid, NULL, 0);
```
|
(UNIX) I have 2 programs in C in which I use a named pipe (created by mkpipe, fopen etc.) to communicate. There is one writer and multiple readers for that pipe.
Is there any way to set a maximum possible number of readers, in writer's code?
|
No there is no such way to do that.
|
For instance,cublas<t>geam()will do:
But what if I want to store the result inAanyway? Can I call it with pointers*C = *Aso that:
without fear that I may be writing output to a matrix still being read as an input??
If so, are guaranteed that we do this with all other CUBLAS matrix operations safely?
|
The answer is alright in the cublas documentation, as you posted it -cublasgeam()-If C overlaps A or B, then behaviour is undefined.
Nvidia won't guarantee that this will work, ifC == A.
|
this is my demo .
```
#include <stdio.h>
int sqsum(int a, ...)
{
va_list list;
int b = 0,n = a;
va_start(list,a);
while(n > 0)
{
b = b+n*n;
n = va_arg(list,int);
}
va_end(list);
return b;
}
int main(int argc,char **argv)
{
printf("%d\n",sqsum(1,2,3... |
If you did not include#include <stdarg.h>and it does not look like you did, then that would explain the error you are seeing, otherwise the program looks correct. If I do not include that header these are the errors I see usinggcc:
```
In function ‘sqsum’:
13:29: error: expected expression before ‘int’
```
|
Currently I'm coding a python script to compile a C/C++ Linux kernel in the following way:
```
subprocess.check_call(["make", "-j5"])
subprocess.check_call(["make", "-j5", "modules_install"])
subprocess.check_call(["make", "-j5", "install"])
```
With these approach the commands are executed in the shell. So I was wo... |
Ultimately, python isn't a C/C++ compiler, so you need to ship out the compiling to an external program (e.g.gcc). So, there is no way to do thisentirelyin python.
Note that here python doesn't spawn any shells (althoughmakemight). You could try to reproduce whatmakedoes entirely in python, (there is a version of m... |
I'm new on StackOverflow so sorry if this topic was already discussed.
I'm working on a project, and I need to use the minimum amount of memory, so my question is: is it possible to access the adres of node of a structure by having the adress of a field of this structure.
For example I have this structure:
```
typed... |
Consideroffsetof <stddef.h>:
```
typedef struct SLL{
char *name;
int *id;
struct SLL *next;
}SLL;
int main()
{
SLL *p=malloc( sizeof(SLL));
void *id=&p->id;
void *test= id - offsetof(SLL, id);
printf("SLL=%p test=%p\n", p, test);
return 0;
}
```
|
I have a struc called player, and I need to make an array of MAX players, so I based on the following pageC - initialize array of structs, like so:
```
DEFINE MAX 200
typedef struct
{
int ID;
} Player;
Player* PlayerList = malloc(MAX * sizeof(Player));
```
Problem is I keep getting the following error
```
erro... |
You can't callmalloc()from outside of any function. Just declarePlayer* PlayerList;, and let one of the first things you do inmain()bePlayerList = malloc(MAX * sizeof(Player));.
|
Hello I'm trying to do this shell command "rm -rf test" by doing this:
```
#include <stdio.h>
#include <stdlib.h>
char name[] = "test";
char buffer[64];
int main()
{
snprintf(buffer,sizeof(buffer),"rm -rf s% s%", name);
system(buffer);
return 0;
}
```
It will compile and run but doesn't rem... |
Don't usesystemto run external processes, especially if the command line you're passing isn't constant. It will only make your life miserable. Seeman forkandman execfor the right way to do this.
|
For instance,cublas<t>geam()will do:
But what if I want to store the result inAanyway? Can I call it with pointers*C = *Aso that:
without fear that I may be writing output to a matrix still being read as an input??
If so, are guaranteed that we do this with all other CUBLAS matrix operations safely?
|
The answer is alright in the cublas documentation, as you posted it -cublasgeam()-If C overlaps A or B, then behaviour is undefined.
Nvidia won't guarantee that this will work, ifC == A.
|
this is my demo .
```
#include <stdio.h>
int sqsum(int a, ...)
{
va_list list;
int b = 0,n = a;
va_start(list,a);
while(n > 0)
{
b = b+n*n;
n = va_arg(list,int);
}
va_end(list);
return b;
}
int main(int argc,char **argv)
{
printf("%d\n",sqsum(1,2,3... |
If you did not include#include <stdarg.h>and it does not look like you did, then that would explain the error you are seeing, otherwise the program looks correct. If I do not include that header these are the errors I see usinggcc:
```
In function ‘sqsum’:
13:29: error: expected expression before ‘int’
```
|
Currently I'm coding a python script to compile a C/C++ Linux kernel in the following way:
```
subprocess.check_call(["make", "-j5"])
subprocess.check_call(["make", "-j5", "modules_install"])
subprocess.check_call(["make", "-j5", "install"])
```
With these approach the commands are executed in the shell. So I was wo... |
Ultimately, python isn't a C/C++ compiler, so you need to ship out the compiling to an external program (e.g.gcc). So, there is no way to do thisentirelyin python.
Note that here python doesn't spawn any shells (althoughmakemight). You could try to reproduce whatmakedoes entirely in python, (there is a version of m... |
I'm new on StackOverflow so sorry if this topic was already discussed.
I'm working on a project, and I need to use the minimum amount of memory, so my question is: is it possible to access the adres of node of a structure by having the adress of a field of this structure.
For example I have this structure:
```
typed... |
Consideroffsetof <stddef.h>:
```
typedef struct SLL{
char *name;
int *id;
struct SLL *next;
}SLL;
int main()
{
SLL *p=malloc( sizeof(SLL));
void *id=&p->id;
void *test= id - offsetof(SLL, id);
printf("SLL=%p test=%p\n", p, test);
return 0;
}
```
|
I have a struc called player, and I need to make an array of MAX players, so I based on the following pageC - initialize array of structs, like so:
```
DEFINE MAX 200
typedef struct
{
int ID;
} Player;
Player* PlayerList = malloc(MAX * sizeof(Player));
```
Problem is I keep getting the following error
```
erro... |
You can't callmalloc()from outside of any function. Just declarePlayer* PlayerList;, and let one of the first things you do inmain()bePlayerList = malloc(MAX * sizeof(Player));.
|
Hello I'm trying to do this shell command "rm -rf test" by doing this:
```
#include <stdio.h>
#include <stdlib.h>
char name[] = "test";
char buffer[64];
int main()
{
snprintf(buffer,sizeof(buffer),"rm -rf s% s%", name);
system(buffer);
return 0;
}
```
It will compile and run but doesn't rem... |
Don't usesystemto run external processes, especially if the command line you're passing isn't constant. It will only make your life miserable. Seeman forkandman execfor the right way to do this.
|
The prefix header functionality in Xcode comes in handy quite often and I was wondering if other IDEs provide a similar functionality? Or is there even a way on compiler level?
I've been looking for this in other environments for quite a time and the only thing I could find were precompiled headers. But that's not re... |
For VC++ you can specifyForced Include Fileusing option /FI on command line or through an IDE. An excerpt fromMSDN:
To set this compiler option in the Visual Studio development
environment:1. Open the project's Property Pages dialog box.
2. Click the C/C++ folder.3. Click the Advanced property page.4. Modify... |
I'm using Microsoft Visual Studio 2010. It was going fine until this morning when I try to build my code. It gave me this weird error:
```
C:\Program Files
(x86)\MSBuild\Microsoft.Cpp\v4.0\Platforms
\Win32\Microsoft.Cpp.Win32.Targets(147,5)
:error` MSB6006: "CL.exe" exited with code 1073741855.
```
I have no idea w... |
1073741855 is 0x0x4000001f, and 0x1f is decimal 31, and 31 isERROR_GEN_FAILURE. In other words, something is hosed and VS isn't going to tell you what it is.
Go toControl Panel/Programs and Features, right click,Uninstall/Change,Repair/Reinstall. If that doesn't fix the problem, I would uninstall VS completely and ... |
I'm using the following program, and I've suid-ed it (by runningchown root XXX; chmod 4755 XXXas root), but the output is stillruid 1000, euid 1000, suid 1000, shouldn't effect uid be zero here?
```
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
int main()
{
uid_t ruid, euid, suid;
if (! ... |
Please check themountcommand output, your file system could be mounted withnosuidoption.
From mount man page
nosuid: Do not allow set-user-identifier or set-group-identifier bits
to take effect.
|
I have a working insertion sort algorithm that sorts integers stored in an array. In a different program I have created a struct with words and a count. I need to sort structs stored in an array alphabetically using the same insertion sort. I understand how to compare them, however I cannot find a way to swap them.... |
You can swapstructs the same way that you swap integers:
```
wordType tmp;
wordType a = {.word="hello", .count=5};
wordType b = {.word="world", .count=11};
tmp = a;
a = b;
b = tmp;
```
Demo on ideone.
|
I'm trying to write a program in C which is a basic simulation of a CPU scheduler.
There will be 10 processes (represented by structs) that will be moved from a CPU queue to the I/O queue and so on.
I initially began to declare the process structs as an array, but it seems cumbersome to me to move the structs strai... |
An array of struct pointers would work nicely for your purposes. The pointers can be moved in the queue at very little expense and all references will update the same object instead of having to worry about copy semantics.
|
When I run my ddd, it doesn't display the source code. The source window is blank. The execution is still there for example I can step through the program but there is no visual indication where in the code the execution is happening.
How can I fix this?
I run it using this command in xterm:
```
ddd mycode
```
Als... |
You should check whether the program has been compiled with debugging information.
For example, if you're using g++ you should include the -g option.
|
could anybody explain me how to read DWORD ,WORD ,BYTE in C from specific address in memory?for example, base address that is returned using MapViewOfFile() function,how can I read a consecutive BYTE,WORD, or DWORD using C ?Thanks.
|
MapViewOfFile()returnsLPVOIDwhich is a typedef ofvoid*. You'll need a cast.
The easiest thing to do would be to read a byte at a time. You don't specify if there's any kind of performance requirement here (nor do you specify your platform, arch, etc), so I'll assume a "byte at a time" is ok.
Note: WORD is defined as... |
When I run my ddd, it doesn't display the source code. The source window is blank. The execution is still there for example I can step through the program but there is no visual indication where in the code the execution is happening.
How can I fix this?
I run it using this command in xterm:
```
ddd mycode
```
Als... |
You should check whether the program has been compiled with debugging information.
For example, if you're using g++ you should include the -g option.
|
could anybody explain me how to read DWORD ,WORD ,BYTE in C from specific address in memory?for example, base address that is returned using MapViewOfFile() function,how can I read a consecutive BYTE,WORD, or DWORD using C ?Thanks.
|
MapViewOfFile()returnsLPVOIDwhich is a typedef ofvoid*. You'll need a cast.
The easiest thing to do would be to read a byte at a time. You don't specify if there's any kind of performance requirement here (nor do you specify your platform, arch, etc), so I'll assume a "byte at a time" is ok.
Note: WORD is defined as... |
I am trying to run a main method in C but am having trouble. here is what I have
```
int main(int argc, char *argv[])
{
if(argc == 0)
return 0;
printf("%s \n", argv[0]);
main(--argc,++argv);
}
```
in command I write this, ./main roses are red!
But it does not run, I am sure it will print this on... |
The output that you are seeing doesnotseem correct to me.
So, let's attempt to run your code.
```
[12:21pm][wlynch@watermelon /tmp] ./foo
./foo
[12:21pm][wlynch@watermelon /tmp] ./foo roses are red
./foo
roses
are
red
[12:21pm][wlynch@watermelon /tmp] ./foo "roses are red"
./foo
roses are red
```
|
My question is related to the syntax used in plain C to address an entire row from a 2-dimensional array. So, if I have a 2d array like:
```
arr[rows][columns]
```
and I want to pass the address of an entire row from this array to a given function f, would a construction like:
```
f(&arr[i])
```
be okay in plain C... |
```
int arr[rows][columns];
void f(int *array) {
int i;
for (i=0;i<columns; i++) {
array[i] = 5 ; // as example
........
}
}
```
and then you can called as mentioned in your question
```
f(&arr[i]);
```
|
I am trying to compileModel 5.0under OS X 10.8.3
I am getting a lot of warnings and errors while compiling. Several of those error are something like
```
xwin.c:31523:2: error: non-void function 'scrfrg' should return a value
[-Wreturn-type]
return;
```
What flag in C/C++ checks that? I want to disable... |
As per the link you posted, seems you're using gcc. You can disable a lot of error/warning checks with a-Wno-xxxxflag, in your case-Wreturn-typeis causing an error so you can disable it with:
-Wno-return-type
Frankly, it's better to just fix the errors/warnings when you can, and that one seems easy to fix.
|
Consider the following code snippet
```
double id = ?;
double res;
long unsigned *res_u = (long unsigned*)&res;
long unsigned i;
for (i = 0; i < (long unsigned)-1; i++){
double *d1 = (double*)&i;
res = id + *d1;
assert(*res_u == i);
}
```
My question: Is there a value forid, so that the assertion holds ... |
-0.is paradoxically the floating-point value that serves as neutral for addition.
+0.nearly is, but-0. + (+0.)makes+0..
Apart from that,+inf + (-0.)makes+inf,-inf + (-0.)makes-inf, andNaN + (-0.)makesNaN.
|
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... |
It's called shared memory. On Windows, it's implemented via CreateFileMapping()/OpenFileMapping() and MapViewOfFile() API functions.
|
Consider the following code snippet
```
double id = ?;
double res;
long unsigned *res_u = (long unsigned*)&res;
long unsigned i;
for (i = 0; i < (long unsigned)-1; i++){
double *d1 = (double*)&i;
res = id + *d1;
assert(*res_u == i);
}
```
My question: Is there a value forid, so that the assertion holds ... |
-0.is paradoxically the floating-point value that serves as neutral for addition.
+0.nearly is, but-0. + (+0.)makes+0..
Apart from that,+inf + (-0.)makes+inf,-inf + (-0.)makes-inf, andNaN + (-0.)makesNaN.
|
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... |
It's called shared memory. On Windows, it's implemented via CreateFileMapping()/OpenFileMapping() and MapViewOfFile() API functions.
|
I'd like to know if it is somehow possible to runsystem("pwd")on the current DIR. So for example let's have this folder structure:
```
example
>test
>>file
>test2
>>file3
>>file4
```
And withopendir()andreaddir()I'll get tofile3, and I want to usesystem("pwd")to get the path..../example/test2/file3. Is this... |
Simply opening and reading directories does not change the current working directory. However, changing directory in your program will.
for reference,
```
#include <unistd.h>
#include <stdio.h>
int main() {
char cwd[1024];
chdir("/path/to/change/directory/to");
getcwd(cwd, sizeof(cwd));
printf("Curr... |
When i use curl_easy_perform in my c program it somehow stops a timer I have for checking something else.
this is my code:
```
curl_easy_setopt(curl, CURLOPT_URL, query.c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, changeddata.c_str());
result = curl_ea... |
Without more info, I am going to guess that curl_easy_perform() is resulting in a signal, which messes up your timer. Try adding this before calling curl_easy_perform():
```
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);
```
This tells curl not to use any functions that install signal handlers or cause signals to be s... |
I've recently started about thinking about making a 2D game engine in C# from scratch.
Now, I've wondered: In java, I'd use the java.awt.Graphics2d and java.awt.Container classes.
What would you suggest me to use in C#?
Apparently, google couldn't help me with that one.
|
In .NET you could useWindows Presentation Foundation, it offers a great lot of graphic-manipulation. But if it fits to create a game-engine, I am not sure.SeeMSDNfor an overview.
Though, if you really want to have power, you should stick withDirectXand C++.
Note: there isFNAandMonoGame(both reimplementations of the ... |
I was playing with the Cygwin GCC, where I wanted to print the current directory path using glib'sg_get_current_dirin Windows and as well as in Linux. The problem is that the app is printing the path always in posix format in windows. But I wanted it to print in dos format in windows and posix format in linux. How wou... |
You can do that with thecygwin_conv_pathfunction, documented in theCygwin API Reference.
|
I am following a tutorialhere, to add a horizontal scrollbar to a list control. Everything there works except the TextWidth() function (VC++ 2012 says it's undefined) so I foundthisquestion. But I have no idea how to initialize a hdc, so I triedthis. But GetTextExtentPoint32 keeps returning zero.
Any idea how I can s... |
My way:
```
SIZE sz;
HFONT font = GetFont(); //GetFont() is part of WTL. If using raw WinAPI it needs to get font in other means.
HDC hdc = GetDC(NULL);
SelectObject(hdc, font); //attach font to hdc
GetTextExtentPoint32(hdc, text, lstrlenW(text), &sz);
ReleaseDC(NULL, hdc);
```
|
I'm using Microchip's XC8 compiler. They want me to#include <xc.h>instead of including a chip-specific header. However, when I add this code on the first line of my code, I'm getting the error:
```
Error [224] C:\...\main.c; 1.4 illegal "#" directive
```
When I place a line feed before the directive, I don't get the... |
One thing that may cause this is corruption or other characters at the start of the file that aren't visible within your text editor. Depending on the editor it may well be thebyte order markthat is used with Unicode files. I suggest taking a look at the first few lines of the file with ahex editorso that you can loca... |
I tried to call from a lua script the c method my_sin. I'm using lua 5.2.2 and wanted to test to use luaL_newlib instead of lua_register. Unfortunately, the lua script doesn't find mysin.
```
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
#include <cmath>
static int my_sin (lua_State *L) {... |
luaL_newlib creates a new table and populates it from a list of functions. Your function mysin is inside this table and is not a global function. If you want it to be a global function, use lua_register.
|
I am using C.
Say I have a pointer to a integer called *myptr
int *myptr;
What would then be the difference between:
```
*myptr++
```
and...
```
*(myptr++)
```
Thanks
Dan
|
Since++has higher precedence than*, there isno differencebetween the two.
|
With this code:
```
int a = 10;
int *ap = 4;
printf("%d", ap);
```
What is happening when I initialize the int pointer ap with 4?
Why does
```
printf("%d", ap);
```
work, but
```
printf("%d", *ap);
```
throws an error?
|
That's because4is not a valid memory address(in your environment). If you try to dereference a pointer that has an invalid memory address you get an error. You should initialize it with a proper memory address
```
int a = 4;
int *ap = &a;
printf("%d", *ap);
```
or
```
int *ap = malloc(sizeof(int));
*ap = 4;
print... |
I was looking at the runtime.c file in the go runtime at
```
/usr/local/go/src/pkg/runtime
```
and saw the following function definitions:
```
void
runtime∕pprof·runtime_cyclesPerSecond(int64 res)
{...}
```
and
```
int64
runtime·tickspersecond(void)
{...}
```
and there are a lot of declarations like
```
v... |
It's Go's special internal syntax for Go package paths. For example,
runtime∕pprof·runtime_cyclesPerSecond
is functionruntime_cyclesPerSecondin package pathruntime∕pprof.
The '∕' character is the Unicode division slash character, which separates path elements. The '·' character is the Unicode middle dot character, ... |
I've recently started about thinking about making a 2D game engine in C# from scratch.
Now, I've wondered: In java, I'd use the java.awt.Graphics2d and java.awt.Container classes.
What would you suggest me to use in C#?
Apparently, google couldn't help me with that one.
|
In .NET you could useWindows Presentation Foundation, it offers a great lot of graphic-manipulation. But if it fits to create a game-engine, I am not sure.SeeMSDNfor an overview.
Though, if you really want to have power, you should stick withDirectXand C++.
Note: there isFNAandMonoGame(both reimplementations of the ... |
I was playing with the Cygwin GCC, where I wanted to print the current directory path using glib'sg_get_current_dirin Windows and as well as in Linux. The problem is that the app is printing the path always in posix format in windows. But I wanted it to print in dos format in windows and posix format in linux. How wou... |
You can do that with thecygwin_conv_pathfunction, documented in theCygwin API Reference.
|
I am following a tutorialhere, to add a horizontal scrollbar to a list control. Everything there works except the TextWidth() function (VC++ 2012 says it's undefined) so I foundthisquestion. But I have no idea how to initialize a hdc, so I triedthis. But GetTextExtentPoint32 keeps returning zero.
Any idea how I can s... |
My way:
```
SIZE sz;
HFONT font = GetFont(); //GetFont() is part of WTL. If using raw WinAPI it needs to get font in other means.
HDC hdc = GetDC(NULL);
SelectObject(hdc, font); //attach font to hdc
GetTextExtentPoint32(hdc, text, lstrlenW(text), &sz);
ReleaseDC(NULL, hdc);
```
|
I'm using Microchip's XC8 compiler. They want me to#include <xc.h>instead of including a chip-specific header. However, when I add this code on the first line of my code, I'm getting the error:
```
Error [224] C:\...\main.c; 1.4 illegal "#" directive
```
When I place a line feed before the directive, I don't get the... |
One thing that may cause this is corruption or other characters at the start of the file that aren't visible within your text editor. Depending on the editor it may well be thebyte order markthat is used with Unicode files. I suggest taking a look at the first few lines of the file with ahex editorso that you can loca... |
I tried to call from a lua script the c method my_sin. I'm using lua 5.2.2 and wanted to test to use luaL_newlib instead of lua_register. Unfortunately, the lua script doesn't find mysin.
```
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
#include <cmath>
static int my_sin (lua_State *L) {... |
luaL_newlib creates a new table and populates it from a list of functions. Your function mysin is inside this table and is not a global function. If you want it to be a global function, use lua_register.
|
I am using C.
Say I have a pointer to a integer called *myptr
int *myptr;
What would then be the difference between:
```
*myptr++
```
and...
```
*(myptr++)
```
Thanks
Dan
|
Since++has higher precedence than*, there isno differencebetween the two.
|
With this code:
```
int a = 10;
int *ap = 4;
printf("%d", ap);
```
What is happening when I initialize the int pointer ap with 4?
Why does
```
printf("%d", ap);
```
work, but
```
printf("%d", *ap);
```
throws an error?
|
That's because4is not a valid memory address(in your environment). If you try to dereference a pointer that has an invalid memory address you get an error. You should initialize it with a proper memory address
```
int a = 4;
int *ap = &a;
printf("%d", *ap);
```
or
```
int *ap = malloc(sizeof(int));
*ap = 4;
print... |
I was looking at the runtime.c file in the go runtime at
```
/usr/local/go/src/pkg/runtime
```
and saw the following function definitions:
```
void
runtime∕pprof·runtime_cyclesPerSecond(int64 res)
{...}
```
and
```
int64
runtime·tickspersecond(void)
{...}
```
and there are a lot of declarations like
```
v... |
It's Go's special internal syntax for Go package paths. For example,
runtime∕pprof·runtime_cyclesPerSecond
is functionruntime_cyclesPerSecondin package pathruntime∕pprof.
The '∕' character is the Unicode division slash character, which separates path elements. The '·' character is the Unicode middle dot character, ... |
I was wondering if there was an alternative to OutputDebugString but for floats instead? As I want to be able to view in the output in Visual studio the values.
|
First convert your float to a string
```
std::ostringstream ss;
ss << 2.5;
std::string s(ss.str());
```
Then print your newly made string with this
```
OutputDebugString(s.c_str());
```
Optionaly you can skip the intermediate string with
```
OutputDebugString(ss.str().c_str());
```
|
I have the following prog written:
```
int main()
{
printf("one\n");
write(1, "two\n", 4);
return 0;
}
```
And then i give the command
./a.out | cat
at the terminal to which the output comes to be
two
one
instead of
one
two
Why???
|
That's becauseprintf's output will get buffered by thelibc,write's output will not get buffered. It's adirect, unbuffered operation on afile(stdout)
Readthis:
if stdout is a terminal then buffering is automatically set to line buffered, else it is set to buffered
So, you are actually piping tocat- that's why buffer... |
I currently usegcc 4.6.3. My understanding is thatgccby default uses thegnu89standard and I would like to enable C11, the latest C standard. I tried:
```
[pauldb@pauldb-laptop test ]$ gcc -std=c11 -o test test.c
cc1: error: unrecognised command line option ‘-std=c11’
```
I replacedc11withgnu11and I get the same erro... |
The correct option is-std=c11.
However, it is not available ingcc 4.6. You need at leastgcc 4.7to have this option supported. In some older versions likegcc 4.6, the option-std=c1xwas available with experimental (i.e., very limited) support of C11.
Note that the current version ofgccisgcc 8.2.
|
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... |
If it is still relevant there are numerous products that can fuzz network products, from open source tools like SPIKE and Peach to commercial fuzzers like beSTORM
|
This is my code:
```
#include<stdio.h>
struct p{
char* d;
};
typedef struct p* pt;
int main(){
pt opt;
opt=(pt)malloc(sizeof(struct p));
scanf("%s",(opt->d));
printf("%s",opt->d);
getch();
return 0;
}
```
Everytim... |
You usedmallocto allocate space for your structure, but not for the string you want to read in. You need to do that too. Here's an example paraphrased from your question:
```
pt opt = malloc(sizeof(struct p));
opt->d = malloc(MAX_STRING_LENGTH);
```
|
Something like this:
```
/*Simple program to calculate the circumference of a circle. */
#include <stdio.h>
#define PI 3.14159
int main()
{
float r1 /*R1 being the radius.*/
/* Since the Circumference is R * PI * 2, or R2 * PI */
/* we do the following */
printf("This is a program that calculates the ... |
0 is equivalent to FALSE. Anything else is TRUE.
|
I have got a function which I need to pass a value to for read-only purposes only.
For example:
```
unsigned short strlen(String str)
{
short i = 0;
while(str[i] != '\0')
i++;
return i;
}
```
As you can see, I do not want to change the original value I work with, I only need to read its length. Would it -... |
Would it - in terms of performance - be better to replace the parameter String str, which is making a copy of the original variable, by a reference like String &str?
Yes, it would. Instead of creating a copy, which you do not seem to need here, a reference would be bound. Since you are not modifying the object, a ref... |
I want to measure the execution time of a c-code segment using Linux.
I take one timestamps at the beginning of the code segment and one at the end.
But I don't know how to protect the code against IRQs and context switches to high prior tasks. The program runs in user space!
The code segment is short so don't panic h... |
You can usegetrusage(2)to get the CPU time used, rather than just measuring real time. That should get you the answer you want without having to resort to funny business like blocking other programs from running.
|
I am writing some C code on Linux. I want to loop through the *argv[] parameter being passed to main, but I don't know how to stop before getting a seg fault.
```
i = 0;
while (i < sizeof(argv)) {
printf("%s\n", argv[i]);
i ++;
}
```
This produces a seg fault because sizeof always returns 8. How do I g... |
The first argument..argcshould already have the CLI argument count.. Any reason why that isn't used?
```
int main(int argc, char** argv)
{
if(argc > 1)
}
```
|
Can one sayVariables and constants are objects of data types?
I wonder what would be the proper explanation for this
```
int a;
float f;
```
Here, Can we sayais an object of typeintandfis an object of typefloat?
|
Yes
Per paragraph §1.8, bothaandbare objects of their corresponding types.
1An object is a region of storage.[Note: A function is not an object,
regardless of whether or not it occupies storage in the way that
objects do. —end note ] An object is created by a definition (3.1), by
a new-expression (5.3.4) or by... |
i want to find LCM of more than two numbers
C++ Program for Finding LCM of given N number
|
```
int lcm(int a, int b) { return (a/gcd(a,b))*b; }
```
Forgcdlook atEuclid algorithm.
For more than 2 numbers uselcmiteratively on the next number and the result of the previous. In code:
```
int lcms(int l int * a)
{
int i, result;
result = 1;
for (i = 0; i < l; i++) result = lcm(resul... |
I am executing::system("del *.log")in a win32 exe
The above code prints the output to exe console.
How can i suppress the output being printed to console?
|
Use redirection and redirect stdout to the nul file:
```
::system("del *.log > nul")
```
"nul" is a hidden file present in all directories, and all it does is discard everything written to it.
This will still show errors (if there are any). If you also want to suppress stderr, then:
```
::system("del *.log > nul 2... |
```
void print_task(void)
{
for(;;)
{
taskLock();
printf("this is task %d\n", taskIdSelf());
taskUnlock();
taskDelay(0);
}
}
void print_test(void)
{
taskSpawn("t1", 100,0,0x10000, (FUNCPTR)print_task, 0,0,0,0,0,0,0,0,0,0);
taskSpawn("t2", 100,0,0x10000, (FUNCPTR)prin... |
The problem lies in taskLock();
Try semaphore or mutex instead.
|
I was looking at some of the solutions in Google Code Jam and some people used this things that I had never seen before. For example,
```
2LL*r+1LL
```
What does 2LL and 1LL mean?
Their includes look like this:
```
#include <math.h>
#include <algorithm>
#define _USE_MATH_DEFINES
```
or
```
#include <cmath>
```
|
TheLLmakes the integer literal of typelong long.
So2LL, is a 2 of typelong long.
Without theLL, the literal would only be of typeint.
This matters when you're doing stuff like this:
```
1 << 40
1LL << 40
```
With just the literal1, (assumingintto be 32-bits, you shift beyond the size of the integer type -> unde... |
I am in a coding environment where I only have access to some most basic c functions. #include'ing other lib is not feasible.
In this environment, I can call rand() which gives me a random number between 0 to 32767 inclusively(I think) in my environment. Is the following code the right logic to get a larger random n... |
rnum = (rand() << 15) | rand()might be faster, but if you need good quality random numbers you should look for an external library. Built-in random functions are generally adequate only for the simplest applications.
|
In windows I can callLogonUserWor on linuxpam_authenticateto check whether a given username/password is correct. How do I do this on OS X (for c/c++)?
|
Take a look atthis:
PAM is a pluggable authentication and authorization library for *nix
based systems – think Linux, FreeBSD and evenMac OS X....
|
This question already has answers here:What happens to a declared, uninitialized variable in C? Does it have a value?(9 answers)Closed10 years ago.
Here is the code.
```
int main(int argc, char *argv[])
{
char name[5];
printf("%s\n",name);
system("PAUSE");
return 1;
}
```
The printf function outpu... |
tl;dr: the value is undetermined.
Depending on the compiler, the value of the array is undetermined (most cases) or zero (some specific compilers that clean the stack).
Most often, the array is simply some memory space that is taken from the stack, so depending on what this area of memory was before you used it, you... |
I have a problem with strtok() - it does not return the input as expected.
```
void parse_input(const char *input,unsigned char *ctext, int mlen){
char * str = strdup(input);
char * pch = strtok(str,"-");
while (pch != NULL)
{
ctext[mlen] = (int) pch;
pch = strtok (NULL, "-");
mlen++;
}
``... |
```
ctext[mlen] = (int) pch;
```
That stores the numeric value of the pointer, whereas you really want thecharacter pointed to by the pointer.Time to read a good article/book/tutorial on pointers.
```
ctext[mlen] = *pch;
```
is what you're looking for.
|
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... |
Compilers Principles,Techniques and Tools By A.V Aho,Ravi Sethi and J.D.Ullman - Pearson Education. First Refer old edition then jump on to new one
This is best and must read book for Compilers
|
I am trying to open and read 4 MB bin file,
but I couldn't usefreadto read more than ~700 KB.
Actually I want to open and read genesis ROM file
which is binary format that reading should be from beginning to the last byte.
When trying to read over that amount, error occurs at run time, program stops and closes.
My c... |
Please do the read operation in a loop for a particular chunk size.
|
This is more just a question of interest - I'm not sure how it would actually be applicable. Anyways - is it possible using bit-checks to see if a number is equal to 1?
|
I am not sure what exactly the questions is, but you can use either!(x ^ 1)orx == 1or!(x-1)or(x & 1) && !(x & ~1)or one of many other ways.
|
Can someone please tell me if it is acceptable to use same goto labels in different functions in the same C file?
To explain what I am facing:
```
function1()
{
...
goto label
...
label:
...
}
function2()
{
...
goto label;
...
label:
...
}
```
Now whats happening is that the co... |
Labels are local, so you can use the same label in multiple functions.
The question about if you should usegotois a different matter though, and one that is not easily answered. In short, don't usegoto. But as with everything (especially when it comes to programming) there are exceptions wheregotomay be useful.
|
I have this little Program:
```
#import <stdio.h>
#import <stdlib.h>
void main(void) {
char a;
char b;
printf("Adress a: %p\n", (void *)&a);
printf("Adress b: %p\n", (void *)&b);
return 0;
}
```
The adress of b is lower, than the adress of b. Why is it like this? Or am i doing something wrong... |
The storage space for a local variable is on the stack. The X86 processor family has a stack which "grows downward". This means that as allocations occur (for example assigning a variable), the stack pointer is moved downwards toward lower memory addresses.
&ais greater than&bbecause after&awas assigned, the stack po... |
I need to reassign a single file pointer to multiple files sequentially.
I have the file paths correctly in a string path.
when i pass the path and the file pointer to a function to reassign, I get "Aborted (core dumped)"..
```
FILE * fptr; //Global file pointer
FILE * getfptrr(char * path)
{
fclose(fpt... |
You do not check that thefptris notNULLbefore you callfclose.
InitializefptrtoNULLin the definition, and then check that it's notNULLbefore callingfclose(orfreopenwhich is actually what you're doing here).
|
Something like dladdr that gives me a dynamic library handle to the shared object or a way to get the handle from the shared object's base address. The file containing the shared object may have been moved or deleted so no, I can't dlopen() the filename given by dladdr.
|
glibc's dlopen handles are based on link_map. I can iterate all link_map's and see if one has l_addr equal to the one given by dladdr. The address of that link_map is the handle.
dietlibc also uses link_map's as handles.
In the case of uClibc there is another struct - dyn_elf. It contains a pointer to a link_map. Th... |
I've been trying to concatenate 4 hex numbers and can't seem to do it.
Example:
```
int a = 0x01;
int b = 0x00;
int c = 0x20;
int d = 0xF1;
//Result should be 0x010020F1
```
The results that I am getting usingsprintf()and bitwise operations always have cut off zeros, giving me answers like 1020F1, which is much dif... |
Supposingunsigned int a,b,c,d;
```
unsigned int result = (a<<24) | (b<<16)| (c<<8) | d;
```
But this is essentially implementation dependent since C++ standard only specifies minimal sizes of integers.
So foruint32_t a, b, c, d:
```
uint32_t result = (a<<24) | (b<<16)| (c<<8) | d;
```
|
I know that execlp replaces the current process.I am trying to run
```
execlp("mpg123", "mpg123", "-q", "1.mp3", 0);
```
Is there any way i can keep the program running while execlp executes?
|
Youforka new process, and do theexeccall in the child process:
```
pid_t child_pid = fork();
if (child_pid == -1)
perror("fork");
else if (child_pid == 0)
{
/* In child process, call `exec*` */
}
else
{
/* In parent process, continue doing... things... */
}
```
|
I am making structs of pointers which point to structs. I've been googling like a madman and I can't figure out why the printf statement below gives different memory addresses. Could somebody explain this to me?
```
struct board_piece {
board_piece* next;
board_piece* prev;
} board_piece;
main (int argc, char ... |
Try using%pas your format specifier. You might be on a platform where pointers and integers are different sizes.
|
Is it possible in Eclipse CDT to do a search on a variable name and only show results where a variable is modified or potentially modified? For example, the variable appears on the left-hand side of an assignment.
If not, is there some other utility that can parse code to produce this result?
|
Right-click the variable name, and choose "Open Call Hierarchy".
It can be picky; you might need to left-click it first to make it highlighted before right-clicking.
|
I am trying to open and read 4 MB bin file,
but I couldn't usefreadto read more than ~700 KB.
Actually I want to open and read genesis ROM file
which is binary format that reading should be from beginning to the last byte.
When trying to read over that amount, error occurs at run time, program stops and closes.
My c... |
Please do the read operation in a loop for a particular chunk size.
|
This is more just a question of interest - I'm not sure how it would actually be applicable. Anyways - is it possible using bit-checks to see if a number is equal to 1?
|
I am not sure what exactly the questions is, but you can use either!(x ^ 1)orx == 1or!(x-1)or(x & 1) && !(x & ~1)or one of many other ways.
|
Can someone please tell me if it is acceptable to use same goto labels in different functions in the same C file?
To explain what I am facing:
```
function1()
{
...
goto label
...
label:
...
}
function2()
{
...
goto label;
...
label:
...
}
```
Now whats happening is that the co... |
Labels are local, so you can use the same label in multiple functions.
The question about if you should usegotois a different matter though, and one that is not easily answered. In short, don't usegoto. But as with everything (especially when it comes to programming) there are exceptions wheregotomay be useful.
|
I have this little Program:
```
#import <stdio.h>
#import <stdlib.h>
void main(void) {
char a;
char b;
printf("Adress a: %p\n", (void *)&a);
printf("Adress b: %p\n", (void *)&b);
return 0;
}
```
The adress of b is lower, than the adress of b. Why is it like this? Or am i doing something wrong... |
The storage space for a local variable is on the stack. The X86 processor family has a stack which "grows downward". This means that as allocations occur (for example assigning a variable), the stack pointer is moved downwards toward lower memory addresses.
&ais greater than&bbecause after&awas assigned, the stack po... |
I need to reassign a single file pointer to multiple files sequentially.
I have the file paths correctly in a string path.
when i pass the path and the file pointer to a function to reassign, I get "Aborted (core dumped)"..
```
FILE * fptr; //Global file pointer
FILE * getfptrr(char * path)
{
fclose(fpt... |
You do not check that thefptris notNULLbefore you callfclose.
InitializefptrtoNULLin the definition, and then check that it's notNULLbefore callingfclose(orfreopenwhich is actually what you're doing here).
|
Something like dladdr that gives me a dynamic library handle to the shared object or a way to get the handle from the shared object's base address. The file containing the shared object may have been moved or deleted so no, I can't dlopen() the filename given by dladdr.
|
glibc's dlopen handles are based on link_map. I can iterate all link_map's and see if one has l_addr equal to the one given by dladdr. The address of that link_map is the handle.
dietlibc also uses link_map's as handles.
In the case of uClibc there is another struct - dyn_elf. It contains a pointer to a link_map. Th... |
I've been trying to concatenate 4 hex numbers and can't seem to do it.
Example:
```
int a = 0x01;
int b = 0x00;
int c = 0x20;
int d = 0xF1;
//Result should be 0x010020F1
```
The results that I am getting usingsprintf()and bitwise operations always have cut off zeros, giving me answers like 1020F1, which is much dif... |
Supposingunsigned int a,b,c,d;
```
unsigned int result = (a<<24) | (b<<16)| (c<<8) | d;
```
But this is essentially implementation dependent since C++ standard only specifies minimal sizes of integers.
So foruint32_t a, b, c, d:
```
uint32_t result = (a<<24) | (b<<16)| (c<<8) | d;
```
|
I know that execlp replaces the current process.I am trying to run
```
execlp("mpg123", "mpg123", "-q", "1.mp3", 0);
```
Is there any way i can keep the program running while execlp executes?
|
Youforka new process, and do theexeccall in the child process:
```
pid_t child_pid = fork();
if (child_pid == -1)
perror("fork");
else if (child_pid == 0)
{
/* In child process, call `exec*` */
}
else
{
/* In parent process, continue doing... things... */
}
```
|
I am making structs of pointers which point to structs. I've been googling like a madman and I can't figure out why the printf statement below gives different memory addresses. Could somebody explain this to me?
```
struct board_piece {
board_piece* next;
board_piece* prev;
} board_piece;
main (int argc, char ... |
Try using%pas your format specifier. You might be on a platform where pointers and integers are different sizes.
|
Is it possible in Eclipse CDT to do a search on a variable name and only show results where a variable is modified or potentially modified? For example, the variable appears on the left-hand side of an assignment.
If not, is there some other utility that can parse code to produce this result?
|
Right-click the variable name, and choose "Open Call Hierarchy".
It can be picky; you might need to left-click it first to make it highlighted before right-clicking.
|
I am using DLL Import to use some functionality in a C dll. The signature of the function is
```
int dllfunction(myfile **fptr, const char *filename, int *status);
```
What marshalling code goes into the line below so I can access the function?
```
[DllImport("name.dll")]
public static extern int dllfunction(??);
`... |
This is the best guess with what little info was posted:
```
[DllImport("name.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int dllfunction(
out IntPtr fptr,
string filename,
ref int status
);
```
|
I have read strings with spaces in them using the followingscanf()statement.
```
scanf("%[^\n]", &stringVariableName);
```
What is the meaning of the control string[^\n]?
Is is okay way to read strings with white space like this?
|
This mean "read anything until you find a '\n'"
This is OK, but would be better to do this "read anything until you find a '\n', or read more characters than my buffer support"
```
char stringVariableName[256] = {}
if (scanf("%255[^\n]", stringVariableName) == 1)
...
```
Edit: removed & from the argument, and c... |
I am creating an alarm clock for my project in C. I am using mgp123 command(in package mpg321) to run the alarm sound. It is only for UBUNTU users.I need the program to check whether mpg321 is installed or not. How can i find using C if the package mpg321 is installed using C program?
|
you can usesystem()
```
system("mpg321 -h");
```
if the command return error than thempg321is not installed
|
I'm trying to read a string
```
char *string=malloc(sizeof(char));
char *start_string=string; //pointer to string start
while ((readch=read(file, buffer, 4000))!=0){ // read
filelen=filelen+readch; //string length
for (d=0;d<readch;d++)
*start_string++=buffer[d]; //append buffer to str
realloc(str... |
realloc()does not update the pointer passed in to it. Ifrealloc()is successful the pointer passed in isfree()d and the address of the allocated memory is returned. In the posted coderealloc()will attempt tofree(string)multiple times, which is undefined behaviour.
Store the result ofrealloc():
```
char* t = realloc(s... |
I have shared library file (libmylib.so), but have no header file (mylib.h) for it.
Do you know some ways/tools to generate this header file from shared library file?
|
This is impossible in general, since the .so file does not contain enough information about the parameter lists - especially if non-standard types (structs, e.g.) are being used, since type information is not part of the .so file.
Even if only standard types are used, the argument list is not part of the ELF symbol t... |
So here's my code.
```
#include<stdio.h>
int main()
{
int a[4]={6,2,7,3};
sort(a,4);
int i;
for(i=0;i<4;i++)
printf("%d",a[i]);
}
int sort(int a[],int n)
{
int i,j,temp;
for (i=0; i< (n -1); i++)
{
for(j = (i+1); j < n; j++)
{
if (a[i]< a[j])
{
temp= a[i];
a[i... |
You are passing a pointer; arrays in function declarations decay to a pointer to their first element.
|
I want to translate my GTK+ application written in C++. I don not have any ideas where to start, I heard about gettext(), but I don't know, how should I use it.
|
Take a look athttps://developer.gnome.org/gtk3/stable/gtk-question-index.htmlpage, in 1.7. paragraph they explain how you can translate your applications usingGNU gettext.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.