question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
When I attempt to#include "postgres.h", I get this errorIntelliSense: cannot open source file "postgres.h".
I have attempted to add to the Include Directories by adding this to the end of the field:$(pathContainingHeaderFile). The error remains when attempting to#include "postgres.h"
If I#include "pathContainingHead... |
You should just append; pathContainingHeaderFileto the Include Directories i.e. omit the$(and)parts. Remove giving the path in the#includeline and it should work fine.
|
This question already has answers here:What are scanf("%*s") and scanf("%*d") format identifiers?(5 answers)Closed9 years ago.
I have a gotten a C program, where one of the line having:
```
scanf("%d%*c%d", &x, &y);
```
What is the meaning of%*c?
|
scanf reads data from stdin and then it stores that data into the parameters pointed according to the format (in your case the parameters are&xand&y).
*indicates that the data is to be read from the stream but ignored (i.e. it is not stored in the location pointed by an parameter).
In your case%*cmeans that the func... |
I need an event which handles clicks on main window of my program.
I usedbutton-press-eventbut when i click on my window nothing happens.
I'm designing my GUI usingGlade Interface Designer.
please explain for me whenbutton-press-eventwill be called in gtk+ & is it the event i need or not?
|
Check you've got the button press event mask set for the window under the
Window Properties - Common tab in glade
|
This question already has answers here:"register" keyword in C?(19 answers)Closed9 years ago.
I was reading some gstreamer code and fell on this line
```
register int i;
```
Does anyone know what theregisterkeyword does ?
|
Another SO questionhas already answered this.
Answer From Brian Knoblauch:
It's a hint to the compiler that the variable will be heavily used and
that you recommend it be kept in a processor register if possible.Most modern compilers do that automatically, and are better at picking
them than us humans. :-)
So, ... |
My function gets aFILE*to read from, and it needs to read starting from some non-negative offset.
I could usefseek(file, offset, SEEK_SET), but it fails onstdin, for instance.
How can I determine iffseekworks? If it doesn't, I could read and discardoffsetbytes.
And is there a way to read (and discard) fromFILEwithou... |
You can test if fseek works on that stream, by callingfseek( file, offset, SEEK_SET)and on error, checking thaterrno == EBADFwhich is returned to say "The stream specified is not a seekable stream".
I think you need to read and discard, with a buffer, but if it can just be pagesize bytes and you keep a count of bytes... |
The GLib provides the structGStringwhich is encoded in UTF-8.
I know there are functions to convert a singlegchar(UTF-8) togunicode(UTF-32) orgunicode2(UTF-16).
But if I want to convert a complete GString into UTF-16/UTF-32, is this possible?
If not, I don't see the point in storing the majority of text in UTF-8 st... |
GLib provides severalCharacter Set Conversionfunctions. If you're confused about them not taking aGString, you can get at the underlying pointer and length using thestrandlenfields.
|
The GLib provides the structGStringwhich is encoded in UTF-8.
I know there are functions to convert a singlegchar(UTF-8) togunicode(UTF-32) orgunicode2(UTF-16).
But if I want to convert a complete GString into UTF-16/UTF-32, is this possible?
If not, I don't see the point in storing the majority of text in UTF-8 st... |
GLib provides severalCharacter Set Conversionfunctions. If you're confused about them not taking aGString, you can get at the underlying pointer and length using thestrandlenfields.
|
I want to send a message in WinAPI to window, created in other thread and then wait for process this message.
Is this possible? Thanks in advance.
|
UseSendMessage()to send a message to a window.
SendMessage()blocks the calling thread until the message had been deliveredandprocessed by the target window's message dispatcher.
FromSendMessage()'s documentation:
Sends the specified message to a window or windows. The SendMessage function calls the window procedure... |
```
int main() {
int i,j=6;
for(;i=j;j-=2)
printf("%d",j);
return 0;
}
```
This piece of code gives output 642
please explain me why this loop doesn't run infinitely and stops when j is non-positive
|
Whenjbecomes0the expressioni=jevaluates to0. Hence, the loop terminates.
Note that ifjwere to start as negative number ( e.g.-1)or as an odd number (e.g.5), then the condition will never evaluate to0and will result in an infinite loop.
|
I was working on the C assignment and being getting some errors for the following code
```
char BA[20] = "Hellow there";
char *pBA;
*pBA = &BA;
```
There is a red line under * and & in the third line of the code. I am getting these errors:
IntelliSense: this declaration has no storage class or type specifierIntelli... |
A good way to do this is -
```
char BA[20] = "Hellow there";
char (*pBA)[20] = &BA;
```
OR
```
char BA[20] = "Hellow there";
char (*pBA)[20] = NULL;
*pBA = &BA;
```
That said, pointers to arrays are quite rare in C, instead use pointers to pointers.
|
I have a problem. I'm trying to add struct elements by previously defined constant.
This is sample code (OpenGL+WinAPI)
```
#define ENGINE_STRUCT \
HGLRC RenderingContext;\
HDC DeviceContext;
```
And then:
```
typedef struct SWINDOW {
ENGINE_STRUCT
HWND Handle;
HINSTANCE ... |
Yes it is possible, a macro is a simple textual substitution
http://www.cplusplus.com/doc/tutorial/preprocessor/
The preprocessor examines the code before actual compilation of code
begins and resolves all these directives before any code is actually
generated by regular statements.
|
```
#include<stdio.h>
#include<malloc.h>
int main(){
int count,i,j;
int* val;
scanf("%d",count);
val = (int*)malloc(sizeof(int)*count);
if(NULL == val){
printf("\n memory is NULl \n");
}
for(i=0;i<count;i++){
scanf("%d",val[i]);
}
for(i=0;i<count;i++){
for(j... |
```
scanf("%d",count);
```
There is no & in scanf. It should be
```
scanf("%d",&count);
```
|
I am running FreeBSD 9.2, attempting to compile Dalnet ircd df4.6.5.
I am running into this error, and do not understand it.
```
channel.c:2536: error: lvalue required as left operand of assignment
```
Which is this line of code:
```
lopt->next = (LOpts *)lopt->yeslist=lopt->nolist=(Link *)NULL;
```
All of the pr... |
(LOpts *)lopt->yeslistis not an lvalue. Hence the compiler error.
Change the line to:
```
lopt->yeslist=lopt->nolist=(Link *)NULL;
lopt->next = (LOpts *)NULL;
```
|
So, here is the function that should create and write string into a /proc/minifwdb:
```
int write_to_file(char* rule)
{
FILE* fin;
fin = fopen("/proc/minifwdb", "a");
if (!fin)
{
printf("Could not open the file /proc/minifwdb, exiting...\n");
return 1;
}
if (fprintf(fin, "%s... |
Files in/procare used as an interface between user space and the kernel.
It is possible to use such a file to pass a string from user space into the kernel, but the kernel code that wants to receive it is responsible for creating the file.
|
I am building a shared library with option
" -L/my/path/ -lxxx.so "
Now i am using dlopen to dynamically link this library to my application
```
pvHandle = dlopen (pszLibName, RTLD_LAZY | RTLD_GLOBAL);
```
But when i execute it is showing an error message
/my/path/libxxx.so: cannot open shared object fil... |
Runldconfigcommand. Also see man page ofldconfigcommand you can get idea about it.
you need to add the path to the file/etc/ld.so.conf.
OR
give full path like
```
dlopen("/some/path/to/lib.so", RTLD_LAZY | RTLD_GLOBAL);
```
|
Why is this bad?
```
if (true)
int stuff = 10;
else
int stuff = 5;
printf("Stuff is %d\n",stuff);
```
Is it because of scope?
|
Yes.stuffonly exists in the scope of theifandelseblocks (where they are two different variables). You have to declare it outside the if-else to work.
```
int stuff;
if (true)
stuff = 10;
else
stuff = 5;
printf("Stuff is %d\n",stuff);
```
|
I was working on the C assignment and being getting some errors for the following code
```
char BA[20] = "Hellow there";
char *pBA;
*pBA = &BA;
```
There is a red line under * and & in the third line of the code. I am getting these errors:
IntelliSense: this declaration has no storage class or type specifierIntelli... |
A good way to do this is -
```
char BA[20] = "Hellow there";
char (*pBA)[20] = &BA;
```
OR
```
char BA[20] = "Hellow there";
char (*pBA)[20] = NULL;
*pBA = &BA;
```
That said, pointers to arrays are quite rare in C, instead use pointers to pointers.
|
I have a problem. I'm trying to add struct elements by previously defined constant.
This is sample code (OpenGL+WinAPI)
```
#define ENGINE_STRUCT \
HGLRC RenderingContext;\
HDC DeviceContext;
```
And then:
```
typedef struct SWINDOW {
ENGINE_STRUCT
HWND Handle;
HINSTANCE ... |
Yes it is possible, a macro is a simple textual substitution
http://www.cplusplus.com/doc/tutorial/preprocessor/
The preprocessor examines the code before actual compilation of code
begins and resolves all these directives before any code is actually
generated by regular statements.
|
```
#include<stdio.h>
#include<malloc.h>
int main(){
int count,i,j;
int* val;
scanf("%d",count);
val = (int*)malloc(sizeof(int)*count);
if(NULL == val){
printf("\n memory is NULl \n");
}
for(i=0;i<count;i++){
scanf("%d",val[i]);
}
for(i=0;i<count;i++){
for(j... |
```
scanf("%d",count);
```
There is no & in scanf. It should be
```
scanf("%d",&count);
```
|
I am running FreeBSD 9.2, attempting to compile Dalnet ircd df4.6.5.
I am running into this error, and do not understand it.
```
channel.c:2536: error: lvalue required as left operand of assignment
```
Which is this line of code:
```
lopt->next = (LOpts *)lopt->yeslist=lopt->nolist=(Link *)NULL;
```
All of the pr... |
(LOpts *)lopt->yeslistis not an lvalue. Hence the compiler error.
Change the line to:
```
lopt->yeslist=lopt->nolist=(Link *)NULL;
lopt->next = (LOpts *)NULL;
```
|
So, here is the function that should create and write string into a /proc/minifwdb:
```
int write_to_file(char* rule)
{
FILE* fin;
fin = fopen("/proc/minifwdb", "a");
if (!fin)
{
printf("Could not open the file /proc/minifwdb, exiting...\n");
return 1;
}
if (fprintf(fin, "%s... |
Files in/procare used as an interface between user space and the kernel.
It is possible to use such a file to pass a string from user space into the kernel, but the kernel code that wants to receive it is responsible for creating the file.
|
I am building a shared library with option
" -L/my/path/ -lxxx.so "
Now i am using dlopen to dynamically link this library to my application
```
pvHandle = dlopen (pszLibName, RTLD_LAZY | RTLD_GLOBAL);
```
But when i execute it is showing an error message
/my/path/libxxx.so: cannot open shared object fil... |
Runldconfigcommand. Also see man page ofldconfigcommand you can get idea about it.
you need to add the path to the file/etc/ld.so.conf.
OR
give full path like
```
dlopen("/some/path/to/lib.so", RTLD_LAZY | RTLD_GLOBAL);
```
|
Why is this bad?
```
if (true)
int stuff = 10;
else
int stuff = 5;
printf("Stuff is %d\n",stuff);
```
Is it because of scope?
|
Yes.stuffonly exists in the scope of theifandelseblocks (where they are two different variables). You have to declare it outside the if-else to work.
```
int stuff;
if (true)
stuff = 10;
else
stuff = 5;
printf("Stuff is %d\n",stuff);
```
|
How can i read it back so that I can see the contents in my console itself?I used this way:
```
n = fread(buffer, sizeof(buffer), 1, fp);
printf("0x%x", buffer);
```
Here I am getting only 1 byte output, but the file contains 72 bytes.
|
As Yves Daoust pointed out, %x formatter expects a single byte. Looping through the values will print all of them in hex.
```
n = fread(buffer, 1, sizeof(buffer), fp);
int i=0;
for(i=0; i<n; i++)
{
printf("0x%x ", buffer[i]);
}
```
Side note about fread:
The second parameter tofreadis size of each member you w... |
I finished my programming classes in C, and thought I would write some code down. BOOM! I run into so many problems. I guess the C language is so complicated, even a book can't explain how it works entirely.
This is my problem(I am trying to display something using a pointer)
```
#include <stdio.h>
#include <stdlib.... |
```
*a = {"hello"};
```
This dereferenced the pointer and assigned something to that memory location. The reason it crashed is because the pointer was uninitialised,ieit did not point at anything (actually it did point at something, but that something was an undefined memory location).
If you had done the following... |
I wanna know how to find how to calculate the values oft[]array in this algorithm?
```
int dow(int y, int m, int d)
{
static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
y -= m < 3;
return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
}
```
|
You can usecode belowto generate the required array
```
#include <stdio.h>
int main(void) {
int arr[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int totalDaysInThisYear = -1, m; /* Parity would make totalDaysInThisYear = 0 */
for(m = 1; m <= 12; ++m) {
const int parity = (m < 3);
... |
hi i came across this piece of code that implements floyds cycle detection algorithm,and was wondering if the checkslow_ptr!=Nullwas required becauseslow_ptris traversing only those nodes that fast pointer either traversed or skipped(after checking if it was non-NULL,that is), so isn't the checkif(fast!=Null&&fast->ne... |
Yes, in the code you've posted check forslow_p != NULLis redundant.
|
I've searched for questions asking this, I've seen many answers about opening the console that I'm showing on the screenshot, but all I see is the console of the command line debugger lldb, not the application's output.
|
printfis line buffered and requires a\nor flush to force it to print the output.
If you change your code to include the following line after everyprintfit will work the way you want.
```
printf("something I want in the console");
// Either of the next two lines should work
putchar('\n');
fflush(stdout);
```
|
I have noticed that 10(^7) or 10 000 000 increment is equal to 10 seconds in my environment.
Here is an example of custom function that works for me that wastes x seconds before the next line:
```
void pause(unsigned short seconds)
{
int f;
unsigned long long deltaTime = seconds*10000000;
for(f=0; f<delt... |
Several things wrong here:
In most compilers, if you enable optimizations (-O), it'll totally remove this code realizing it does nothing.the speed of the loop is determined by compiler, processor, system load, and many other aspectsThere's already asleepfunction.
|
I am trying to retrieve a list of the available video modes for my monitor using GLFW 3, but I'm struggling to understand the GLFW help pages.
I can retrieve the current video mode as follows:
```
int county
const GLFWvidmode* modes = glfwGetVideoModes(glfwGetPrimaryMonitor(), &county);
int width = modes->width;
in... |
It will give you an array of modes which the size is given bycounty(variable name shown in your code).
So you need to loop throughmodesfrom zero to less thancounty.
|
How can i read it back so that I can see the contents in my console itself?I used this way:
```
n = fread(buffer, sizeof(buffer), 1, fp);
printf("0x%x", buffer);
```
Here I am getting only 1 byte output, but the file contains 72 bytes.
|
As Yves Daoust pointed out, %x formatter expects a single byte. Looping through the values will print all of them in hex.
```
n = fread(buffer, 1, sizeof(buffer), fp);
int i=0;
for(i=0; i<n; i++)
{
printf("0x%x ", buffer[i]);
}
```
Side note about fread:
The second parameter tofreadis size of each member you w... |
I finished my programming classes in C, and thought I would write some code down. BOOM! I run into so many problems. I guess the C language is so complicated, even a book can't explain how it works entirely.
This is my problem(I am trying to display something using a pointer)
```
#include <stdio.h>
#include <stdlib.... |
```
*a = {"hello"};
```
This dereferenced the pointer and assigned something to that memory location. The reason it crashed is because the pointer was uninitialised,ieit did not point at anything (actually it did point at something, but that something was an undefined memory location).
If you had done the following... |
I wanna know how to find how to calculate the values oft[]array in this algorithm?
```
int dow(int y, int m, int d)
{
static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
y -= m < 3;
return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
}
```
|
You can usecode belowto generate the required array
```
#include <stdio.h>
int main(void) {
int arr[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int totalDaysInThisYear = -1, m; /* Parity would make totalDaysInThisYear = 0 */
for(m = 1; m <= 12; ++m) {
const int parity = (m < 3);
... |
hi i came across this piece of code that implements floyds cycle detection algorithm,and was wondering if the checkslow_ptr!=Nullwas required becauseslow_ptris traversing only those nodes that fast pointer either traversed or skipped(after checking if it was non-NULL,that is), so isn't the checkif(fast!=Null&&fast->ne... |
Yes, in the code you've posted check forslow_p != NULLis redundant.
|
I've searched for questions asking this, I've seen many answers about opening the console that I'm showing on the screenshot, but all I see is the console of the command line debugger lldb, not the application's output.
|
printfis line buffered and requires a\nor flush to force it to print the output.
If you change your code to include the following line after everyprintfit will work the way you want.
```
printf("something I want in the console");
// Either of the next two lines should work
putchar('\n');
fflush(stdout);
```
|
I have noticed that 10(^7) or 10 000 000 increment is equal to 10 seconds in my environment.
Here is an example of custom function that works for me that wastes x seconds before the next line:
```
void pause(unsigned short seconds)
{
int f;
unsigned long long deltaTime = seconds*10000000;
for(f=0; f<delt... |
Several things wrong here:
In most compilers, if you enable optimizations (-O), it'll totally remove this code realizing it does nothing.the speed of the loop is determined by compiler, processor, system load, and many other aspectsThere's already asleepfunction.
|
I am trying to retrieve a list of the available video modes for my monitor using GLFW 3, but I'm struggling to understand the GLFW help pages.
I can retrieve the current video mode as follows:
```
int county
const GLFWvidmode* modes = glfwGetVideoModes(glfwGetPrimaryMonitor(), &county);
int width = modes->width;
in... |
It will give you an array of modes which the size is given bycounty(variable name shown in your code).
So you need to loop throughmodesfrom zero to less thancounty.
|
I have noticed that 10(^7) or 10 000 000 increment is equal to 10 seconds in my environment.
Here is an example of custom function that works for me that wastes x seconds before the next line:
```
void pause(unsigned short seconds)
{
int f;
unsigned long long deltaTime = seconds*10000000;
for(f=0; f<delt... |
Several things wrong here:
In most compilers, if you enable optimizations (-O), it'll totally remove this code realizing it does nothing.the speed of the loop is determined by compiler, processor, system load, and many other aspectsThere's already asleepfunction.
|
I am trying to retrieve a list of the available video modes for my monitor using GLFW 3, but I'm struggling to understand the GLFW help pages.
I can retrieve the current video mode as follows:
```
int county
const GLFWvidmode* modes = glfwGetVideoModes(glfwGetPrimaryMonitor(), &county);
int width = modes->width;
in... |
It will give you an array of modes which the size is given bycounty(variable name shown in your code).
So you need to loop throughmodesfrom zero to less thancounty.
|
```
main() {
unsigned int a=-9;
printf("%d",a);//gives output -9
cout<<a;// gives output 9429967287
getch();
}
```
Why it gives different output in both cases?
Do 'printf' and 'cout' treat bit pattern in a different way?
Why is 'printf' not giving the positive answer?
|
Because you told it to:%dis for printing an argument as asignedint. To print an unsigned int, you should have used%u.
|
What is wrong with this piece of code? I can't find out what's going on.
```
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char *s = "OKAY";
for (int i = 0; i < 4; i++)
tolower(s[i]);
printf("\n%s\n", s);
return 0;
}
```
Output:
```
OKAY
```
|
You need to assign the return value oftolowertosbut this will invoke undefined behavior because string literals are non-modifiable as they are placed on read only section of memory. You can't modify it. Try this instead
```
char s[]= "OKAY";
for (int i = 0; i < 4; i++)
s[i] = tolower(s[i]);
```
|
Can I get a list of people that are online on Facebook?
For example, I am in a location and I want to get a list of people that are using Facebook at that time (are online) from a distance of, let's say, 50 meters. Is this possible?
Note: I notice that you can retrieve a list of online people that are in your friends ... |
directly: NO
but there are workarounds like: make users login into your app with facebook, check their facebook online status and location, do your stuff based on that info.
|
I've got a code that i cannot understand in C;
char c is string, that supposed to be randomized,
here is the question however, 26 is supposed to be range of values starting from 97, but it easy to understand for integer, but in case of char i have no clue what it is supposed to be
```
char c = (char) rand() % 26 + 97... |
That is generating a random character.In ASCII, alphabetical characters start at 97. So, the code is taking 97, adding a random number between 0 and 25 to it, then casting it to achar, which generates a random alphabetical character.
|
What is wrong with this piece of code? I can't find out what's going on.
```
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char *s = "OKAY";
for (int i = 0; i < 4; i++)
tolower(s[i]);
printf("\n%s\n", s);
return 0;
}
```
Output:
```
OKAY
```
|
You need to assign the return value oftolowertosbut this will invoke undefined behavior because string literals are non-modifiable as they are placed on read only section of memory. You can't modify it. Try this instead
```
char s[]= "OKAY";
for (int i = 0; i < 4; i++)
s[i] = tolower(s[i]);
```
|
Can I get a list of people that are online on Facebook?
For example, I am in a location and I want to get a list of people that are using Facebook at that time (are online) from a distance of, let's say, 50 meters. Is this possible?
Note: I notice that you can retrieve a list of online people that are in your friends ... |
directly: NO
but there are workarounds like: make users login into your app with facebook, check their facebook online status and location, do your stuff based on that info.
|
I've got a code that i cannot understand in C;
char c is string, that supposed to be randomized,
here is the question however, 26 is supposed to be range of values starting from 97, but it easy to understand for integer, but in case of char i have no clue what it is supposed to be
```
char c = (char) rand() % 26 + 97... |
That is generating a random character.In ASCII, alphabetical characters start at 97. So, the code is taking 97, adding a random number between 0 and 25 to it, then casting it to achar, which generates a random alphabetical character.
|
Can I get a list of people that are online on Facebook?
For example, I am in a location and I want to get a list of people that are using Facebook at that time (are online) from a distance of, let's say, 50 meters. Is this possible?
Note: I notice that you can retrieve a list of online people that are in your friends ... |
directly: NO
but there are workarounds like: make users login into your app with facebook, check their facebook online status and location, do your stuff based on that info.
|
I've got a code that i cannot understand in C;
char c is string, that supposed to be randomized,
here is the question however, 26 is supposed to be range of values starting from 97, but it easy to understand for integer, but in case of char i have no clue what it is supposed to be
```
char c = (char) rand() % 26 + 97... |
That is generating a random character.In ASCII, alphabetical characters start at 97. So, the code is taking 97, adding a random number between 0 and 25 to it, then casting it to achar, which generates a random alphabetical character.
|
I have a problem with Visual Studio 2012
I want to include one header file in other and then to include the second header file in .c file.
I want to define a constant in first header file and use its value in c file.
I think this is possible because it is done in standart libraries
When I do this compiler is sending... |
I think it's OK. Maybe you can show more details about your problem.
First header (a.h):
```
#ifndef A_H
#define A_H
const int i = 5;
#endif
```
Second header (b.h):
```
#ifndef B_H
#define B_H
#include "a.h"
#endif
```
source file:
```
#include <stdio.h>
#include "b.h"
main() {
printf("%d\n", i);
... |
I am new to C. What is the most simple way to execute a C program without an IDE?
I created my first C program und it runs flawlessly using my IDE Netbeans on Mac OS X. Now I need to make that program be "executable without IDE on Windows".
Also the requirement is only "Windows", no specific version. Which means I m... |
As soon as you have built your app, it is a program you can run outside the IDE. You just need to find it. :) In NetBeans this will usually be under your project directory in a subdirectory called "dist". There will be an executable file in there which you can copy out to wherever you want.
|
I'm experienced with Objective C and easily know how to use NSScanner. I have a project I need to write in either C or Python that needs to use similar functionality to NSScanner(such as scanUpToString). Are there any standard or non-standard libraries that could provide similar functionality?
|
In Python take a look at thefindmethod ofstr.
You could combine it like so:
```
foo ="barbazzapp"
foo[:foo.find("zapp")] # Returns 'barbaz'
```
|
I am debugging a C program with gdb. I have used the tty command to send the output to a new terminal window but am unable to enter input while the program is running.
If I debug in the same window it works fine, but when using a separate terminal window, input doesn't do anything.
I can still kill the process with ... |
Start your program in one window. While your program is waiting for input, start gdb in another window. Use the gdbattachcommand to attach to and debug your program.
|
This question already has answers here:Why can't the size of a static array be made variable?(4 answers)Closed9 years ago.
My teacher said that I can't do that when I'm declaring an array:
```
int flag_x =0 , flag_y = 0 , x=2, y=2, principal[x][y];
```
He said I need to user define to use static array , like that:
... |
He is right. The number of elements in an array declaration with static storage duration (e.g., declared at file scope) has to be an integer constant expression.
If the array has automatic storage duration, the number of element doesn't have to be an integer constant expression:
```
void foo(void)
{
int x=2, y=2... |
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
```
//What I have that works on integers with 10 digits or less:
#include <stdio.h>
#include <string.h>
int... |
The problem is perhaps rather "how do you work with integers with more than 10 decimal digits of precision?"
The answer isby using a big-number librarysince you cannot assume the built-in types to support that many digits, typically.
Or, you can perhaps get away by using
```
#include <stdint.h>
```
and usinguint64... |
If y is of integer type, then the expressions:
```
3*(y-8)/9
```
and
```
(y-8)/9*3
```
Will yield different result always or is it possible for them to yield same result?
What does it depend on?
Explanation with an example will be helpful.
|
May yield different or same result, it is depend on 'y' value. The operations will be carried from left to right.
Ex: for y=11:
3*(y-8)/9: 1 (y-8)/9*3: 0
for y = 10
3*(y-8)/9: 0 (y-8)/9*3: 0
|
I'm curious about one thing, the following code works perfectly.
```
#include <stdio.h>
int main()
{
FILE * fp = fopen("test.txt", "r");
char line[100];
while( fgets(line, sizeof(line), fp) != NULL )
fputs(line, stdout);
fclose(fp);
return 0;
}
```
But why it is not possible to use instead:
```
char ... |
fgetscrashes because it is writing the result intounallocated memory.
Without any further memory allocation,char *linepoints to "nothing". It points tosomething, but not to any valid memory location --nullif your compiler sets uninitialized values to0, or anyrandommemory location anywhere on or not on your system.
E... |
Good day everyone. I have the following c-string initialization:*(str) = 0;where str is declared aschar str[255];. The questions are:
1) is it the best way to initialize a string this way?
2) should I expect trouble with this code on 64-bit platform?
Thanks in advance.
|
The instruction*(str) = 0is completely equivalent tostr[0] = 0;.
The initiatlization simply place the integer0(which is equivalent to'\0') in the first position, making the string empty.
1) There's no "best way", the key is being consistent so if you choose the "*(str) = 0;" path, always do the same everywhere.
2) ... |
Good day everyone. I have the following c-string initialization:*(str) = 0;where str is declared aschar str[255];. The questions are:
1) is it the best way to initialize a string this way?
2) should I expect trouble with this code on 64-bit platform?
Thanks in advance.
|
The instruction*(str) = 0is completely equivalent tostr[0] = 0;.
The initiatlization simply place the integer0(which is equivalent to'\0') in the first position, making the string empty.
1) There's no "best way", the key is being consistent so if you choose the "*(str) = 0;" path, always do the same everywhere.
2) ... |
How to access a struct that is put into an array as pointer?
How to access thebootearray propertly? I tried also usingboot = *boote[i];
```
typedef struct boot {
char name[30];
} Boot;
Boot *boote[3] = {NULL, NULL, NULL};
Boot boot;
scanf("%s", boot.name);
boote[0] = &boot;
for (int i = 0; i < 3; i++) {
... |
Leaving aside thestrcpything, the way you access the struct is ok, in fact the "abc" is being printed. However, in theforloop you're looping overbootie[1]andbootie[2]which are not assigned yet, therefore it doesn't print anything.
|
After reading some C programming books, I would like to understand something about portability. C code is portable, but must be recompiled on each machine, so that the compiler can generate the right assembler and binary code for the processor.
Yet, when I download games (portable games) that contain some files, the ... |
All Windows machines use the same two architectures (x64 or x86).
That means that if you want to run on adifferentarchitecture, such as Linux, you need to recompile.
|
I would like to know if the open() system call in Linux latest kernel would block if the filesystem is mounted as remote device, for example a CEPH filesystem, or NFS , and there is a network failure of some sort?
|
Yes. How long depends on the speed (and state) of the uplink, but your process or thread will block until the remote operation finishes. NFS is a bit notorious for this, and some FUSE file systems handle the blocking for whatever has the file handle, but you will block onopen(),read()andwrite(), often at the mercy of ... |
For instance, if I attach a renderbuffer to GL_DEPTH_ATTACHMENT and then proceed to attach a texture to GL_DEPTH_ATTACHMENT, will the renderbuffer still be attached?
|
Yes, they do share the "same space."
Technically, what you attach to FBOs are images. These images can take the form of a renderbuffer or a myriad of different types of textures, some of which are actually multiple different images (necessitating things like layered rendering to use all of the images in a texture in ... |
I am using g++(under linux) to compile a piece of c code. The compiled executable file works good on linux. But it doesn`t run on unix(SunOS). How to make the compiled file runs on both Unix and Linux? Thank you.
|
The POSIX.1 standard guarantees compatibility on source code niveau. This is—every program that is written to use the POSIX.1 APIs is guaranteed to compile and run on any POSIX platform. POSIX does not and did never guarantee that binaries are portable between different platforms, even if all of them are compliant.
D... |
I'm having a big problem on Eclipse Kepler for Mac!!
Please, help me!!
```
**** Incremental Build of configuration Debug for project Working ****
make all
Building file: ../hello.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++11 -MMD -MP -MF"hello.d" -MT"hello.d" -o "hello.o" "../hell... |
Set the variableDYLD_LIBRARY_PATHto the location of libmpc library. To do this, you have to go to Run/Run Configurations and then select Environment tab, then add the variableDYLD_LIBRARY_PATHand finally set its value to the path to the required dylib.
|
I am trying to create a multifile c program, I am using a function in one file that I want to call again from another file, how do I do this without making either of the files header files? Can I use function prototypes for this?
|
In order to use functions defined in another file, you must use a header file, but you don't convert your .c files to header files, you include the function prototypes needed by one particular class (file) in the header file, and then include that header file in each file.
```
calc.h
calc.c <---- include calc.h
main... |
We can do matrix multiplication in several ways. A and B are two matrix, of size 1000 * 1000.
Use the matlab builtin matrix operator.A*BWrite two nests explicitly.Write three nests explicitly.Dynamically link C code to do the three nests.
The result is
*operator is very fast. It takes about 1 second.Nests are very... |
Because matrix multiplication is highly optimised in Matlab, usingLAPACKlibraries under the hood.
You will find it hard to beat the performance of those libraries. Certainly, simple nested loops don't takecache effectsinto account, and will thus exhibit terrible performance.
|
I'm attempting to define a Makefile that will take in a filename (eg. foo) as a variable from the command line, and then compile & link using gcc.
So if I typemake fooit will compilefoo.c,link upfoo.oto the required libraries, and clean up the .o file. Here's my code so far, does anyone have any suggestions for where ... |
Make already uses the arguments as the target list. And it already hasimplicit rulesthat do what you want. You should be able to get away with something like this as your makefile:
```
LDLIBS=-lmar -lbar
LDFLAGS=-v
CFLAGS=-v
```
|
This question already has answers here:How to write log base(2) in c/c++(14 answers)Closed9 years ago.
I want to execute logx in C, but I found out that the math library in C, only provides logs with bases e and 10. How is it possible to get a logarithm in some other basis?
|
http://en.wikipedia.org/wiki/Logarithm#Change%5Fof%5Fbase
The logarithmlog_b(x)can be computed from the logarithms ofxandbwith respect to an arbitrary basekusing the following formula:log_b(x) = ln(x) / ln(b)
|
We can do matrix multiplication in several ways. A and B are two matrix, of size 1000 * 1000.
Use the matlab builtin matrix operator.A*BWrite two nests explicitly.Write three nests explicitly.Dynamically link C code to do the three nests.
The result is
*operator is very fast. It takes about 1 second.Nests are very... |
Because matrix multiplication is highly optimised in Matlab, usingLAPACKlibraries under the hood.
You will find it hard to beat the performance of those libraries. Certainly, simple nested loops don't takecache effectsinto account, and will thus exhibit terrible performance.
|
I'm attempting to define a Makefile that will take in a filename (eg. foo) as a variable from the command line, and then compile & link using gcc.
So if I typemake fooit will compilefoo.c,link upfoo.oto the required libraries, and clean up the .o file. Here's my code so far, does anyone have any suggestions for where ... |
Make already uses the arguments as the target list. And it already hasimplicit rulesthat do what you want. You should be able to get away with something like this as your makefile:
```
LDLIBS=-lmar -lbar
LDFLAGS=-v
CFLAGS=-v
```
|
This question already has answers here:How to write log base(2) in c/c++(14 answers)Closed9 years ago.
I want to execute logx in C, but I found out that the math library in C, only provides logs with bases e and 10. How is it possible to get a logarithm in some other basis?
|
http://en.wikipedia.org/wiki/Logarithm#Change%5Fof%5Fbase
The logarithmlog_b(x)can be computed from the logarithms ofxandbwith respect to an arbitrary basekusing the following formula:log_b(x) = ln(x) / ln(b)
|
I seem to have confused myself so much that this doesn't make sense anymore.
1 byte = 8 bits.
So if I have a memory location such as
```
0xdeadbeef
3735928559 (base10)
1101 1110 1010 1101 1011 1110 1110 1111
```
Now if I addone byteto0xdeadbeef, what is the binary sequence I'm adding? Is it1000? If I add 1 bit, I ... |
What I understand from your question is that, you are confused with adding a bit and a byte to the counter.Since memory addresses are measured in bytes (in programming languages), any arithmetic operation to it is done in bytes.To increment counter, adding1to it is like increment it to one byte next to the base addres... |
I have an array of pointers to structs.
```
struct key {
int *data;
};
struct key *entry = NULL;
entry = malloc(sizeof(entry));
```
Reallocated a bit of times:
```
node = realloc(node, (length+1)*sizeof(node[0]));
node[length].data = some_int;
```
In another part of my pr... |
&(node[i])takes the address ofnode[i].
So
```
&(node[i]) != NULL
```
will always be true, asthe address ofnode[i]willalwaysbe different fromNULL.
|
I need to write program to find the integer square root of a number which is thousands of digits long. I can't use Newton Raphson as I don't have data types to store and divide such large numbers. I am using a long array in C to store the number. Is there any algorithm to find the square root by maybe iterating ove... |
If you can input the target number, then youmusthave a way to store at least one such large number. For Newton-Raphson you only need to be able to halve and add numbers. Think of a way to halve a number without using division.
ETA: Correction: division can be avoided by doubling and subtraction.
|
I would like to use:
```
BN_rand_range(...);
```
and due to the OpenSSL documentation:
The PRNG must be seeded prior to calling BN_rand() or BN_rand_range().
But there is no link or method name hint provided how I could do that. What is the correct way to seed the PRNG with OpenSSL?
|
What is the correct way to seed the PRNG with OpenSSL?
Internally, OpenSSL of auto-seeds itself withRAND_poll(with some hand waiving). There's a few reasons why you might want to avoid the behavior and explicitly seed the generator yourself.
There's a more complete writeup on the OpenSSL wiki atRandom Numbers.
|
My code contains the following line:
```
int counts[config.max_c];
```
I was surprised to see that it compiled without issue using defaultgccwithout any flags. According toman gccthe default standard for c code isgnu89. Does this standard support this type of array initialisation, and if so where can I find a refere... |
Does this standard support this type of array initialisation, and if so where can I find a reference?
No. It doesn't support variable length arrays.
Variable-length automatic arrays are allowed in ISO C99,and as anextension GCC.Although you are compiling your code in C89, it compiles without error because of the GCC... |
I have declared a structure in a shared library and I want to use it on my application but I don't know how to use it.
It's not possible to re-declare it in my application due to compiler incompatibility.
what is the solution?
|
Astructdoesn't existanywherein a C program or shared library etc. After compilation, astructonly exists as a bunch of offsets into a "blob" where instructions will read from / write to.
If you want to link against a library that uses somestructas part of its API, youmustinclude a header file that declares the structu... |
In my C program I am using void* pointers. Is there anyway to check in an if statement if the void* pointer is pointing to an int* or a char*?
|
Nope. There is no run-time type information in C. Avoid*is just an address. That's it. It's completely up to the programmer to know / keep track of what information avoid*points to.
With more information about how/why you're usingvoid*, a workaround could possibly be suggested.
|
In an example of "C Primer Plus", the author has used%ulformat specifier (in both scanf and printf) forunsigned long. When I try to generalize the problem, it seems that the%ulmakes something wrong in my computer. But using%lusolved the issue.
Actually, rather than focusing on the problem and the line of codes, I wan... |
%luis correct, while%ulisincorrect.
Aprintfformat specifier follows the form%[flags][width][.precision][length]specifier.
uis aspecifiermeaning "unsigned decimal integer".
lis alengthmodifier meaning "long".
Thelengthmodifier should go before the conversionspecifier, which means%luis correct.
|
I am writing a C program on OS X and compiling it with clang. I am quite new to C and I have come to understand that some functions likegetline()are useful but non-standard. I would like to be able to compile the program on a system where the GNU C Library is not available. Not knowing exactly what functions are non-s... |
You can usefeature test macros(see also:XSH 2.2.1 POSIX.1 Symbols) to request visibility of only a particular set of standard interfaces. In particular,
```
-D_XOPEN_SOURCE=600
```
on the command line or
```
#define _XOPEN_SOURCE 600
```
should expose POSIX base plus the XSI option for the outdated 2001 version of... |
Assuming I understand the flow correctly, one would like to read few byes off an openedFILEstream, lets says, usingfread:
thereadsyscall will copy the data from the kernel to the user space bufferuser space buffer (either allocated byglibcor provided bysetvbuf...) will be copied to the buffer provided tofread
why is... |
The purpose of the 2nd buffer is to amortize the system call overhead. If you read/write only a few bytes at a time, this second user space buffer will improve performance enormously. OTOH if you read/write a large chunk, the 2nd buffer can be bypassed, so you don't pay the price for double copying.
|
This question already has answers here:strcat problem with char *a[10](5 answers)Closed9 years ago.
I'm trying to get the user argv and print in the screen the result. Here is my following code:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[])
{
if (argc >= 1)
... |
You need your destination argument to strcat to be large enough to hold everything, ie
```
char command[50];
strcpy(command, "gcc ");
strcat(command, argv[1]);
```
|
I am using LDA algorithm to classify a signal, how can i do that with multiple classes ? I have read some references but don't get the result.
I I've looked example code atlink
but it doesn't have explicit classifier part for me!
|
You can use OpenCV to keep doing this.
|
I have auint8_tarray from which I need to take the first 4 elements, 32 bits, to create asize_t(uint32_ton my machine).
Example non-working code:
```
uint8_t array[8];
array[0] = 128;
array[1] = 128;
array[2] = 0;
array[3] = 0;
size_t size = array[0]; //results in 128
size = *array; //also results in 128
```
The by... |
To do it in a portable way (i.e. endian independent) use the shift operators. Something like
```
uint32_t result = 0;
for(int i=3; i>=0; --i) {
result <<= 8;
result += array[i];
}
// result now holds the value you desire
```
|
When I run the following code at the same time on two different machines, I get the same results. Why they are the same and how I can make them different?
```
for (int i = 0; i < 10; i++)
{
delay[i] = (rand() % 2000) + 100;
printf("random number: %i\n", delay[i]);
}
```
the results are the same when I use
`... |
srand()seeds or sets the initial state of the random number generator. I think the problem you are seeing is becausetime()typically only has a resolution of 1 second. It's possible to start the two programs within 1 second of each other so they both get the same starting seed.
You might try using a higher-resolution ... |
When I run the following code at the same time on two different machines, I get the same results. Why they are the same and how I can make them different?
```
for (int i = 0; i < 10; i++)
{
delay[i] = (rand() % 2000) + 100;
printf("random number: %i\n", delay[i]);
}
```
the results are the same when I use
`... |
srand()seeds or sets the initial state of the random number generator. I think the problem you are seeing is becausetime()typically only has a resolution of 1 second. It's possible to start the two programs within 1 second of each other so they both get the same starting seed.
You might try using a higher-resolution ... |
This isn't a specific code question, more of a general question regarding some feedback I've been getting. I write C/C++ code quite frequently (which is not to say I'm any good at it, but that's another story), and occasionally I will cast a pointer, e.g.:
```
void **result = (void **) malloc(size);
```
I understand... |
Answer is different for C and C++. In C youshould not cast the return value ofmalloc.In C++ you must have to cast it.
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed9 years ago.Improve... |
use-Wno-pointer-sign. You can find it inman gcc
|
I have stored an int in a void * variable in a struct
```
void * data = &ID;
```
and now I want to print it. How would I do this? I tried to dereference it but the compiler complained about dereferencing void*. Thanks!
|
You should castdatatoint *first, then derefer it:
```
printf("%d\n", *(int *)data);
```
|
I have stored an int in a void * variable in a struct
```
void * data = &ID;
```
and now I want to print it. How would I do this? I tried to dereference it but the compiler complained about dereferencing void*. Thanks!
|
You should castdatatoint *first, then derefer it:
```
printf("%d\n", *(int *)data);
```
|
Can we dynamically create a function from string and call a ffi.C binding?
example :
```
ffi.cdef [[
void foo_bar_A_get_info(void);
void foo_bar_B_get_info(void);
]]
some = ffi.load("some.so")
function call_fun(var)
-- var can be A or B
some.foo_bar_var_get_info()
end
call_fun("A")
call_fun("B")
```
I am... |
C libraries loaded from the FFI are indexed just like Lua table; you can index them with a raw value in the same way:
```
some["foo_bar"..some_string.."_baz"]()
```
|
I'm working on Linux and FreeBSD. When I usegetpwnam()orgetpwuid(), I get a pointer to apasswdstruct. What's the safe way to use thechar*members of thatpasswdstruct?
The man page says this struct is a static object but will be overwritten by subsequent calls, so I guess the safe way is to usestrdup()to get a copy of ... |
The safest way is not to use them at all, but instead usegetpwnam_randgetpwuid_r, which store the results in a caller-provided buffer. This not only avoids the issue you're asking about, but also makes your code safe for use in a multi-threaded process.
|
For some reason when I call WSARecvFrom the function does not return until something is received.
```
_socket = WSASocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP, NULL, NULL, WS_OVERLAPPED);
...
sockaddr_in addr = ...
if(bind(_socket, (const sockaddr*)&addr, sizeof(addr)) != EXIT_SUCCESS) { ... }
...
HANDLE _handle = Create... |
ChangeWS_OVERLAPPED(which as a value of 0) toWSA_FLAG_OVERLAPPED(which has a value of 1) instead. You are not creating an overlapped socket correctly, so_recvOverlapis being ignored byWSARecvFrom().
|
I just started to use gstreamer and I want to know how to register a plugin that I wrote. Of course, I have followed thePlugin Writer's Guideand used themake_elementcommand to build my plugin. Now, I want to test it in a basic pipe line using thegst-launchcommand.
The problem is that I don't know how to register my ... |
I'v solve my problem by upgrading to 1.0 but I also had to change the installation path in the "configure" folder.
|
This question already has answers here:Alternative (K&R) C syntax for function declaration versus prototypes(6 answers)Closed9 years ago.
What's the difference between this declaration:
```
void
main(argc, argv)
int argc;
char **argv;
{
// ...
}
```
from this?
```
void
main(int argc, char **argv)
{
// ..... |
Its a different notation style that was used in C at its beginning called the KR Notation (for Kernighan and Ritchie, C's designers). The well known C notation style that is used today follows the ANSI standard.
Here's link to a Wikipedia article describing the KR notation :http://en.wikipedia.org/wiki/K%26R_C#K.26R_... |
I have the following code:
```
char* p;
void func1()
{
p = "hello world";
}
int main()
{
func1();
printf(p);
return 0;
}
```
This code works fine here, but I'd like to know if it is correct or if there is an "undefined behavior" here.
Will the "hello world" still exist outside the func1()?
|
String literals are character arrays with static storage duration (cf. C11 6.4.5/6), and thus their lifetime extends to the end of the entire program. Your code is fine.
|
So I am trying to run a sscanf on char *temp[512], but i get an error( error:invalid operands to binary & (have 'char *' and 'float').
char *temp[512] contains info:Flen 2014-5-20 19.90 14.15 19.91 2014-05-21 15.05 11.3 15.05
```
char dates[13];
char dates2[13];
char city[15];
float temp1, temp2, temp3, temp4, temp5,... |
Iftempis defined aschar *temp[512]then you it isn't a string and you can't pass it tosscanf. It should be defined aschar temp[512].
|
I want to convert the epoch time in binary to hex. I am able to do this in the command line by the following command
```
# epoxy time in decimal
me@bof:/auto/homes$ date +%s
1400687648
# epoxy time in hex
me@bof:/auto/homes$ printf "%x\n" $(date +%s)
537ccc3b
```
Now I want to do the above inside a Makefiles, I am ... |
you forgot to putshellfor the call ofdate
```
identifier:
printf "%x\n" $(shell date +%s)
```
|
I want to have some unicode labels in GTK+ interface windows. How can I use it? Code:
```
gtk_window_set_title(GTK_WINDOW(window), "ŲŪ");
```
Does not show anything in the window title bar so I guess it is because of encoding.
I am using Visual Studio 2012 and C compiler from Windows Driver Kit 7.1.0 which is outda... |
if you need to use Unicode code points directly inside C, you can use the C escaped octal form; for instance, the Copyright sign © is\302\251.
this table should help you converting code points:http://utf8-chartable.de/unicode-utf8-table.pl?utf8=oct
|
Why I can't dereference a null pointer? That is, why I can't read/write memory which address is simply 0?
Does the base pointer of my process have a different address? If yes, is there a way to obtain the lower memory adders available for the default heap of my process?
|
A null pointer is not a pointer to "memory [whose] address is simply 0". It's just a special pointer that doesn't point to anything valid.
The C language says that there are no requirements on the behaviour of a program that dereferences a null pointer.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.