question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
As I compile my app.cpp file into app.js using Emscripten, I'm not seeing a difference between the -o1/2/3 optimization levels when I inspect the app.js file. They are all unoptimized/unminified and human readable. I've run the emcc update/install commands, and I use
```
emcc -o3 app.cpp -o app.js
```
to compile into javascript. I'm sure I'm missing something obvious, but I've been through the docs and can't seem to realize what I'm passing over. This is kind of silly to me, but I guess I just need to ask.
I appreciate any help.
|
Yup, it was obvious. The command is case sensitive. Needs to be a capital 'O'. I don't have much experience with the command line. This is what happens.
|
I am trying to debug my C program that accesses a postgres database.
I would like to dump the contents of PGresult using some postgres provided routine.
Is there a postgres provided routine that will dump PGresult in a human readable way?
I will add that as an option to the logging that will dump the contents of PGresult.
Here is a related question for non-SELECT commands:How to dump PGresult for non-SELECT commands
|
Insrc/interfaces/libpq/fe-print.cthere is a public functionPQprint; it'sin the manual.
|
I have a multi-dimensional structure in R in which I'm accessing a list on those ways:
model$a$bormodel[[5]][[4]]
But how to do this in a C extension? Right now I'm trying it like that:
VECTOR_ELT(VECTOR_ETL(model, (R_xlen_t) 4), (R_xlen_t) 3)
But it behaves more likemodel[5][4]thanmodel[[5]][[4]]
|
Got it by using
coerceVector with generic vector (VECSXP) after first VECTOR_ELT
and
coerceVector with integer vector (INTSXP) after second VECTOR_ELT
|
Is there any difference between null pointer and uninitialized pointer?
This question was asked in one of the interviews.
Could you please explain the difference that they have?
|
Well, the difference is exactly that. Null pointer is initialized to null, and as such has defined meaning. You can check it for null, and dereferencing it will (on all platforms I know) cause a program to crash with meaningful diagnostics. You can also use null pointers in some specific hacks.
Unitinialized pointers, on the other hand, are just random and should be avoided.
|
Closed. This question needs to be morefocused. It is not currently accepting answers.Want to improve this question?Update the question so it focuses on one problem only byediting this post.Closed8 years ago.Improve this question
Is my definition of machine code right?
Machine code is the programming language which is native (understandable) only by a specific type of system or operating system and not by other system or operating system.
My teacher told it is wrong and the word native must not be used.
What is machine code?
|
Machine code is the code written in the native instruction set of the machine. i.e. the CPU. It is possible to write code which can run on different OSes, and different processors, though this is usually only done when there is relatively minor differences.
I used to have a program which could run on a Z80 or x86, on MS-DOS or CPM-86.
|
The following call fails to dynamically load the library, complaining that it cannot load more objects with static TLS:
```
dlopen("libfoo.so",RTLD_LOCAL | RTLD_NOW);
```
However after I examine it:
```
readelf -a libfoo.so | grep TLS
```
There are no TLS symbols.
Any ideas why it would be failing to load?
|
Any ideas why it would be failing to load
This library probably depends on some other library with a TLS segment.
You can runldd libfoo.so, and thenreadelf -lon each dependent library. One of them has to have aTLSsegment, or you wouldn't be getting the error you are getting.
|
I'm using CooCox CoIDE and GCC ARM embedded 4.9q2 and I use the cmsis library, programming on an ARM Cortex-M4 STM32F3 MCU.
I'm currently trying to do some quick saturating arithmetics inside an interrupt. I was under the impression that I could do that using the ARM C Language Extension (ACLE) to avoid having some assembler inserts in my C code.
However, when I call a function like __qadd16(a,b), I get an "undefined reference" error.
I suppose I have something more to include or a compiler option to specify in order to enable the ACLE, but I don't know which exactly.
So my questions are:
Is it possible or did I misunderstand the use of ACLE ??
What is the procedure to be able to call these functions? Are they not part of arm GCC? If not, what should I include?
Thanks in advance!
|
You should
```
#include <core_cm4_simd.h>
```
From the CMSIS headers. It defines the instructions as inline functions, prefixed by__.
|
```
#include <stdio.h>
int main()
{
int i=-1;
!i;
printf(i);
}
```
Output:
0
Why is the outputzero?
|
In your code,
```
printf(i);
```
isinvalid, becauseprintf()expects aconst char *as the first argument, and you're passing anint. It invokesundefined behaviour.
Turn up the compiler warnings. With the basic level of warning turned on, you should get some message along the line
warning: passing argument 1 of ‘printf’ makes pointer from integer without a cast
Solution: I believe, what youwantedis
```
printf("%d\n", i);
```
|
Let's say i have source and header files for C code (bus-driver.candbus-driver.h)can i call functions inside them from node.js
for examplebus-driver.h
```
void bus_init(void);
void bus_write(char *buf);
```
I want to call these functions from node.js.
|
The nodeffi seems to be simplest way to do that.
I didn't test it so it can has problems that I don't realize now.
But I would suggest to do something like that, following thetutorial.
Installnodeffi:
Generate a library for your bus-driver if you don't have one, let's call it libbusdriver.
Then in your javascript do something similar to this:
```
var ffi = require('ffi');
var libbusdriver = ffi.Library('libbusdriver', {
'bus_init': [ 'void', [ 'void' ] ],
'bus_write': [ 'void', [ 'string' ] ],
});
libbusdriver.bus_init();
libbusdriver.bus_write("Hello");
```
Let me know if it helps.
|
With IBM's cc compiler there is one option -brtl.
cc-brtl .....
This option does the following:-
-brtl Tells the linkage editor to accept both .so and .a library file types.
I am using gcc compiler now on ubuntu. I want to know what is the corresponding option in gcc to achieve
the same thing?
|
You don't need that option forgcc. The link editor will accept both so and a files by default, with so files being preferred. You can think ofgccas having the opposite behaviour to IBM's C compiler: The behaviour without any options is as if you provided-brtlto IBM's C compiler, while the option-staticturns of dynamic linking (and thus causesgccto not take so files into consideration), which is as if you didn't specify-brtlto IBM's C compiler.
|
I have a variable i:
```
int i;
if(b){
i=1;
}
else{
i=-1;
}
```
Isiundefined behavior because ofint i;exists?
Or Should we alwaysint i=0first?
|
Absolutely fine.
You are initialisingion all program control paths, and not reading the value until initialisation is complete.
I prefer using the ternary operator in such instances.
int i = b ? 1 : -1;
as that's less vulnerable to accidental reference to an uninitialisedi.
|
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * fp;
fp = fopen ("file.txt", "w+");
fclose(fp);
return(0);
}
```
the above programs will create a file . i need that file needs to be placed in specific directory. please help
|
Add path into the parameter offopen().
```
fp = fopen ("/path/to/file.txt", "w+");
```
|
For a project I have to change the zero-driver to produce an infinite amount of 'a' instead of the usual zero. So I modified /usr/src/drivers/memory/memory.c
This was the original:
```
/* Initialize /dev/zero. Simply write zeros into the buffer. */
for (i=0; i<ZERO_BUF_SIZE; i++) {
dev_zero[i] = '\0'; //This is line 247
}
```
This is my modification:
```
/* Initialize /dev/zero. Simply write zeros into the buffer. */
for (i=0; i<ZERO_BUF_SIZE; i++) {
dev_zero[i] = 'a'; //This is line 247
}
```
So I save and close and recompile memory.c but no changes when I saycat /dev/zero. I even tried deleting /dev/zero and usingmknod /dev/zero c 1 5to create a new one. But still no changes. I also tried rebooting.
Am I changing the incorrect file or am I not compiling the right files?
|
Assuming you are editing the kernel source code, you probably need to reboot to see your changes take effect.
|
Go through the following C code
```
# define swap(a,b) temp=a; a=b; b=temp;
main( )
{
int i, j, temp;
i=5;
j=10;
temp=0;
if( i > j)
swap ( i, j );
printf ( "%d %d %d", i, j, temp);
}
```
Compiler Output:
```
10 0 0
```
I am Expecting this output
```
10 5 0
```
Why am I wrong??
|
It's the lack of braces. This is one of the common pitfalls with macros. Let's see what happens:
```
if(i > j)
swap(i, j);
```
becomes:
```
if(i > j)
temp = a; a = b; b = temp;;
```
Made a little more readable:
```
if(i > j)
temp = a;
a = b;
b = temp;
```
So the linesa = b;andb = temp;will always be executed, they fall outside theifbody.
Either put braces around theif, or the macro.
|
I recently started using Dev C++ 4.9.9.2 to experiment with graphics program in C(thanks to thistutorial). But for some reasonsetbkcolor()does absolutely nothing. Here's the code...
```
#include <stdio.h>
#include <graphics.h>
#include <conio.h>
int main()
{
initwindow(800,600);
setbkcolor(GREEN); //FAILED. also tried "setbkcolor(2);"
while ( !kbhit() ){}
return 0;
}
```
Here's the Output:
I am usingWindows 7 Professional. Is this something to do with the Operating System?
|
Thedocumentationsays in theWindows notespart:
Also, only future drawing will use the new background color (anything currently drawn in the old background color will stay in the old color). Callingsetbkcolor(0)will change the background color to the current color at index[0]of the palette (rather than always changing the background to black).
You have misunderstood the goal of the function.
|
I am trying to understandsscanfformatting. Can it take arrays of C strings to output to (the code below gives a segfault, which is what prompted the question)? Also, when trying to take only specific characters for a string, is the format%[abc]swhereabcis the set of characters to keep?
```
char s[] = "This is a 345.454 test";
char str[6][256];
double f;
sscanf(s,"%s %*s %*s %f %s",s[0],f,s[1]);
for(int i=0; i<2; i++)
printf("%s\n",s[i]);
```
|
Re-write thesscanfline as follows -
```
sscanf(s,"%s %*s %*s %lf %s",str[0],&f,str[1]);
^address of float variable required
```
And infor loopprint value of arraystr.
See working code here-https://ideone.com/hFpvDJ
|
i'm calling setsockopt function as shown below to turn off the loop back of the same data gram which I send from the server to the client.
```
char loop_back = 0;
if((loop_back_flag = setsockopt(sock, IPPROTO_UDP, IP_MULTICAST_LOOP, (char *)&loop_back, sizeof(loop_back))) == -1)
{
// Print Error message
}
else
{
// print success message with loop_back_flag value
}
```
But what I observe is: when I print the loop_back_flag, it is printing as 255.
Now my understanding is it should either return -1 on error or 0 if success.
What is this 255? am I making any mistake in my setsockopt function call?
|
EDIT: just declareloop_backasint
```
int loop_back = 0;
```
if you look at the man guide,setsockoptreturn anint
|
What does this macro mean or what is the result?
```
#define MOD_TYPE_12 0x11, 0x20, 0x0C, 0x00, 0x02, 0x00, 0x07, 0x0F, 0x42, 0x40, 0x01, 0xC9, 0xC3, 0x80, 0x00, 0x02
```
Is this evaluated to an array?
I couldn't find anything... Maybe because I don`t know what I have to search for ^^
|
All the
MOD_TYPE_12
in your program will be replaced with
0x11, 0x20, 0x0C
There is no specialty with commas
|
I created a for-loop in C, which should work, Eclipse however told me that I used an undeclared variable, here's my code:
```
#include <stdio.h>
int main( int argc, char ** argv ) {
for(int i = 1; i <= 5; ++i) {
printf("i is %d\n", i);
}
return 0;
}
```
according to Eclipse the undeclared variable, ision theprintfline it has been declared in theforstatement right? This code is the exact same code as used in the tutorial I am following, it did work in the video though.
|
In ANSI C (unlike C90/C11) you cannot declare variables in for loop. You unfortunatelly have to to this (or change your compiler to a more modern one, you won't be compatible with the ANSI standard though):
```
int main( int argc, char ** argv ) {
int i;
for(i = 1; i <= 5; ++i) {
printf("i is %d\n", i);
}
return 0;
}
```
|
I have a C-function which returns astructdata type with several items in it (size_t, char*, int, unsigned and other structs). When I call this function there is no output in python. After some googling I think the problem is that I didn't declare the data type in my interface file. But this turns out to be not that easy. What is the right approach:typemapsor just a simpletypedef?
Can someone help me?
|
You need to %include the header first. You need the headers for the nested structs too, in dependency order!
After you've done that, Swig should automatically wrap the struct so that a call to your function will return a proxy object with the appropriate members.
A typemap is for when you want to change Swig's default behaviors.
|
Is there any other method to print names in left justified and the numbers in right justified manner in file without usingprintf("%10d")in c language?
|
How about this?
```
void print_uint32_right_justify(uint32_t num, int width) {
char b[width + 2];
char *p = b + width + 1;
*(p--) = 0;
if(!num)
*(p--) = '0';
while(num > 0) {
*(p--) = '0' + num % 10;
num /= 10;
}
while(p > b)
*(p--) = ' ';
write(1, b + 1, width);
}
```
|
I have a code which looks something like this
```
void * mypointer;
void * array = malloc(sizeof(void*)*10)
loop{
mypointer = malloc(some random size);
memset(mypointer,start,end)
array[i++] = mypointer++
}
```
Now this is throwing an exception that
```
'void*' is unknown size for array and 'void' illeagal with all types
```
EDIT
I tried having**array also but it also throws an exception.
|
Sincearrayis supposed to be an array of pointers, use:
```
void ** array = malloc(sizeof(void*)*10)
```
When you use
```
void* array = ...
```
you cannot indexarraylike you are doing in the following line.
```
array[i++] = mypointer++;
```
Remember that
```
array[k] = *(array+k);
```
array+kcan be evaluated only ifsizeof(*array)can be determined.sizeof(*array)cannot determined ifarrayis of typevoid*.
|
When I run my program within Code::Blocks it works fine. But when I build it and then click on the executable I get an error saying
The program can't start becauselibgcc_s_dw2-1.dllis missing from your computer. Try reinstalling the program to fix this problem.
I'm not to sure why that happens I did everything that all the tuts that I have watched to install Code::blocks have done.
|
You should copylibgcc_s_dw2-1.dll(it should be located somewhere similar toC:\MinGW\binorC:\Program Files\CodeBlocks\MinGW\bin) into the same folder as the.exe.
|
I just came to know aboutbool. It seems that bothboolandwhile (true)orwhile (1)are the same endless function. Doesboolhave any advantages overwhile (true)orwhile (1)?. I can't see any difference.
bool:
```
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(void)
{
bool keep_going = true; // Could also be `bool keep_going = 1;`
while(keep_going)
{
printf("This will run as long as keep_going is true.\n");
// keep_going = false;
// Could also be `keep_going = 0;`
}
printf("Stopping!\n");
return EXIT_SUCCESS;
}
```
|
While(true) is an infinite loop. Boolean is a data type with true and false values. Bool is used in case if you want to change to false at any stage. So you can change the value of bool inside for loop to stop loop.
|
```
addr4 = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
internal_addr = inet_netof(*addr4);
printf("IPv4 MASK %08x \n",internal_addr);
```
I have the above code. It is printing the IPv4 MASK as
```
IPv4 MASK 00ffffff
```
I am assuming this represents255.255.255.0. Is that correct assumption?
I want to convert that to24(an integer in CIDR notation)
|
Per your desire to convert it to the number of mask bits (CIDR notation), just count the number of one bits in the mask.
Just loop through the 32-bit, unsigned integer (0x00ffffff), checking if it is greater than 0, if it is greater than 0 add 1 to your answer, then divide the unsigned integer by 2 (or shift it right 1 bit).
|
I would like to get (almost) exactly the same result of htmlSAXParseDoc in Java, for an Android mail parsing module.
Specifically, sincemailcore 2uses htmlSAXParseDoc to "flatten" html (in method "flattenHTMLAndShowBlockquoteAndLink"), with certain state passed in as parameter. I wonder if there are similar method in Java libraries, such as in Jsoup?
Thank you!
|
ok it looks like Android does have libxml2 included in its core package. Will go from there first.
|
Please take a look at this screenshot:
As you can see, the"Executable modules"and"Threads"child windows are free to roam about in the sandbox-like"Themida"parent window, and if they get dragged past the edge the overflow simply gets hidden. How can I create this effect?
|
That is aMultiple Document Interface(MDI) application. The containing window, with the dark grey background is the MDI client window, and the windows inside are the MDI child windows.
The use of MDI has been discouraged by Microsoft for many years so you may wish to think twice about using it in a new application.
|
```
void main()
{
int u, t, h ;
printf("\n Enter a number (with 3 digits) \n");
printf("\n Enter the unit digit number \n");
scanf("%d",&u);
printf("\n Enter the tenth digit number \n");
scanf("%d",&t);
printf("\n Enter the hundredth digit number \n");
scanf("%d",&h);
}
```
I want them in order like if user inputuas 1,tas 2 andhas 3, then after concatenation it should print 321 together as one integer number.
|
With this solution the final string stored instris portable throughout your program.
```
char str[16];
sprintf(str, "%d", (h*100) + (t*10) + u);
printf("%s\n", str);
```
|
I just started migrating to Mac OS X and I wanted to port a couple of tools I wrote for Windows. The question is what is the equivalent for the following:
```
CreateFile()
CreateFileMapping()
MapViewOfFile()
```
I would appreciate if someone could either guide me to a place where I can read about it or if there is some sort of a quick guide for such common questions/problems or simply answer my question.
The language of choice is C/C++ for a command line tool.
|
The equivalent ofCreateFilewould beopen. The latter two steps for mapping a file,CreateFileMappingandMapViewOfFile, are condensed into one step on Mac OS X, with themmapfunction.
|
I'm writing a library that works withHWNDandHDCunder the hood.ReleaseDCtakes aHWNDas a parameter, but what if the window has already been destroyed? Does Windows free theHDCautomatically, or does this cause a resource leak?
|
When testing on Windows 10, it appears that a DC retrieved withGetDCis automatically released when the window is destroyed.
An infinite loop that creates a window, retrieves a DC, and destroys the window had no increase of memory usage after the first iteration. To make sure some internal reference count wasn't being incremented without also being decremented, I changed the loop to repeatedly get a DC from the same window. This not only increased memory usage with each iteration, but also made my entire system slow and unstable.
|
I am trying to inverse a hexadecimal value. The result is wrong, however.
```
#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>
int main(void)
{
uint32_t acc = 0xBBD1;
printf("0x%X", htons(~acc)); // prints 0x2E44
}
```
Let's do the inversion by hand:
```
0xBBD1 = 1011 1011 1101 0001
~1011 1011 1101 0001 =
0100 0100 0010 1110
0100 0100 0010 1110 = 0x442E
```
This means, the code should actually print0x442Einstead of0x2E44.
What's wrong with my code?
|
Technically, no. But why are you usinghtons? It changes the endianess of a 16 bit datum to big-endian (that is, network byte order). First is your variable not 16 bit but 32 bit, souint16_t acc = 0xBBD1would be more appropriate. Second, as your on a little-endian machine, the bytes are exchanged, hence the output.
|
installing festival speech synthesis system fromhttp://festvox.org/...directly by running general script.
Facing below given problem .....this problem will effect my working on festival framework or not ?????
```
eps.c: In function ‘getd’:
eps.c:142:7: warning: ignoring return value of ‘fscanf’, declared with attribute warn_unused_result [-Wunused-result]
fscanf(fp, "%d %d", x, y);
^
```
|
Read documentation offscanf(3). You should use the returned count of successfully scanned items, e.g. code something like:
```
int x = 0, y = 0;
if (fscanf(fp, "%d %d", &x, &y) < 2) {
fprintf(stderr, "missing numbers at offset %ld\n", ftell(fp));
exit(EXIT_FAILURE);
}
```
so you could improve theeps.cfile (and perhaps submit a patch and/or a bug report upstream).
|
```
idx x, z ;
for (x = 0 ; x < k ; ++x) {
if (mots[x].mot) {
printf("%s :", mots[x].mot) ;
//Below not working properly how to write all my refs ?
// printf("%i ", mots[x].refs -> cdr ->ref);
// while (mots[x].refs -> cdr) printf("%i ", mots[x].refs -> ref);
printf("\n") ;
```
How to iterate properly on my struct in order to display each refs of mots[x] ?
I hope the problem is clear enough, thanks in advance
|
```
if (mots[x].mot) {
printf("%s :", mots[x].mot) ;
struct node *node = mots[x].refs;
while (node) {
printf("%i ", node->ref);
node = node->cdr;
}
printf("\n");
}
```
|
This question already has an answer here:The program control flow doesn't work as expected(1 answer)Closed8 years ago.
I'm learning C and to get something done I need to ask the user to input 2 characters, like in this example: "b [enter] t". and store them in two different variables, but my code is not working that way.
Why doesn't this work? Is there a simple way to fix it?
```
void main(void){
int a,b;
printf("Input a char");
a=getchar();
printf("Input second char");
b=getchar();
printf("Characters entered: %c and %c.", a, b);
return 0
}
```
|
The problem is thatawill be set to'b'butbwill be set to'\n'(fromEnter). If you want sane user input, always read a whole line first (e.g. withfgets), then process it (e.g. take the first character or convert it to a number, etc).
|
I'm trying to solve a problem where I want a bash script to call acprogram and a value from thecprogram to be returned to the bach script and be stored in a variable.
Here is an example (code isn't really written properly):
Bash script:
```
$value = ./foo
echo $value
```
C program:
```
int main() {
//Have a value here that is returned to the variable 'value' in the bash script.
return 0;
}
```
Is this possible?
|
You can get the return value of the last program you executed by using$?or you can print the value to stdout and then capture it.
```
#include <stdio.h>
int main()
{
printf("my_value");
return 0;
}
```
and then in bash do
```
value=$(./my_program)
echo $value
```
the result will bemy_value
|
I remember being constantly told that the C preprocessor does not know C. It doesn't know about types, doesn't remember declared symbols, etc. If that's the case, how can it possibly act differently based on the type of its parameter?
|
The_Genericfeature is not processed by the preprocessor. It is aprimary expressionthat is treated with higher preference than most other expressions.
|
So I am starting to learn C. I am learning from the classic K&R book. In the book they have the following function:
```
/*squeeze: delete all c from s */
void squeeze(char s[], int c)
{
int i, j;
for (i = j = 0; s[i] != '\0'; i++)
if (s[i] != c)
s[j++] = s[i];
s[j] = '\0';
}
```
My question is this: does squeeze() actually change the number of chars in s[]?
It seems that all it does is "cut off" the rest of the string by adding the null character. Do other values exist past the '\0' in the array?
|
A string in c is just an array of characters with a null terminator,\0, signifying the end. Characters can still exist after the null terminator, but any functions using c strings, ie.printforstrcpywill use the null terminator to mark the end, so it will effectively be treated as if there were nothing after the\0.
|
Is there anything similar to Java's Integer.MIN_VALUE in C, which gives the smallest possible value of a signed integer, or do I just have to hard code the value myself?
|
You can uselimits.hhttp://en.cppreference.com/w/c/types/limits
I think this is what you're looking for:INT_MIN = minimum value for an int
|
Why is this code not working properly?
The intent of this code is to generate and print two random numbers separately
as many times as user choose.
M.T.
Thanks.
```
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define random(x) rand() % x
#define randomize srand((unsigned)time(NULL))
int i=0;
int j=0;
int x=0;
int y=0;
int main(void)
{
printf("insert number of loops:");
scanf("%d",x);
for(y=0;y=x;y++)
{
randomize;
i = random(51);
j = random(51);
printf("%d\n",i);
printf("%d\n",j);
}
return 0;
}
```
|
You are callingsrandmore than once. Placerandomize;outside theforloop. Another problem is with the statement
```
scanf("%d",x);
```
you forget to place&beforex.
Also You need to correct the loop conditiony = xtoy < xas mentioned in comment by @Cool Guy.
|
```
FILE *fp = fopen("./con", "w");
char *s = "hello!";
fwrite(s, sizeof(char), strlen(s), fp);
fclose(fp);
return 0;
```
If my file name is "con", thenfwrite()will work just likeprintf().
How does it work?
|
Windows/DOS has a number ofreserved filenamesincluding CON, PRN, AUX, CLOCK$, NUL
COM1, COM2, COM3, COM4 LPT1, LPT2, LPT3, LPT4 and others.
CONis the standard console (output), so that is where the data went.
Credits: @BLUEPIXY @Joachim Pileborg
|
Is there a way to hide the Scrollbar thumb, for example in this image Notepad does not have a thumb for both Scrollbars:
I have tried to setSCROLLINFO.nPageto0but it did not work.
Edit:I am talking about a control Scrollbar.
|
When you callSetScrollInfo, set theSIF_DISABLENOSCROLLflag in thefMaskfield. The scrollbar will then be disabled (and the thumb hidden) if the scroll bar's parameters make the scroll bar unnecessary.
However that technique only works for the non-client window scrollbars. If you want to disable a control scrollbar you need to do it yourself usingEnableWindow().
|
What is the difference in += and normal add
```
a = a + b;
a += b;
```
what is the different in above two lines?Is there any increase in CPU cycles for "+=" operator?Which would be the preferable method of coding.?
|
Beside single evaluation of first operand, there is second difference, that occurs whenbis an expression, involving operators with lower precedence. For instance:
```
int a = 1;
a += 0 || 1;
```
yields two, while:
```
int a = 1;
a = a + 0 || 1;
```
stores one intoa. The equivalent of former statement would be:
```
a = a + (0 || 1);
```
|
```
FILE *fp = fopen("./con", "w");
char *s = "hello!";
fwrite(s, sizeof(char), strlen(s), fp);
fclose(fp);
return 0;
```
If my file name is "con", thenfwrite()will work just likeprintf().
How does it work?
|
Windows/DOS has a number ofreserved filenamesincluding CON, PRN, AUX, CLOCK$, NUL
COM1, COM2, COM3, COM4 LPT1, LPT2, LPT3, LPT4 and others.
CONis the standard console (output), so that is where the data went.
Credits: @BLUEPIXY @Joachim Pileborg
|
Is there a way to hide the Scrollbar thumb, for example in this image Notepad does not have a thumb for both Scrollbars:
I have tried to setSCROLLINFO.nPageto0but it did not work.
Edit:I am talking about a control Scrollbar.
|
When you callSetScrollInfo, set theSIF_DISABLENOSCROLLflag in thefMaskfield. The scrollbar will then be disabled (and the thumb hidden) if the scroll bar's parameters make the scroll bar unnecessary.
However that technique only works for the non-client window scrollbars. If you want to disable a control scrollbar you need to do it yourself usingEnableWindow().
|
What is the difference in += and normal add
```
a = a + b;
a += b;
```
what is the different in above two lines?Is there any increase in CPU cycles for "+=" operator?Which would be the preferable method of coding.?
|
Beside single evaluation of first operand, there is second difference, that occurs whenbis an expression, involving operators with lower precedence. For instance:
```
int a = 1;
a += 0 || 1;
```
yields two, while:
```
int a = 1;
a = a + 0 || 1;
```
stores one intoa. The equivalent of former statement would be:
```
a = a + (0 || 1);
```
|
If I mention
```
int ar[100]={1,1};
```
and I want to know the number of elements present in it rather than the size of it, what commands should I use?
|
In case of anarray, the size is always the number of elements multiplied by the size of each element. Neither of them (number of element or size) vary, once it is defined.
If you meant to find out themeaningful(to you) elements present in the array, well, you need to have asentinel valuesomewhere (thereby marking the end of valid data entry), and using a loop, you need to count the valid elements yourself.
|
Closed. This question isopinion-based. It is not currently accepting answers.Want to improve this question?Update the question so it can be answered with facts and citations byediting this post.Closed8 years ago.Improve this question
I am a student, at the moment I finished my first language C fundamentals course. I like boards like Arduino, Raspberry etc etc...
In particular I prefer Raspberry but the main programming language is Python. As I already say, I know only C.
Which boards do you suggest me for begin?
Thanks
|
It sounds like you want to use Raspberry Pi to control other hardware using the general purpose I/O pins. In this case there are libraries for bothPythonandCavailable to access those pins.
|
I am getting "variable may be used before being set" when I create a pointer to a structureexample *e. If I use a variable insteadexample e, I am not getting the error. Is this because I haven't allocated memory for the pointer?
```
typedef struct example {
int a;
}example;
void test (){
example *e;
e->a=1;
printf_all("val %d",e->a);
}
```
|
eis NOT pointing to anything. You are using an uninitialized pointer. You "set" through an invalid pointer, and then trying to access it.
Your pointer should point to anexampleinstance. For example:
```
example exampleInstance;
example * examplePointer = &exampleInstance;
```
|
I'm trying to celebrate 10,000,000 questions on StackOverflow with a simple console application written in C, but I don't want to waste any memory. What's the most efficient way to store the number 10,000,000 in memory?
|
The type you're looking for isint_least32_t, fromstdint.h, which will give you the smallest type with at least 32 bits. This type is guaranteed to exist on C99 implementations.
Exact-width typedefs such asint32_tare not guaranteed to exist, though you'd be hard pressed to find a platform without it.
|
Let me be judged as a Noob in programming, I have been learning obfuscated way of programming in c/c++, as the c compiler compiles a statement from the right hand side towards the left hand side.
I have the following code:
```
int main(){
int x=5, y=20, z=1;
int k = x > y < z;
printf("%d", k);
return 0;
}
```
The output returned is1, Does this means thatx > y < z=(x>y) < zorx > y < z=x > (y<z)
I would love if someone would give me link to work on these skills.Thanks and Regards.
|
Changez=-1orx=0and find out. Also changeint main()to the more correctint main ( void )
Changingz = -1will ouput0, whereaskwill be1if you assign itx > y == zifz = 0. So in short:
```
k = x > y < z;
```
is the same as writing
```
k = (x > y) < z;
```
left-to-right.
|
I'm doing a very basic printout of scientific notation.
But, it appears to me its not working and I can't figure out why?
Code:
```
size_t result = 0;
printf("%e \n",result);
```
Value it prints is below:
```
1.278341e-307
```
What would be right way to do scientific notations?
|
If you use a floating-point printf format code, like%e, the matching argument must be adouble. But you are passing it an integer (size_t).
Printf does not know the types of its arguments, so you have to tell it what they are by using the correct format code. If you lie to it, you will get undefined results.
And if you are using gcc or clang, please always use the-Wallcommand-line option andread the warnings. That will save all of us a lot of trouble.
|
I'm doing a very basic printout of scientific notation.
But, it appears to me its not working and I can't figure out why?
Code:
```
size_t result = 0;
printf("%e \n",result);
```
Value it prints is below:
```
1.278341e-307
```
What would be right way to do scientific notations?
|
If you use a floating-point printf format code, like%e, the matching argument must be adouble. But you are passing it an integer (size_t).
Printf does not know the types of its arguments, so you have to tell it what they are by using the correct format code. If you lie to it, you will get undefined results.
And if you are using gcc or clang, please always use the-Wallcommand-line option andread the warnings. That will save all of us a lot of trouble.
|
Is it possible to read a character and an integer in one time?
Like this:
```
char name[32];
int age;
printf("Give name and age: ");
scanf("%s%d%*c", name, &age);
```
It blocks all the time.
|
UPDATED:You only accept input but not printing any thing. See the below code (working and tested)
```
#include <stdio.h>
int main(void) {
char name[32];
int age;
printf("Give name and age: ");
scanf("%31s%d", name, &age);
printf("Your name is %s and age is %d",name,age);
}
```
intput: Shaz 30Output: Your name is Shaz and age is 30
|
My goal is to parse potentially garbled ASCII data containing text and numbers. So far I've been doing fine with getting a pointer to numbers within the text withstrcmpand hard-coded pointer arithmetic and then converting them withstrtol, but I feel there must be a better way.
Is there a function with the effect ofscanfwhich takes a pointer to memory instead of input stream?
|
You'll be wantingsscanf. Note that it does expect a null-terminated string.
|
From a Fortran Code, I intend to run a C code (to read a file) and fetch the read information.
The main program is the Fortran code, which uses a function written in C to do the processing.
In this C code, is it necessary to run a main function?
|
If Fortran only calls the C function, then the C code does not need amain()function.
Themain()function of C is the program entry point. The system loads the .exe, transfers control to the startup code, which address is mentioned in the .exe file (the startup code is calledcrt, C run-time start-up). The run-time startup does initialization and then transfers control to the user code. The user code entry point ismain().
Since Fortran is the main program, no C run-time start-up is needed and so nomain()is needed.
|
The ISO C Standard requiresCHAR_BITto be at least 8.
With POSIX mandatingCHAR_BITbe equal to 8, and (almost?) all networking and communication standards usingoctets, is thereanycontemporary C implementation whereCHAR_BIT> 8?
(Note: I'm not interested in historic computer architectures using 18 or 36 bit words. It's genuinely a question about C as it is used today on current hardware; think systems with a C99 or later implementation).
|
TMS320C28xDSP from Texas Instruments has a byte with 16 bits.
Documentationfor the compiler specifiesCHAR_BITas 16 on page 101.
This appears to be a modern processor (currently being sold), compilers supporting C99 and C++03.
|
I have a string which captures details stored indata
User 6%, System 18%, IOW 0%, IRQ 0%
What i am doing is
sscanf(data,"User %d,System %d,IOW %d,IRQ %d",&user,&sys,&iow,&irq);
I am getting wrong output . why ?
Is is like i am missing something ?
|
You left out the%symbols and some spaces - try:
```
sscanf(data,"User %d%%, System %d%%, IOW %d%%, IRQ %d%%",&user,&sys,&iow,&irq);
```
|
My PC configuration is
Intel Core i3-2100 CPU @3.10GHz
Windows7 64 bit
But when I'm executing below code why it's printing 1000?
```
#include<stdio.h>
#include<conio.h>
#include<time.h>
main()
{
printf("Clock %d",CLOCKS_PER_SEC);
getch();
}
```
The actual clock speed should be around 3.1x10^12 per sec right?
|
Clock ticks are units of time of a constant but system-specific length, as those returned by functionclock.
It has nothing to do with the processor speed.
|
I have the following linked list:
```
struct node {
int d;
struct node *next;
};
int main()
{
struct node *l = 0;
struct node *k = l;
k = malloc(sizeof(struct node));
/* l->d = 8; */
return 0;
}
```
Why is the commented code wrong to use? I don't understand why the memory isn't allocated for the node that ``l points to sincekpoints to the same node asland I used thek-pointer to allocate memory for it.
|
Let's take it apart. Look at the comments
```
struct node{
int d;
struct node * next;
};
int main(){
struct node * l = 0; // Now l = 0 (or NULL)
struct node * k = l; // Now k=l=0
k = malloc(sizeof(struct node)); // Now k=<some address allocated>
/*
l->d = 8; // But l is still 0
*/
return 0;
}
```
So the commented code is trying to dereference a NULL pointer.
|
My goal is to parse potentially garbled ASCII data containing text and numbers. So far I've been doing fine with getting a pointer to numbers within the text withstrcmpand hard-coded pointer arithmetic and then converting them withstrtol, but I feel there must be a better way.
Is there a function with the effect ofscanfwhich takes a pointer to memory instead of input stream?
|
You'll be wantingsscanf. Note that it does expect a null-terminated string.
|
From a Fortran Code, I intend to run a C code (to read a file) and fetch the read information.
The main program is the Fortran code, which uses a function written in C to do the processing.
In this C code, is it necessary to run a main function?
|
If Fortran only calls the C function, then the C code does not need amain()function.
Themain()function of C is the program entry point. The system loads the .exe, transfers control to the startup code, which address is mentioned in the .exe file (the startup code is calledcrt, C run-time start-up). The run-time startup does initialization and then transfers control to the user code. The user code entry point ismain().
Since Fortran is the main program, no C run-time start-up is needed and so nomain()is needed.
|
This is a question for deeper understanding.
Let's say I have the following code:
```
#define DEF 1,2,3
#if (DEF > 3)
#endif
```
If I am right the if should always be true, as 1 and 2 are Expressions that have no affect and only 3 will be checked. (This should at least be true in normalC/C++-code)
But is that right or would there be any Reason why I should think about 1 and 2, too? I saw it in some code and I am not really sure if this could have any sense or affect.
|
DEFwill expand to give#if (1, 2, 3 > 3). Because,has low precedence, the only expression that "does" anything is3 > 3which, of course, is false.
|
Of course I know that we don't cast the result ofmalloc(), but what aboutmkl_malloc()?
Here is theprototype:void* mkl_malloc (size_t alloc_size, int alignment);
It has the same return type asmalloc(), as you can see:void* malloc (size_t size);
As a result, I would not cast the result, for thesereasons. But the Intel people do, as you can seehere, which makes me fear that I am missing something.
Does anybody know?
|
Casting the result is superfluous and doesn't make much sense, so you shouldn't do it for that reason. But it is not super-important, it is a minor trifle.
The whole "cast the result of malloc" debate has gone out of proportion on Stack Overflow, and the most valid concerns of why you shouldn't went obsolete 16 years ago when implicit int was removed from the C language.
|
What's the difference between (1)
```
char s[5] = {'a', 'b', 'c', 'd', '\0'};
char s2[strlen(s) + 1];
strcpy(s2, s);
```
And (2)
```
char s[5] = {'a', 'b', 'c', 'd', '\0'};
char *s2 = malloc(strlen(s) + 1);
strcpy(s2, s);
```
In what situation should you use each of these? Can you only use the first one when you are certain that the arraysis of a static size?
|
In case 1,
```
char s2[strlen(s) + 1];
```
s2is an array. In case 2,
```
char *s2 = malloc(strlen(s) + 1);
```
s2is a pointer.
FWIW, the first approach won't work if the compiler does not supportVLA.
As per the latest standard,C11, VLA is anoptionalfeature which compiler(s) is (are) notbound tosupport. The second approach, is an integral part of C standard (library) and available without anyadditional requirementof the compiler support.
|
I have a situation where i have to callwake_up_interruptible()on a wait queue, which may not holding any process to sleep. Is it ok to callwake_up_interruptible()on an unused wait queue ?
|
Yes, as long as the queue is initialized you are fine.
|
I am creating cross platform code(Win and Linux) and in windowsVS the file path is usually used as
```
"Folder1\\folder2\\file"
```
where as in gcc it should be '/' in the place of '\'
```
"Folder1/folder2/file"
```
Can anyone suggest a way to use that or is there any #define macro that I can use in assigning this.
Although I have tried using
```
#if __linux__
#define // '\'
#endif
```
But its throwing an error. Somebody pls help!!
|
Use/on both platforms. The C APIs for Windows accept both/and\.
|
Consider the following code:
```
#define P1(x) x+x
#define P2(x) 2*P1(x)
int main()
{
int a = P1(1) ? 1 : 0;
int b = P2(a)&a;
return 0;
}
```
Now, I thought that the compiler first replacing the macros with their values and soint b = 2*a+a&a;(and sincea=1thenb=3). Why isn't it so?
|
This is because&has lowerprecedencethan that of addition+operator. The grouping of operands will take place as
```
int b = ( (2*a + a) & a );
```
Therefore,(2*a + a) = 3and3 & 1 = 1(011 & 001 = 001).
|
I have searched for that several times but I have no obvious answer
I want to make a C function that takes a variable as an argument and then uses that argument to replace a placeholder in another template file in the form like that
Port %PORT%
I need that when that function get called the %PORT% is replaced with the parameter being passed ( this placeholder is in another file )
any hint for that ?
|
Have you considered usingsed? It is available on most linux systems, you should be able to accomplish what you want using this examples, which reads template file tmpl.txt and creates a file called specific.txt where the value %Port% is replaced with a 4242 which was saved in a variable PVAR:
tmpl.txt
```
Port %PORT%
```
code:
```
PVAR=4242
sed "s/%PORT%/$PVAR/" tmpl.txt > p4242.txt
```
p4242.txt:
```
Port 4242
```
|
What does this expression mean:
```
typedef char foo [FOO];
```
I am just struggeling with the meaning of the expression between the squared brackets.
|
It readsfoois the type of an array ofFOO-manycharelements. In this case,FOOis a constant, defined somewhere as#define FOO 100
```
typedef int pair[2]; // Pair is an array of two ints.
```
|
This is a question for deeper understanding.
Let's say I have the following code:
```
#define DEF 1,2,3
#if (DEF > 3)
#endif
```
If I am right the if should always be true, as 1 and 2 are Expressions that have no affect and only 3 will be checked. (This should at least be true in normalC/C++-code)
But is that right or would there be any Reason why I should think about 1 and 2, too? I saw it in some code and I am not really sure if this could have any sense or affect.
|
DEFwill expand to give#if (1, 2, 3 > 3). Because,has low precedence, the only expression that "does" anything is3 > 3which, of course, is false.
|
Of course I know that we don't cast the result ofmalloc(), but what aboutmkl_malloc()?
Here is theprototype:void* mkl_malloc (size_t alloc_size, int alignment);
It has the same return type asmalloc(), as you can see:void* malloc (size_t size);
As a result, I would not cast the result, for thesereasons. But the Intel people do, as you can seehere, which makes me fear that I am missing something.
Does anybody know?
|
Casting the result is superfluous and doesn't make much sense, so you shouldn't do it for that reason. But it is not super-important, it is a minor trifle.
The whole "cast the result of malloc" debate has gone out of proportion on Stack Overflow, and the most valid concerns of why you shouldn't went obsolete 16 years ago when implicit int was removed from the C language.
|
What's the difference between (1)
```
char s[5] = {'a', 'b', 'c', 'd', '\0'};
char s2[strlen(s) + 1];
strcpy(s2, s);
```
And (2)
```
char s[5] = {'a', 'b', 'c', 'd', '\0'};
char *s2 = malloc(strlen(s) + 1);
strcpy(s2, s);
```
In what situation should you use each of these? Can you only use the first one when you are certain that the arraysis of a static size?
|
In case 1,
```
char s2[strlen(s) + 1];
```
s2is an array. In case 2,
```
char *s2 = malloc(strlen(s) + 1);
```
s2is a pointer.
FWIW, the first approach won't work if the compiler does not supportVLA.
As per the latest standard,C11, VLA is anoptionalfeature which compiler(s) is (are) notbound tosupport. The second approach, is an integral part of C standard (library) and available without anyadditional requirementof the compiler support.
|
I have a situation where i have to callwake_up_interruptible()on a wait queue, which may not holding any process to sleep. Is it ok to callwake_up_interruptible()on an unused wait queue ?
|
Yes, as long as the queue is initialized you are fine.
|
I am creating cross platform code(Win and Linux) and in windowsVS the file path is usually used as
```
"Folder1\\folder2\\file"
```
where as in gcc it should be '/' in the place of '\'
```
"Folder1/folder2/file"
```
Can anyone suggest a way to use that or is there any #define macro that I can use in assigning this.
Although I have tried using
```
#if __linux__
#define // '\'
#endif
```
But its throwing an error. Somebody pls help!!
|
Use/on both platforms. The C APIs for Windows accept both/and\.
|
```
int main()
{
int a=10,b=11,c=13;
*((a)?&b:&c)=a?b:c;
printf("%d %d %d ,"a,b,c);
return 0;
}
```
I don't understand the output of*((a)?&b:&c)=a?b:c;statement
|
Lets comprehend this monster:
*((a)?&b:&c)=a?b:c;
Take the first evaluated part:(a)?&b:&c: simply means ifais not zero then get the address ofb, otherwise get the address ofc.
Second evaluated part:
*(...)dereferences an address to the actual value. In this case this evaluates to*&bwhich is justb(*is the inverse of&).
The right hand sidea?b:cevaluates tob(as it does at the left hand side).
i.e. you just wrote downb = b;)
|
I want to define a specific memory region in the STM32 micro where to store some strings. I'm using IAR compiler but I don't find a simple example that can help me to create the region in the correct way using the icf file. How can I create the region and use this region in the code? Thanks
|
I found this solution:
In the icf file I define the memory region in this way:
```
define region LANGUAGE_region = mem:[from 0x080FB000 to 0x080FC000];
"LANGUAGE_PLACE":place at start of LANGUAGE_region { section .LANGUAGE_PLACE.noinit };
```
I will fill this region with an external srec file using a programmer.
To test the region with a simple program (using an integer) I use this declaration:
In the header:extern const unsigned int mydata @".LANGUAGE_PLACE.noinit";In the C file:const unsigned int mydata;
In the debugger I can see the correct address of mydata constant at 0x0800FB000
|
```
curl_easy_setopt(curl, CURLOPT_URL, "127.0.0.1:8081/get.php");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS,"pulse=70 & temp=35" );
```
this above code run successfully but when I pass this
```
int pulsedata = 70;
int tempdata = 35;
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "pulse=pulsedata & temp = tempdata");
```
when I run this above line it give me error
how can I pass this pulsedata and tempdata ??
|
A possible C solution:
```
char sendbuffer[100];
snprintf(sendbuffer, sizeof(sendbuffer), "pulse=%d&temp=%d", pulsedate, tempdata);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, sendbuffer);
```
|
I am making an uno card game with structure of card with fields:
```
struct card
{
int rank
char *color
char *action.
}
```
I am able to make it sort by color with insertion. I wonder how could I first sort the array of uno card by color, then sort the rank of each color.
|
Thanks to Bo Persoson, this is the solution to my question
```
void sort(card *a, int length) {
int j;
for (int i = 1; i < length; i++) {
j = i;
while (j > 0 && a[j].color < a[j - 1].color || (a[j].color == a[j - 1].color && a[j].rank < a[j - 1].rank)) {
swap(&a[j], &a[j - 1]);
j--;
}
}
```
}
|
I need to somehow enable XML file transfer in the way that some machine, which generates a XML file sends the XML file through HTTP to another client. This other client would be based on C, receive the XML file and process it.
Is this possible in any way? I only found results for sending XML files to a HTTP server using some URL. I guess I'd have to implement my own HTTP server in my C application? Any ideas?
|
maybe you can use libcurl
here is a http POST example:http://curl.haxx.se/libcurl/c/http-post.html
on the receiving computer has to be a listening socket. here is a socket example:http://www.codeproject.com/Articles/586000/Networking-and-Socket-programming-tutorial-in-C
this socket takes the incoming data for later processing...
|
```
#include<stdio.h>
int main()
{
char ch;
for(ch='0';ch<=127;ch++)
printf("%c %d",ch,ch);
return 0;
}
```
How ever this becomes an infinite loop when executed. I want to know exact reason behind it? Is type casting to and fro from int to char the reason?
Also one small question
Whether all files having .c extension are required to havemain()in all of them??
|
Here, you are comparingchartoint
```
for(ch='0';ch<=127;ch++)
```
int value of a char can range from 0 to 255 or -128 to 127, depending on implementation.
In your case, acharis asigned char, which can hold the value of a range to -128 to +127. Therefore once the value reaches 127 in your case, it overflows and you get negative value and loop continues forever, because it's value will never become more than 127.once it reaches 127, in next iteration the value will be -128, and the loop continues.
You can useunsigned char ch;
|
I'm trying to send an encrypted message in a simple server-client chat program.
This is thesend()call:
```
int send(int sockfd, const void *msg, int len, int flags);
```
Can I pass anintarray as*msg?
|
I think you can use thesend()system call. But be aware, that thelenis thelength of the message in bytes. So i think for an array of 5int. You need to specify thelenas5*(sizeof(int)).
Additionally, on the receiving side, you need to interpret it accordingly.
As Naveen pointed out, a more detailed answer to your question is already presenthere.
|
it seems that escaped characters passed in write() don't work (at least) properly.
```
printf("test");
printf("\r1234);
```
return
```
123
```
as expected, but
```
printf("test");
write(1, "\r1234, 5);
```
return
```
1234test
```
so the line is not overwritten
I would like to know how to erase/overwrite a line in C (i am on linux btw)
Thank you
|
Try flushing the output stream:
Code:
```
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("test");
fflush(stdout);
write(1, "\r1234", 5);
return 0;
}
```
Output:
```
1234
```
|
I am using Code Composer Studio (CCS) for developing an embedded application. It is very helpful if I can use printf to print something on console of CCS. But it is not working. I includedstdio.h. The Code compiles. When I run, I see data in putty, but I see nothing in CCS. Is is possible to see something in console like in eclipse?
|
this link:http://processors.wiki.ti.com/index.php/Printf_support_for_MSP430_CCSTUDIO_compiler
contains the details on how to use printf() (per some compiler settings in the CCS) to display the results of printf() statements on the CCS console
in the 'properties' window, in the 'Library Function Assumptions' sub page, in the 'Level of printf() support required' select 'full'
|
i want to make statements in for loop condition based on another condition. E.g. Given two numbers a and b, if a>b I want to put condition of i-- and otherwise i++. This can be done with two for statements in if, but I want to do it with one for loop only.
something like this..
```
for(i=a; if(a>b),put i>=b here else put i<=b; if(a>b) put i-- here else i++)
{
some code...
}
```
I tried this :
```
for( i = a; ( a > b ? i >= b : i <= b ); ( a > b ? i-- : i++ ) )
{
...
}
```
But it didn't worked.
Can I get some some help regarding it?
UPDATE : This was not working on some online compiler. Same code works fine in local machine. Solved.
|
This was not working on some online compiler. I tried to use it in local machine in codeblocks. It is working as intended. I don't know why it was not working on online compiler.
|
A code snippet is as follows:
```
struct wer
{
unsigned int a:5;
unsigned int:0;
unsigned int b:3;
unsigned int c:2;
unsigned int:0;
}v;
```
I know that all of these are packed bit fields but how to find the storage which would be needed for v.
|
You can get the storage required forvusingsizeof(v).
|
I am not trying to use a DPI call, but a simple Verilog program which internally uses its PLI to call a function written in C language. I don't know about static linking. I am using edaplayground.
Can anyone tell me which simulator should I use and switch should I pass to link both Verilog and C? Should I include the C file in the Verilog?
The sample code is as follows
```
// C function implementation
#include <stdio.h>
void hello() {
printf ("\nHello world\n");
}
// SV function call
module sv_pli ();
initial begin
$hello;
#10 $finish;
end
endmodule
```
I would like to know if there was any need to register the pli since currently the pli call hello is not detected.
|
I put your C code in a new file named test.c, and added SV-DPI to your Verilog code, removed dollar sign from $hello task to become a DPI call.
See the simulator output and it should be the expected result from your sample code.
|
```
int var = (1 == 1) ? (5) : (10);
```
This outputs5, which is correct.
```
int var = 100 + (1 == 1) ? (5) : (10);
```
this again outputs5. Why?
I know I can fix the problem with adding braces around the entire ternary statement, but that doesn't explain what happens with the addition and why it behaves like that on a first place.
|
In C every non-zero value is “true”, here the value of100 + (1 == 1)is101, which is also “true”, therefore(5)is selected. Since?:has a very low precedence, the parentheses should be((1==1) ? 5 : 10)to have the effect you want.
|
I have this simple code, and can't figure out how to allocate memory for scanf
```
char* string= (char*) malloc (sizeof(char));
printf("insert string: \n");
scanf("%s", string);
free(string);
```
doesn't matter how many chars my string is, it's an error. I want to use malloc for the char*, any way to set memory for scanf.
|
You are just request 1 byte. You need to allocate more than that if you want store more than just the0terminator in the string:
```
char* string= malloc (256); //256 bytes, arbitrary value...
```
I removed:
sizeof(char)because it's always guaranteed to be1.(char*)because casting the return value ofmalloc()is needless.
I would also recommend usingfgets()instead ofscanf()to prevent overflowing the buffer. The same could be done withscanf()by specifying the length in the format string. But I personally prefer usingfgets()and parsing usingsscanf()if necessary.
|
i want to make statements in for loop condition based on another condition. E.g. Given two numbers a and b, if a>b I want to put condition of i-- and otherwise i++. This can be done with two for statements in if, but I want to do it with one for loop only.
something like this..
```
for(i=a; if(a>b),put i>=b here else put i<=b; if(a>b) put i-- here else i++)
{
some code...
}
```
I tried this :
```
for( i = a; ( a > b ? i >= b : i <= b ); ( a > b ? i-- : i++ ) )
{
...
}
```
But it didn't worked.
Can I get some some help regarding it?
UPDATE : This was not working on some online compiler. Same code works fine in local machine. Solved.
|
This was not working on some online compiler. I tried to use it in local machine in codeblocks. It is working as intended. I don't know why it was not working on online compiler.
|
A code snippet is as follows:
```
struct wer
{
unsigned int a:5;
unsigned int:0;
unsigned int b:3;
unsigned int c:2;
unsigned int:0;
}v;
```
I know that all of these are packed bit fields but how to find the storage which would be needed for v.
|
You can get the storage required forvusingsizeof(v).
|
I am not trying to use a DPI call, but a simple Verilog program which internally uses its PLI to call a function written in C language. I don't know about static linking. I am using edaplayground.
Can anyone tell me which simulator should I use and switch should I pass to link both Verilog and C? Should I include the C file in the Verilog?
The sample code is as follows
```
// C function implementation
#include <stdio.h>
void hello() {
printf ("\nHello world\n");
}
// SV function call
module sv_pli ();
initial begin
$hello;
#10 $finish;
end
endmodule
```
I would like to know if there was any need to register the pli since currently the pli call hello is not detected.
|
I put your C code in a new file named test.c, and added SV-DPI to your Verilog code, removed dollar sign from $hello task to become a DPI call.
See the simulator output and it should be the expected result from your sample code.
|
```
int var = (1 == 1) ? (5) : (10);
```
This outputs5, which is correct.
```
int var = 100 + (1 == 1) ? (5) : (10);
```
this again outputs5. Why?
I know I can fix the problem with adding braces around the entire ternary statement, but that doesn't explain what happens with the addition and why it behaves like that on a first place.
|
In C every non-zero value is “true”, here the value of100 + (1 == 1)is101, which is also “true”, therefore(5)is selected. Since?:has a very low precedence, the parentheses should be((1==1) ? 5 : 10)to have the effect you want.
|
I have this simple code, and can't figure out how to allocate memory for scanf
```
char* string= (char*) malloc (sizeof(char));
printf("insert string: \n");
scanf("%s", string);
free(string);
```
doesn't matter how many chars my string is, it's an error. I want to use malloc for the char*, any way to set memory for scanf.
|
You are just request 1 byte. You need to allocate more than that if you want store more than just the0terminator in the string:
```
char* string= malloc (256); //256 bytes, arbitrary value...
```
I removed:
sizeof(char)because it's always guaranteed to be1.(char*)because casting the return value ofmalloc()is needless.
I would also recommend usingfgets()instead ofscanf()to prevent overflowing the buffer. The same could be done withscanf()by specifying the length in the format string. But I personally prefer usingfgets()and parsing usingsscanf()if necessary.
|
I was wondering if I can create macro that creating value with custom "shift" (or other way to create it in compile time). I mean, concatenate two numbers or something...
Something like that (of course it's not working):
```
#define CUSTOM_DOUBLE(shift) 1.05E shift
```
I know I can do:
```
#define CUSTOM_DOUBLE(shift) 1.05 * pow(10.0, shift)
```
But I'm aware that it isn't calculated in compile time.
|
As long asshiftargument is passed asinteger constant(of decimal form) this can be accomplished by##operator, that concatenates preprocessing tokens. For instance, it may be implemented as:
```
#include <stdio.h>
#define CUSTOM_DOUBLE(shift) (1.05E ## shift)
int main(void)
{
double d = CUSTOM_DOUBLE(3);
printf("%E\n", d);
return 0;
}
```
|
I have this simple code for writing to a file in c
```
FILE* fp = fopen ("file.txt", "w+");
fprintf(fp, "bla");
free(fp);
```
i'm getting tons of errors when running valgrind,
```
Address "xxxxxxx" is 192 bytes inside a block of size 568 free'd
Address "xxxxxxx" is 168 bytes inside a block of size 568 free'd
```
and a lot more like these.
No leaks!, but errors.
|
You should replace free(fp) with fclose(fp).
Also check fp for NULL
|
I have this code
```
char* chars = (char*) malloc (sizeof(char));
memcpy(chars, "", 0);
char* hey = "hello doit";
chars = (char*) realloc (chars, 10);
memcpy(chars, hey, 10);
printf("string: %s\n", chars);
free(chars);
```
and I'm getting an error in memory
```
Address "xxxxxxx" is 0 bytes after a block of size 10 alloc'd
```
what am I doing wrong?
|
10 bytes is not enough to contain"hello doit"including a string terminator. You don't use any string function here, but perhaps there is other code that does. Please show the complete verifiable example.
You didn't post the whole code, but have now commented"When I print the string..."(and edited the question as I typed this).
The sizes need to be 11. You need to copy the terminator too.
```
chars = realloc (chars, 11);
memcpy(chars, hey, 11);
```
|
Consider the following macro:
```
#define FOO(a,b) (--a)* 8 + (--b);
```
Now
```
int graph[8][8] = { 0 };
int *graph_p = &(graph[0][0]);
int *p = graph_p + FOO(2, 3);
```
Why do I get the error:
IntelliSense: expression must be a modifiable lvalue
|
It's because you are passing aninteger constantto function-like macroFOO(a, b), that applies pre-increment--operator to its arguments.
The result of this macro expansion looks as:
```
int *p = graph_p + (--2)* 8 + (--3);;
```
which is illegal in C, as operator requires amodifiable lvalueas its operand.
Another issues here are, that you should put parantheses around macro's replacement and do not place semicolon at the end:
```
#define FOO(a,b) ((--a)* 8 + (--b))
```
|
I've been tasked to build a Cocoa interface for a C terminal application.
There are no requirments other than the GUI.
My question is:
Would it be best and/or fastest to make the terminal calls or get source code (which I do have authorization to use) and call the functions directly from Cocoa?
Please state pros and cons for educational purposes.
|
It would be best (faster, easier) to call the functions directly from Cocoa.
Of course you realise that Cocoa apps must be Sandboxed if they are going on the Mac App Store and Sandboxing can make many, previously trivial, operations much more complicated?
|
I would like parse two numbers.
From a RTC IC I get 7 bits, where bit 6, 5, 4 are upper digits (first digit in number of seconds 0 - 5) and bits 3, 2, 1, 0 are unit digits (0 - 9). Now I would like to create a function that parses these two numbers and return the number of seconds.
Here is a table of the second number which I get from the RTC IC.
For the first number, I masked these bits and I get upper and lower numbers. I would like to parse these two numbers and return them from a function.
How?
|
It's pretty straightforward, just split the bits as documented :
```
uint8_t i = getBcd();
return (i >> 4 & 0x7) * 10 + (i & 0xf);
```
|
My sourcecode:
```
#include <stdio.h>
int main()
{
char myArray[150];
int n = sizeof(myArray);
for(int i = 0; i < n; i++)
{
myArray[i] = i + 1;
printf("%d\n", myArray[i]);
}
return 0;
}
```
I'm using Ubuntu 14 and gcc to compile it, what it prints out is:
```
1
2
3
...
125
126
127
-128
-127
-126
-125
...
```
Why doesn't it just count up to 150?
|
intvalue of acharcan range from 0 to 255 or -127 to 127, depending on implementation.
Therefore once the value reaches 127 in your case, it overflows and you get negative value as output.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.