question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
This is the solution ofProgramming Pearlsin column 1.6_1:
```
> #include <stdio.h>
int intcomp(int *x, int *y)
{
return *x-*y;
}
int a[1000000];
int main(void) {
// insert code here...
int i,n=0;
while (scanf("%d",&a[n])!=EOF) {
n++;
}
qsort(a,n,sizeof(a[0]),intcomp);
for(i=0;i<n;... |
Comment (which turned out to be a correct guess) promoted to answer:
It's unclear if the source code above was from typed in from the book, or found online. The code above has a few differences fromthis github copy of p1c1quicksort, i.e. the code above is missing:
```
#include <stdlib.h>.
```
|
I know that Guile has ascm_assert_smob_typefunction, but I do not believe that it returns a boolean.
I want to be able to do something like:
```
if (type(smob) == int_smob)
{
int_foo(smob);
}
else if (type(smob) == string_smob)
{
string_foo(smob);
}
```
|
You can checkscm_assert_smob_type'sdefinitionfor hints:
```
void
scm_assert_smob_type (scm_t_bits tag, SCM val)
{
if (!SCM_SMOB_PREDICATE (tag, val))
scm_wrong_type_arg_msg (NULL, 0, val, scm_smobs[SCM_TC2SMOBNUM(tag)].name);
}
```
As you can see, it utilizesSCM_SMOB_PREDICATEwhich does return a boolean. The m... |
Novice in c programming. Could someone help me understand what the while loop is doing in this code snippet? I've never seen a while loop of this type.
However, I do understand that it is performing pointer arithmetic, but what is it actually saying broken down in terms of pseudocode or plain English? :)
```
char*
c... |
In C a value of 0 means false and any other means true. Strings end in a null character with a value of 0. This while loop copies all the characters from s to d until the null (end of string) is reached.
The assignment*d++ = *s++returns the same value as*s++is assigned to*d
After the loop bothsanddwill be pointing ... |
I'm trying to dynamically link a Rust .so library with a C program in Linux with gcc. Using onlydlopenanddlcloseresults in no errors, but I get a segmentation fault with the following code:
```
char * (*my_function)(char *);
char *my_input_string = "foo";
//...abbreviated code...
my_function = dlsym(handle, "my_fun... |
I ran it throughgdband it turns out the library was trying to call a function in the calling program that didn't exist.
|
This is the solution ofProgramming Pearlsin column 1.6_1:
```
> #include <stdio.h>
int intcomp(int *x, int *y)
{
return *x-*y;
}
int a[1000000];
int main(void) {
// insert code here...
int i,n=0;
while (scanf("%d",&a[n])!=EOF) {
n++;
}
qsort(a,n,sizeof(a[0]),intcomp);
for(i=0;i<n;... |
Comment (which turned out to be a correct guess) promoted to answer:
It's unclear if the source code above was from typed in from the book, or found online. The code above has a few differences fromthis github copy of p1c1quicksort, i.e. the code above is missing:
```
#include <stdlib.h>.
```
|
I know that Guile has ascm_assert_smob_typefunction, but I do not believe that it returns a boolean.
I want to be able to do something like:
```
if (type(smob) == int_smob)
{
int_foo(smob);
}
else if (type(smob) == string_smob)
{
string_foo(smob);
}
```
|
You can checkscm_assert_smob_type'sdefinitionfor hints:
```
void
scm_assert_smob_type (scm_t_bits tag, SCM val)
{
if (!SCM_SMOB_PREDICATE (tag, val))
scm_wrong_type_arg_msg (NULL, 0, val, scm_smobs[SCM_TC2SMOBNUM(tag)].name);
}
```
As you can see, it utilizesSCM_SMOB_PREDICATEwhich does return a boolean. The m... |
Novice in c programming. Could someone help me understand what the while loop is doing in this code snippet? I've never seen a while loop of this type.
However, I do understand that it is performing pointer arithmetic, but what is it actually saying broken down in terms of pseudocode or plain English? :)
```
char*
c... |
In C a value of 0 means false and any other means true. Strings end in a null character with a value of 0. This while loop copies all the characters from s to d until the null (end of string) is reached.
The assignment*d++ = *s++returns the same value as*s++is assigned to*d
After the loop bothsanddwill be pointing ... |
I'm trying to dynamically link a Rust .so library with a C program in Linux with gcc. Using onlydlopenanddlcloseresults in no errors, but I get a segmentation fault with the following code:
```
char * (*my_function)(char *);
char *my_input_string = "foo";
//...abbreviated code...
my_function = dlsym(handle, "my_fun... |
I ran it throughgdband it turns out the library was trying to call a function in the calling program that didn't exist.
|
I am using Kinetis Design Studio v 3.0 and am trying to launch a C application on my FRDM-K64 board. The project builds just fine; however, when I try to debug, I get this error:
```
Error in final launch sequence
Failed to execute MI command:
-exec-run
Error message from debugger back end:
Don't know how to ... |
I solved the problem--apparently my software needed to be updated. So if anyone is getting the same error, be sure you have tried checking for updates.
|
I have a program that only generates the output when it returns normally or when it calls theexit()function (I'm trying to usegcovon a C program). On a special input my program hangs in an infinite loop so I have to terminate it by sending termination signal. In this situation it won't produce the output I need since ... |
As suggested in the comments, I executed my program withingdband after receiving signal I manually callexit()and it worked like charm.
|
This question already has answers here:Why both clang and gcc only give a warning when there is a space after backslash if C standard says that whitespace is forbidden?(4 answers)Closed3 years ago.
When using\to continue a line, are spaces allowedafterthe backslash (on the same line)?
|
A new-line character should go immediately after a backslash. The C++ standard (N4140) states:
2.2 Phases of translation....Each instance of a backslash character (\) immediately followed by a new-line character is deleted,
splicing physical source lines to form logical source lines. Only the last backslash on any ph... |
my code is given below
```
#include <stdio.h>
#include <ctype.h>
#define size 5
void main(){
int i;
char letter[size];
for(i=0;i<size;i++)
letter[i]=getchar();
for(i=0;i<size;i++)
putchar(toupper(letter[i]));
}
```
and the output is :
```
bitto@HP-ProBook-4430s:~$ gcc test.c
bitto... |
As EOF said, any input you have will be taking two chars as input because you are typing inAthenEnterwhichCreads asaand\nso that is two chars, not one.
|
I'm rooting around some really old C code and have come across the following:
```
GLOBAL void Input_Channels()
{
// removed
}
```
There are also plenty of similar, but LOCAL.
What is this? I can't see any information anywhere about the LOCAL / GLOBAL function.
|
My best guess is that somewhere there are macros defined for this, to help you see whether the functions should be considered public or private (to use object-oriented lingo) - or whether the function is exported or not.
GLOBAL could do nothing where LOCAL could mark the functions static.
I haven't seen that before,... |
This question already has answers here:Conditional execution based on short-circuit logical operation(2 answers)Closed7 years ago.
So, let's say, I have this piece of code:
```
int value = 256;
if( check_value_1(value) && check_value_2(value) )
{
// .. do stuff ..
}
```
If functioncheck_value_1()returnsFALSEwil... |
Ifcheck_value_1(value)returnsFALSE, the second portion of the if-statement will be skipped and will not execute. This is known asshort circuit evaluation.
|
I'm making a program in C that has the option (for the user) to launch automatically at Linux startup. I'm looking for a code snippet or something helpful. The way I want to do it, is programmaticallyif the user selected auto-startup, then (code I am looking for)
I saw many thing about cron jobs and/etc/rd.somethings... |
if the user selected auto-startup, then (code I am looking for)
One way is to add a cron job to that user's crontab with special time specification@reboot.
|
I am trying to print a SHA256 hash in C but when I use the for loop shown below, the only way the hash is printed is when I add the newline to printf. Ideally I want to print it all on one line.
```
void enclave_main()
{
char string[] = "Hello World";
int x;
unsigned char digest[SHA256_DIGEST_LENGTH];
... |
Standard output is (typically) line-buffered, which means output won't be flushed to the terminal until the buffer is fulloryou send a newlineoryou flush the stream manually withfflush().
The easiest thing to do is print the newline after the loop:
```
for(x = 0; x < SHA256_DIGEST_LENGTH; x++)
printf("%02x",... |
I am trying to write a recursive Fibonacci generator that prints each term in C. The number of terms is user-specified; I have developed the algorithm. When I try to print, it only prints ones. Can anyone point me in the direction of where I am going wrong?
```
#include <stdio.h>
#include <stdlib.h>
int Fibonacci (i... |
```
if (n == 0)
```
not
```
if (n=0)
```
check your syntax careful.
|
The way to call execlp is shown in the following:
```
int execlp(const char *file, const char *arg, ...
/* (char *) NULL */);
```
For example,
```
execlp("/bin/Binary","Binary","0x00","0x01","0x02",(char *)0);
```
In this case, since my argument"0x00","0x01"and"0x02"are always fixed. Can I ... |
I think you are looking forexecvp:
```
int execvp(const char *file, char *const argv[]);
```
But mindEOF's comment:0x00and"0x00"are most definitely not interchangeable.
EDIT
As pointed out in the comments, the array passed in this case toexecvpmust contain aNULLpointer as the last member (unlike your example tha... |
I am trying to write a recursive Fibonacci generator that prints each term in C. The number of terms is user-specified; I have developed the algorithm. When I try to print, it only prints ones. Can anyone point me in the direction of where I am going wrong?
```
#include <stdio.h>
#include <stdlib.h>
int Fibonacci (i... |
```
if (n == 0)
```
not
```
if (n=0)
```
check your syntax careful.
|
The way to call execlp is shown in the following:
```
int execlp(const char *file, const char *arg, ...
/* (char *) NULL */);
```
For example,
```
execlp("/bin/Binary","Binary","0x00","0x01","0x02",(char *)0);
```
In this case, since my argument"0x00","0x01"and"0x02"are always fixed. Can I ... |
I think you are looking forexecvp:
```
int execvp(const char *file, char *const argv[]);
```
But mindEOF's comment:0x00and"0x00"are most definitely not interchangeable.
EDIT
As pointed out in the comments, the array passed in this case toexecvpmust contain aNULLpointer as the last member (unlike your example tha... |
This question already has answers here:when to use while loop rather than for loop(15 answers)Closed7 years ago.
What is the need for using thewhileloop when we can iterate without usingwhile? Is there something that cannot be done withoutwhile?
|
There is nothing thatwhilecan do that you wouldn't be able to do withfor. In fact,
```
while (xxxxxxx) {
}
```
can be replaced mechanically with
```
for (; xxxxxxx ;) {
}
```
and the code would work exactly the same.
The only reason for having thewhileloop as well is better readability of your code.
|
I have a problem with my two dimensional array in C. Say 2D array isboard[d][d](d=7) and i want to assign value ofboard[d-1][d-2]to anint. When i do this i get error, if i printfboard[d-1][d-2]i get32766. The highest value in the array isd*d-1=48.
What am i doing wrong?
```
int main(void)
{
int d=7;
int nr=(d*... |
It's because you didn't initialize it with any value, so it simply stores whatever garbage happened to be there in memory atm.
You need to run on board and set initial values to it.
|
I have been going through the documentation and I'm still lost on how to filter out_idresults from mongodb using the C driver.I essentially want this functionality but I'm not sure
```
db.collection.find({"test":"pass"},{_id: false});
```
How would I include that projection in C?
```
cursor = mongoc_collection_find... |
After a bit of trial and error I was able to finally add flags to a search query. For anyone else here is the format for appending the No id flag to a MongoC search.
bson_t *field = bson_new();BSON_APPEND_INT32(field,"_id", 0);
to a search pattern like
cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE... |
I created a library for my C programs and this includes threads. I usually work with Code::Blocks and I never had problems, but now I need to compile programs directly from terminal. I saw that I need to write-lpthreadbut also my library name (its name is my_lib.h). I tried to compile first the library withgcc my_li... |
I assumemy_lib.cis just a module (object file) rather than shared library.
The compiling consists of two parts - compiling into object files and then linking:
```
# compiling (note the -c)
gcc -c my_lib.c
gcc -c main.c
# linking (no -c, just specify target with -o)
gcc -o main main.o my_lib.o -lpthread
```
Header f... |
I have a problem with my two dimensional array in C. Say 2D array isboard[d][d](d=7) and i want to assign value ofboard[d-1][d-2]to anint. When i do this i get error, if i printfboard[d-1][d-2]i get32766. The highest value in the array isd*d-1=48.
What am i doing wrong?
```
int main(void)
{
int d=7;
int nr=(d*... |
It's because you didn't initialize it with any value, so it simply stores whatever garbage happened to be there in memory atm.
You need to run on board and set initial values to it.
|
I have been going through the documentation and I'm still lost on how to filter out_idresults from mongodb using the C driver.I essentially want this functionality but I'm not sure
```
db.collection.find({"test":"pass"},{_id: false});
```
How would I include that projection in C?
```
cursor = mongoc_collection_find... |
After a bit of trial and error I was able to finally add flags to a search query. For anyone else here is the format for appending the No id flag to a MongoC search.
bson_t *field = bson_new();BSON_APPEND_INT32(field,"_id", 0);
to a search pattern like
cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE... |
I created a library for my C programs and this includes threads. I usually work with Code::Blocks and I never had problems, but now I need to compile programs directly from terminal. I saw that I need to write-lpthreadbut also my library name (its name is my_lib.h). I tried to compile first the library withgcc my_li... |
I assumemy_lib.cis just a module (object file) rather than shared library.
The compiling consists of two parts - compiling into object files and then linking:
```
# compiling (note the -c)
gcc -c my_lib.c
gcc -c main.c
# linking (no -c, just specify target with -o)
gcc -o main main.o my_lib.o -lpthread
```
Header f... |
This question already has answers here:Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer(5 answers)Closed7 years ago.
I'm trying out the following code:
```
int main()
{
char *yo = "yo";
char *whaddup = NULL;
strcpy(whaddup,yo);
}
```
and I get a segfault. Complete ... |
Just anystrcpydocumentation will tell you that the destination string should be achararray large enough to hold the string and theNULterminator.
So what you need is something like
```
char* yo = "yo";
char* whaddup = malloc(strlen(yo)+1);
strcpy(whaddup, yo);
```
Or alternatively you could usestrdupfunction which d... |
I'm using an Arduino Mini Pro and I'm using it to sample the data line of a C218D 433Mhz rf receiver. When using timer interrupts, the Arduino seems to miss most of the samples. However when using delays instead, it seems to work perfectly fine! Problem is, is that I cannot use delays for my project and need to use th... |
Think i solved it, Serial port was open and messing with my interupts
|
I'm reading a file on linux and windows, on linux all work pretty well, but on windows, thefread(r_hash, 1, 64 , f);will put 64 char in r_hash then 32 char of junk, and I don't understand why. Here is my code Thanks!
```
int status;
FILE *f;
char *path;
char ln[64];
char *r_hash = calloc(64, 1);
path = malloc(1024);
... |
r_hash = calloc(68, 1); // anything more than 64
|
I'm usingstat.st_mtimeto get my last modification time of a directory and then store it into afile.txt(stored string is something like that :1467035651)
Later when I retrieved data from myfile.txt, I tried to convert my string from myfile.txttointtype since the string contains just seconds but I don't know if it's ... |
According to thereference documentationtime_tis just an unspecified numeric format.
Just directly read back the numeric value from the file, there's no need for special conversions:
```
time_t t;
std::ifstream input("File.txt");
// ...
input >> t;
```
|
I've created a background worker. I want to manually delete it and relaunch a new one. At this point, I am doing the following:
```
select * from pg_stat_activity;
select pg_terminate_backend(pid);
```
It certainly stops the current worker. But I think it does not delete the metadata about the bgworker. In the confi... |
Please refer the below URL for an answer:
```
https://www.postgresql.org/message-id/CALF3U-4To6FfrBcMWH2uR7yubcm03L9G0pJYMcyv0fNA6A%3DZ3Q%40mail.gmail.com
```
|
What are some use cases of do nothing function (in C) like:
```
dummy() {}
```
I am reading "The C programming Language" by K&R and in chapter 4 (Functions & Program Structures) , it mentions that
A do-nothing function like this (shown above) sometimes useful as a place holder during program development.
Can anyon... |
A function that does nothing (yet) is an indicator that something should be done, but hasn't been implemented yet.
|
I have a struct inside a struct and on initialization of the outer struct I want to initialize the inner struct as const.
```
typedef struct A {
uint16_t id;
}A;
typedef struct B {
A a;
uint16_t data;
}
```
I know I can initialize the inner struct when initializing the outer struct by this code:
```
B test =... |
You need to define the inner member asconst:
```
typedef struct B {
const A a;
uint16_t data;
} B;
```
Then you can initialize like this:
```
B test = {
{
.id = 0x100
},
.data = 0
};
```
While this generates a compiler error:
```
test.a.id=1;
```
|
I was wondering ifcurrent->link->datadata andcurrent->dataprovides the same result.
Also another concept what exactly the difference betweencurrentandcurrent->linkin singly linked list?
|
I was wondering if current->link->data data and current->data provides
the same result.
May be they provide same data if same data is stored, but these are different locations i.e. ifcurrent->dataisdataatcurrent nodethencurrent->link->datawould bedataofnext node. as shown in figure.
```
struct node
{
struct node *... |
Below is the code in C language:
function call:
```
insert(&head,value);
void insert(struct node** headref,int value)
{
struct node* head = (*headref);
while( head!=NULL )
{
head= head->link;
}
struct node* new_node=(struct node*)malloc( sizeof(struct node) );
new_node->data=v... |
You need to link the last element of the list tonew_nodeotherwise you will loose the linked-ness(if there is such a word :) ) of your list. You need to store 2 pointers in the cycle -head, that you already have and a pointer to the previous element(the element before head). Take special care for the case where you hav... |
I am programming STM32F373RCT and I have been trying to make a USB virtual comport device. if I send data up to about 960 bits per second (I used a timer (50Hz) and I transmit 14 bytes in every cycle), communication is working correctly but if I try to send data more than this, some data lost. I have to increase data ... |
USB has built-in flow control so you should be able to send data as fast as possible without losing any data. There is either a bug in the USB stack you are using or in the code that you are using to send data to the USB stack. If you can identify and fix that bug, then you should be able to send data a lot faster w... |
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed7 years ago.Improve this question
I have#included <xcb... |
Linking with-lxcb-utildid the trick as mentioned byMarcus Müller
|
according to the C Standard (and K&R) the syntax of the Comma-Operator is as follows:
```
expression:
assignment-expression
expression, assignment-expression
```
But why does this statement work?
```
5+5, 1+1;
```
5+5 and 1+1 are not assignment-expressions, but the C Standard requires assignment-expression... |
assignment-expression⊃conditional-expression⊃logical-OR-expression⊃logical-AND-expression⊃inclusive-OR-expression⊃exclusive-OR-expression⊃AND-expression⊃equality-expression⊃relational-expression⊃shift-expression⊃additive-expressionwhich finally are ⊃additive-expression + multiplicative-expression.
So no, 5+5 is indee... |
I have been able to use the digit-separator'in my C projects thus far. They have all been compiled with the MSVC compiler with no problems.
I have just changed to using the GCC compiler instead, which does not allow these digit-separators and throws an error, when I use them. I assume the reason is because, Visual St... |
It's defined inn2626, thus, you can use this feature straightly with--std=c2x(for gcc/clang) currently.
|
```
#define HELPER(param) Wazz ##param
HELPER(hek)
```
Doing agcc -E filenameshows me
```
Wazzhek
```
How do I getWazz hek? How do I insert a space between the 2 tokens?
```
#define HELPER(param) Wazz ## ## ##param
```
Doesnt work either. Any suggestions?
|
Just do not use token concatenation operator when you don't want to do token concatenation.
```
#define HELPER(param) Wazz param
HELPER(hek)
```
|
My question is that in the below program,how does the code
```
while (scanf("%d %d", &a, &b), (a || b))
```
is being evaluated?
The program get two number and print the sum:
```
int a, b;
while (scanf("%d %d", &a, &b), (a || b))
printf("%d\n", a + b);
```
|
Read more documentation aboutCand itsstandard library.
Start by readingcarefullythe documentation ofscanf.
Then read about thecomma operator,and thelogical operators(e.g.||and&&)
Also, compile your code with all warnings & debug info (gcc -Wall -g) and run it step by step in the debugger (gdb). That would give you ... |
I just know about the %i format specifier from this link
Difference between format specifiers %i and %d in printf
and I tried to implement it with this program.
```
#include <stdio.h>
int main(){
long long a,b;
printf("Input: ");
scanf("%i %lld",&b,&a);
printf("Output: %i %lld",b,a);
}
```
%i ... |
scanf%itakes anint *, but you're passing&b, which is along long int *. This has undefined behavior.
You should be using%lli.
The same problem occurs inprintf: Use%llito printb, not%i.
You should also checkscanf's return value to make sure two values were successfully read.
|
I have a line of code like this:
```
for (ivalue=list[i];i>0 && list[i-1]>ivalue;i--)
...
```
which runs fine. But if I change the position of first condition i>0 it exits with Segmentation fault: 11 while running:
```
for (ivalue=list[i];list[i-1]>ivalue && i>0;i--)
exits with Segmentation fault: 11
```
Why t... |
The order of Associativity of&&operator is left to right
So it first checks forlist[i-1]>ivaluebefore checkingi>0
Thus wheni=0thelist[i-1]becomeslist[-1]that is out of bound and hence givessegmentation error
NOTE:i>0is never checked
|
Which way is the best for line up all the output on the right ?
Example: for powers of 2:
```
2
4
8
16
32
64
128
256
512
1024
2048
...
134217728
```
If my last number has N digits, how print the first one (which in this case has just one digit)... |
You can supply a computed field width toprintf()using*. So after you calculate the maximum number of digits, you can do:
```
printf("%*d\n", max_digits, value);
```
|
I know that in C both of these works:
```
char* string = "foo";
printf("string value: %s", string);
```
and more simply:
```
printf("string value: %s", "foo");
```
But I was asking myself why.
I know that%sidentifier expects the argument to be a char*, andstringactually is (and it will be the same with an array o... |
The string constant"foo"has typechar []. When passed to a function, the array decays to a pointer, i.e.char *. So you can pass it to a function that expects the same.
For the same reason, you can also pass a variable of this type:
```
char string[4] = "foo";
printf("string value: %s", string);
```
|
```
#include<stdio.h>
int main()
{
FILE *opening;
opening = fopen("hello.usr","w");
fprintf(opening,"Hello world!");
fclose(opening);
printf("Writing to the file was successful.\n");
printf("Closing the program");
return 0;
}
```
I have tried this code to create a file in c pr... |
If you want to know what is wrong check the result offopen
```
opening = fopen("hello.usr","w");
if (opening == NULL) {
perror("fopen");
}
```
|
I am working on an exercise where this is a piece of the code:
```
typedef struct node
{
size_t size;
struct node *next;
} node_t;
byte heap[SIZE];
node_t *node_list;
void heap_init()
{
node_list = (node_t*) heap;
node_list->size = SIZE;
node_list->next = NULL;
}
```
But i have some trouble u... |
heapis an array of bytes of sizeSIZE.
node_listis a pointer of typenode_t. This pointer is assigned to the first byte of the arrayheap. What this does is thatnode_listis assigned to an allocated location of memory.
I am guessing that the next pointer for the list will be assigned to a location further along this arr... |
I know that in C both of these works:
```
char* string = "foo";
printf("string value: %s", string);
```
and more simply:
```
printf("string value: %s", "foo");
```
But I was asking myself why.
I know that%sidentifier expects the argument to be a char*, andstringactually is (and it will be the same with an array o... |
The string constant"foo"has typechar []. When passed to a function, the array decays to a pointer, i.e.char *. So you can pass it to a function that expects the same.
For the same reason, you can also pass a variable of this type:
```
char string[4] = "foo";
printf("string value: %s", string);
```
|
```
#include<stdio.h>
int main()
{
FILE *opening;
opening = fopen("hello.usr","w");
fprintf(opening,"Hello world!");
fclose(opening);
printf("Writing to the file was successful.\n");
printf("Closing the program");
return 0;
}
```
I have tried this code to create a file in c pr... |
If you want to know what is wrong check the result offopen
```
opening = fopen("hello.usr","w");
if (opening == NULL) {
perror("fopen");
}
```
|
I am working on an exercise where this is a piece of the code:
```
typedef struct node
{
size_t size;
struct node *next;
} node_t;
byte heap[SIZE];
node_t *node_list;
void heap_init()
{
node_list = (node_t*) heap;
node_list->size = SIZE;
node_list->next = NULL;
}
```
But i have some trouble u... |
heapis an array of bytes of sizeSIZE.
node_listis a pointer of typenode_t. This pointer is assigned to the first byte of the arrayheap. What this does is thatnode_listis assigned to an allocated location of memory.
I am guessing that the next pointer for the list will be assigned to a location further along this arr... |
I'm current working in a C project with visual studio (community 2015). I'm attempted to remove warnings from my project. Currently I'm getting the following warning:
C4100: 'argc': unreferenced formal parameter
Searching on why I get this warning I found this stack overflow question:Why the unnamed parameter warnin... |
this is a C warning.
It is saying that you have a parameter to a function that is not actually used within the function.
Note: if the function ismain(), then never assume anything about the parameters, especially the number of command line parameters.
This means do not reference anything beyondargv[0]without first ... |
I'm practicing structures in C, and I come up with this doubt. Sometimes I see something like:
```
struct myStruct{
//some data
} *p;
```
What does that pointerpmeans?
How is that different from:
```
struct myStruct{
//some data
};
```
|
In your code
```
struct myStruct{
//some data
};
```
is the definition of thestruct. There is novariablecreated with that data type.
On the other hand,
```
struct myStruct{
//some data
} *p;
```
is the definition of thestructas well as creating a variablepof type pointer-to-struct. After allocating memor... |
How can I embed a small Python script into a Windows shell command to provide arguments to a program?
Example:
```
C:\> hello Bob
Welcome Bob!
```
What I need is something like this:
```
C:\> hello 'python -c print('Bob')'
Welcome Bob!
```
Thanks!
|
Powershell supports the same format as bash, so you can do:
```
PS C:\> hello $(python -c "print('Bob')")
```
Forcmd.exe, there is no such equivalent, but you can try this (untested):
```
C:\>FOR /F "usebackq" %x in (`python -c "print('Bob')"`) DO hello %x
```
|
I'm trying to compile aCproject usinggcc. All source files and the .a library file arein the same folder. How can I successfully compile the project?
I've tried:
```
gcc -o test main.c IPT.c logitem_list.c -L -./ -libpt
```
But I receieve error:
```
/usr/bin/ld: cannot find -libpt
collect2: error: ld returned 1 ... |
You specify the directory to-Land the 'core' name to-l:
```
gcc -o test main.c IPT.c logitem_list.c -L . -lpt
```
When given-lpt, the linker looks forlibpt.aorlibpt.soor equivalents (extensions like.dylibor.slor.dllor.libon other platforms).
The-L -./is suggesting that the linker look in a directory called 'dash do... |
Here is my code. My question is, why does it keep printing only 5 numbers? Why won't it print 10 like it's supposed to?
```
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
int r, col;
srand((unsigned)time(NULL));
for (col=1; col<=10; col++){
r = rand() % 11;
printf("%d\n... |
Because, you are doingcol++twice, once in the loop body, and once in the post-loop statement.
```
for (col=1; col<=10; col++) //...................(i)
^^^^^^^
```
and
```
r = rand() % 11;
printf("%d\n", r);
col++; //.....................(ii)
^^^^^
```
So, for a single it... |
I am familiar with the Arduino programming tools but have relatively small experience with embedded programming. When using decimal numbers in the Arduino I never had any issues, so when I recently started playing around with TI's Launchpad F28069M(TMS320F28069M Chip), I was surprised that my math was not yielding my ... |
Try with this code instead:
```
float A;
main()
{
A = .25;
}
```
|
Can we access the mtharray element, if it has m elements?
I mean that, if the array has 7 elements, was it ever possible to store any value in array[7]?
But the array indexes start from 0 and end with 6, when length is is 7.
|
No, accessing the element beyond the array bound is undefined behaviour. Taking address of the element 1 beyond last array element is well defined.
To understand the implications, consider readingHow dangerous is it to access an array out of bounds?
|
The value contained in the pointer 'p' from the structure below is wrong printed and i can not find the way to print it right. What's the right code for it?
The code:
```
#include <stdio.h>
struct my_struct{ //structure definition
int a,*p;
};
int main(){
my_struct var;
var.a = 5; //va... |
The%dformat specifier toprintfexpects anint, but you're passing it anint *.
You need to dereference the pointer to obtain anint:
```
printf("%d\n",*(var.p));
```
|
I want to iterate through any array starting at an index that's close to the middle, go to the end then go to the beginning.As an example:
```
#include <stdio.h>
int main(){
int a[]= {1, 2, 3, 4, 5, 6, 7,};
int i = 0;
for (i = 2; i < 6; i++){
if (i == 6){
i = 0;
}
printf("%d\n", a[i]);
}
... |
Here is a simple write-up. Not tested so adjust as needed. The idea is have the counter start at 0 and add the value of start each time using modulus to make it relative.
```
int a[]= {1, 2, 3, 4, 5, 6, 7};
int length = sizeof(a)/sizeof(a[0]);
int start = length/2;
for (int i = 0; i < length; i++)
{
printf("%d\n"... |
I am using tcp to transfer data. The server code is written by C, and client code is written by nodejs.
When I send one buffer, sometimes the client will receive two parts of this buffer, the console.log function will trigger twice, but sometimes it works well.
following are nodejs code and C code.
nodejs code:
```
... |
This is typical for TCP, which is a stream-oriented (as opposed to packet-oriented like UDP) protocol after all.
There's no guarantee that one write to the network equals one read at the other end, multiple writes may be delivered together and single writes may be split.
You must add an applicaton-level message prot... |
What is the quickest bit-hack to achieve the following result?
Let x be a 4 byte int, in a C program.
If x is0x00000000, then x should be0xFFFFFFFF, else x should be untouched.
|
x |= -(x == 0);x |= -!x;x = x ? x : 0xFFFFFFFF;if (x == 0)
x = 0xFFFFFFFF;...
Benchmark and choose what's appropriate for you
|
I want to print the decimal value of 1010 ingdb,
but it prints the result as it is what I gave last.
```
(gdb)
(gdb) p/d 1010
$1 = 1010
(gdb)
```
|
GDB'sp[rint] command prints the value of the expression you provide, which is interpreted in the source language of the program being debugged. In C, your1010is a decimal literal, not a binary literal, so your basic problem is that you are giving GDB bad input.
Standard C has no support for binary literals, but GNU ... |
The value contained in the pointer 'p' from the structure below is wrong printed and i can not find the way to print it right. What's the right code for it?
The code:
```
#include <stdio.h>
struct my_struct{ //structure definition
int a,*p;
};
int main(){
my_struct var;
var.a = 5; //va... |
The%dformat specifier toprintfexpects anint, but you're passing it anint *.
You need to dereference the pointer to obtain anint:
```
printf("%d\n",*(var.p));
```
|
I want to iterate through any array starting at an index that's close to the middle, go to the end then go to the beginning.As an example:
```
#include <stdio.h>
int main(){
int a[]= {1, 2, 3, 4, 5, 6, 7,};
int i = 0;
for (i = 2; i < 6; i++){
if (i == 6){
i = 0;
}
printf("%d\n", a[i]);
}
... |
Here is a simple write-up. Not tested so adjust as needed. The idea is have the counter start at 0 and add the value of start each time using modulus to make it relative.
```
int a[]= {1, 2, 3, 4, 5, 6, 7};
int length = sizeof(a)/sizeof(a[0]);
int start = length/2;
for (int i = 0; i < length; i++)
{
printf("%d\n"... |
I know I can do this:
```
//With A = tax(x);
return tan(arctan(A)/2);
```
but I wanted something more efficient.
|
Whenxis between -π/2 and π/2 you can use this formula:
```
t / (1 + sqrt(1 + t*t))
```
This is hardly an improvement on the original formula, but it uses one function call instead of two.
Note:I found this formulahere. The wikipedia page is in Russian, and the equivalent English page does not include the same formu... |
I just got a error from connect API in linux.
I knew 'connect' will return zero if connection is successful, I got return value "3"
is it error code? or is there something else what don't know?
```
connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
```
I got value 3 from sock.
|
To get the return value ofconnect(), it is most straight forward to use a variable that is used as the left hand side of an assignment.
```
int result = connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
printf("connect returned: %d\n", result);
```
sockmust be a socket, and was assigned a file descript... |
Is the same
```
char* s1[size];
```
To
```
char** s2 = malloc(size * sizeof(char*));
```
They have any difference?
|
Theoretically,*arr[]and**arrare different. For example :
```
char *arr[size]; //case 1
```
Herearris a an array of sizesizewhose elements are of the typechar*
Whereas,
```
char **arr; //case2
```
Herearris itself a pointer to the typechar*
Note:Incase 1arrayarrdegrades to a pointer to become the typechar**but it... |
I am reading lines from a file, the lines look like this:
```
89f81a03eb30a03c8708dde38cf:000391716
```
The thing is: I want to remove everything after the:(including the:).
I tried everything I could find online but they seem to useconst charand the lines arecharpointers.
|
You can usestrchr:
```
char str[] = "89f81a03eb30a03c8708dde38cf:000391716";
char *ptr;
ptr = strchr(str, ':');
if (ptr != NULL) {
*ptr = '\0';
}
```
|
So, it has been some time since I last programmed in C, and now I am trying to get back into C again, but I am having trouble with my program. The program is very simple, I use getchar to store chars in a char array, but for some reason the program stops running after my while loop.
```
#include <stdio.h>
#define MAX... |
Send EOF (Ctrl+D for *nix Ctrl+Z for Win), it will show the Still running.
```
root@Linux-VirtualBox:~/program/progEdit# ./stktest.o
sdf
fdf
sdf
Still runningroot@Linux-VirtualBox:~/program/progEdit#
```
|
Can anyone tell me why my MATLAB code reads doubles correctly, but not floats?
This works as expected:
Linux c server code:
```
double x = 25.2575;
write(sd, &x, sizeof(x));
```
MATLAB client code
```
t = tcpip('10.5.5.7', 50505, 'NetworkRole', 'client');
t.InputBufferSize = 8;
fopen(t);
data = swapbytes(fread(t,... |
The problem was solved by removing the swapbytes call and instead using:
```
t.ByteOrder = 'littleEndian';
```
I do not know why however.
|
This question already has an answer here:__PTRDIFF_TYPE__ vs. ptrdiff_t(1 answer)Closed7 years ago.
I see it is legal to use the variable__PTRDIFF_TYPE__with no header inclusion.
I tried to look for this variable name inISO/IEC 9899but it does not appear. I expected to see its definition in the 7th part, C library.
... |
This is a predefined macro in gcc (a GNU C extension); seehttps://gcc.gnu.org/onlinedocs/cpp/Common-Predefined-Macros.html.
As for why this is legal: The standard reserves all names starting with two underscores (and all names starting with an underscore followed by an uppercase letter) for use by the implementation,... |
I want to initialize a couple of arrays which are members of a struct which is passed to a function by reference.
Appreciate any help.
```
typedef struct Snake_pos
{
char field[10][10];
int Y[10];
int X[10];
}snake_pos;
int main()
{
snake_pos pos1;
pos_init(&pos1);
return 0;
}
void pos_init(... |
You can only use the syntax= {}when defining the variable. So to zero every member you can either define it as
```
snake_pos pos1 = { 0 };
```
Or if it is passed to a function, like this
```
void pos_init(snake_pos *pos1)
{
memset(pos1, 0, sizeof *pos1);
}
```
|
```
#include <stdio.h>
int main(void) {
double numbersEntered, sum = 0;
do
{
printf("Enter a number: ");
scanf("%lf", &numbersEntered);
sum += numbersEntered;
}
while (/* ??? */);
printf("Sum = %.2lf", sum);
return 0;
}
```
What should I do in thewhilestatement to stop the loop after the user enters4... |
You need to introduce a counter:
```
double numbersEntered, sum = 0;
int count = 0;
do
{
printf("Enter a number: ");
scanf("%lf", &numbersEntered);
sum += numbersEntered;
count++;
} while (count < 4);
```
Make sure you increment it otherwise your loop will never end.
Changing the 4 to a constant (o... |
According to the given Elf32_Ehdr structure (page9) in the linkelf-formatelf header size should be 52 bytes and fixed. But there is also field e_ehsize and can be greater than 52 bytes. In where defined those extra bytes until first section header starts ?
|
As it says, also on page 9:
Some object file control structures can grow, because the ELF header contains their actual sizes.If the object file format changes, a program may encounter control structures that are larger or smaller than expected. Programs might therefore ignore ‘‘extra’’ information. The treatment of... |
This question already has answers here:Is floating point math broken?(33 answers)Closed7 years ago.
I am using Code::Block 16.01, the current version, that come with compiler. The problem is when I changexMaxto1.2, the result does not change. It produce the same result asxMax=1.1. Did I do something wrong with my C c... |
You have a float point precision problem. Since1.2cannot be represented exactly in the binary form, there is a precision loss. Your code should work if you change1.2to something bigger, let's say,1.201
In general, please try to avoid=in float point comparisons.
|
I am writing a GPIO-driver for my RPI2 OS. And I was surfing really long time about it, but I found only linux data. How should I do such functions as
```
void gpio_set(int pin);
void gpio_clr(int pin);
```
in C for the driver. Or, maybe it can be done due inline assembly?
|
As explainedhere
The underlying architecture in BCM2836 is identical to BCM2835. The only significant difference is the removal of the ARM1176JZF-S processor and replacement with a quad-core Cortex-A7 cluster.
The available documentation for the BCM2836 does not detail the peripheral hardare, only the A7. Instead y... |
```
#include <stdio.h>
int main(void) {
double numbersEntered, sum = 0;
do
{
printf("Enter a number: ");
scanf("%lf", &numbersEntered);
sum += numbersEntered;
}
while (/* ??? */);
printf("Sum = %.2lf", sum);
return 0;
}
```
What should I do in thewhilestatement to stop the loop after the user enters4... |
You need to introduce a counter:
```
double numbersEntered, sum = 0;
int count = 0;
do
{
printf("Enter a number: ");
scanf("%lf", &numbersEntered);
sum += numbersEntered;
count++;
} while (count < 4);
```
Make sure you increment it otherwise your loop will never end.
Changing the 4 to a constant (o... |
According to the given Elf32_Ehdr structure (page9) in the linkelf-formatelf header size should be 52 bytes and fixed. But there is also field e_ehsize and can be greater than 52 bytes. In where defined those extra bytes until first section header starts ?
|
As it says, also on page 9:
Some object file control structures can grow, because the ELF header contains their actual sizes.If the object file format changes, a program may encounter control structures that are larger or smaller than expected. Programs might therefore ignore ‘‘extra’’ information. The treatment of... |
This question already has answers here:Is floating point math broken?(33 answers)Closed7 years ago.
I am using Code::Block 16.01, the current version, that come with compiler. The problem is when I changexMaxto1.2, the result does not change. It produce the same result asxMax=1.1. Did I do something wrong with my C c... |
You have a float point precision problem. Since1.2cannot be represented exactly in the binary form, there is a precision loss. Your code should work if you change1.2to something bigger, let's say,1.201
In general, please try to avoid=in float point comparisons.
|
I am writing a GPIO-driver for my RPI2 OS. And I was surfing really long time about it, but I found only linux data. How should I do such functions as
```
void gpio_set(int pin);
void gpio_clr(int pin);
```
in C for the driver. Or, maybe it can be done due inline assembly?
|
As explainedhere
The underlying architecture in BCM2836 is identical to BCM2835. The only significant difference is the removal of the ARM1176JZF-S processor and replacement with a quad-core Cortex-A7 cluster.
The available documentation for the BCM2836 does not detail the peripheral hardare, only the A7. Instead y... |
Linking C with Assembly in Visual StudioI've seen that already but that doesn't contain any helpful informations.
I have a C program, in which I'm using function written in assembly.
I include fun.h header in C file with declaration, and have fun.asm with implementation.
It was firstly written using NASM, and there i... |
According to what Michael Petch wrote in comment:
Searched keyword is PUBLIC, and in x86_64 there is NO need for underscore on PROC functions.
|
fwrite()is a library call that firstly buffers the data into a user space buffer, and then calls thewrite()system call later to actually carry out the write operations.
If a program invokesfwrite()to write some data to a file but then exists abnormally, will the buffer offwrite()beclearedflushed, or the buffered data... |
If your program exited abnormally, any buffered data will not be flushed. The OS just says "oh dear me, you left a file descriptor open, I better close that for you" when the process terminates; it has no idea there's some random data lying somewhere in memory that the program intended to write to disk but did not.
|
Consider thedocumentationofuv_tcp_connect.Here is the declaration of the function:
```
int uv_tcp_connect(uv_connect_t* req, uv_tcp_t* handle, const struct sockaddr* addr, uv_connect_cb cb);
```
It accepts a callback and returns an integer.Usually, the other functions inlibuvreturns an error code (0 in case of no er... |
See theerror handling sectionin the documentation. An error (return < 0) means no operation will be performed and no callback will be called.
|
Could you help me understand what the following piece of code means? Specifically, I do not understand what the effect ofname_fnis.
```
#define name_fn
void name_fn Function(void);
```
|
The macroname_fnexpands to nothing during pre-processing. So the next line is same as
```
void Function(void);
```
Empty#defineis useful for compatibility, self documentation and/or mechanical checking.
For example, in socket programming, you may encounter :
```
SOCKET WSAAPI
accept (IN SOCKET s,OUT struct sockadd... |
I'm on my IOT project with raspberry pi,
And I want to raise event in certain time like 06:00:00 and 12:00:00
But I can't do this with jiffies because jiffies only counts the time since the os started.
I have an Idea :
I may raise interrupt every second and check local time, compare it with certain time.
But I th... |
Run a cron at 06:00:00 and 12:00:00. Trigger your event through cron.How to create a cronjob
|
fwrite()is a library call that firstly buffers the data into a user space buffer, and then calls thewrite()system call later to actually carry out the write operations.
If a program invokesfwrite()to write some data to a file but then exists abnormally, will the buffer offwrite()beclearedflushed, or the buffered data... |
If your program exited abnormally, any buffered data will not be flushed. The OS just says "oh dear me, you left a file descriptor open, I better close that for you" when the process terminates; it has no idea there's some random data lying somewhere in memory that the program intended to write to disk but did not.
|
Consider thedocumentationofuv_tcp_connect.Here is the declaration of the function:
```
int uv_tcp_connect(uv_connect_t* req, uv_tcp_t* handle, const struct sockaddr* addr, uv_connect_cb cb);
```
It accepts a callback and returns an integer.Usually, the other functions inlibuvreturns an error code (0 in case of no er... |
See theerror handling sectionin the documentation. An error (return < 0) means no operation will be performed and no callback will be called.
|
I am trying to make this for-loop parallelized by using Openmp, i recognized that there reduction in this loop so i added "#pragma omp parallel for reduction(+,ftab)",but it did not work and it gave me this error :
error: user defined reduction not found for ‘ftab’.
```
#pragma omp parallel for reduction(+:ftab)
... |
The operation you want to do isprefix sum. It can be done in parallel. A simple way is to usethrust::inclusive_scanwith OpenMP or TBB backend.
```
thrust::inclusive_scan(thrust::omp::par, ftab, ftab + 65536, fab);
```
or
```
thrust::inclusive_scan(thrust::tbb::par, ftab, ftab + 65536, fab);
```
You could also impl... |
This question already has answers here:Is short-circuiting logical operators mandated? And evaluation order?(7 answers)Closed7 years ago.
Let's take this C-code example:
```
int ID = 0;
if( (Check(&ID) == ERROR)
||(ID == -1)
){
return ERROR;
}
```
Do you have any guarantee that(Check(&ID) == ERROR)ischecked... |
Yes you do. For an expression of the formx || y,yis only evaluated ifxevaluates to 0.
This is calledshort-circutting, and also applies to&&.
Your parentheses are also superfluous: the same applies to the equivalent (and, in my opinion, clearer)
if (Check(&ID) == ERROR || ID == -1)
|
Given the filealfa.c:
```
#include <stdio.h>
int main() { // this is a comment
puts("hello world");
}
```
I can format it with GNU Indent like so:
```
$ indent -st alfa.c
#include <stdio.h>
int
main ()
{ // this is a comment
puts ("hello world");
}
```
However the comment is now w... |
indent -c0 -nut -ts2
This will change all your tabs to spaces.
the -c0 removes indentation for comments after code (so this will affect all comments).
edit: reduced the spaces in a tab
|
This question already has answers here:What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?(3 answers)Closed7 years ago.
I have been trying to improve my understanding of C/C++ but looking at includes for functions, such asprintf, which I use a lot. However I am running across a syntax which I... |
It defines the variable as a bitfield of length 1 bit.
It's only valid in a struct, and only makes sense if you have multiple bitfields together.
Don't use it as a generic boolean because it doesn't save memory - a single bitfield on its own will still take up a full word of memory.
|
Another company gives me three files(demo.c,api.h,libapi.so). they told me that't enough for develop. I'm confuse how to build these thing together.
I use gcc demo.c -o demo -l libapi.so . But's it's said "ld: library not found". I use Mac OS system. Some websites said i should use Linux to use .so file. what should ... |
*.so is "shared object" it works only on Linux. The Windows counterpart of *.so is DLL.These are combiled object code.
What you have to do is
1] "compile" your .c to .o [object file]
2] "Link" the new .o file with the .so
|
I have a socket server which should receive a message and write an answer. For some messages I want to send a special answer. If the message is for example"Hello"I want to answer"Hi!". Here is a part of my code:
```
...
char in[2000];
char out[2000];
...
while((read_size = recv(fd, in, 2000, 0)) > 0){
if(strcmp(... |
Usestrncmpfunction, which compares the firstnbytes of the string:
```
if (strncmp(in, "Hello", strlen("Hello")) == 0) ...
```
|
I am trying to make this for-loop parallelized by using Openmp, i recognized that there reduction in this loop so i added "#pragma omp parallel for reduction(+,ftab)",but it did not work and it gave me this error :
error: user defined reduction not found for ‘ftab’.
```
#pragma omp parallel for reduction(+:ftab)
... |
The operation you want to do isprefix sum. It can be done in parallel. A simple way is to usethrust::inclusive_scanwith OpenMP or TBB backend.
```
thrust::inclusive_scan(thrust::omp::par, ftab, ftab + 65536, fab);
```
or
```
thrust::inclusive_scan(thrust::tbb::par, ftab, ftab + 65536, fab);
```
You could also impl... |
This question already has answers here:Is short-circuiting logical operators mandated? And evaluation order?(7 answers)Closed7 years ago.
Let's take this C-code example:
```
int ID = 0;
if( (Check(&ID) == ERROR)
||(ID == -1)
){
return ERROR;
}
```
Do you have any guarantee that(Check(&ID) == ERROR)ischecked... |
Yes you do. For an expression of the formx || y,yis only evaluated ifxevaluates to 0.
This is calledshort-circutting, and also applies to&&.
Your parentheses are also superfluous: the same applies to the equivalent (and, in my opinion, clearer)
if (Check(&ID) == ERROR || ID == -1)
|
Given the filealfa.c:
```
#include <stdio.h>
int main() { // this is a comment
puts("hello world");
}
```
I can format it with GNU Indent like so:
```
$ indent -st alfa.c
#include <stdio.h>
int
main ()
{ // this is a comment
puts ("hello world");
}
```
However the comment is now w... |
indent -c0 -nut -ts2
This will change all your tabs to spaces.
the -c0 removes indentation for comments after code (so this will affect all comments).
edit: reduced the spaces in a tab
|
This question already has answers here:What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?(3 answers)Closed7 years ago.
I have been trying to improve my understanding of C/C++ but looking at includes for functions, such asprintf, which I use a lot. However I am running across a syntax which I... |
It defines the variable as a bitfield of length 1 bit.
It's only valid in a struct, and only makes sense if you have multiple bitfields together.
Don't use it as a generic boolean because it doesn't save memory - a single bitfield on its own will still take up a full word of memory.
|
Another company gives me three files(demo.c,api.h,libapi.so). they told me that't enough for develop. I'm confuse how to build these thing together.
I use gcc demo.c -o demo -l libapi.so . But's it's said "ld: library not found". I use Mac OS system. Some websites said i should use Linux to use .so file. what should ... |
*.so is "shared object" it works only on Linux. The Windows counterpart of *.so is DLL.These are combiled object code.
What you have to do is
1] "compile" your .c to .o [object file]
2] "Link" the new .o file with the .so
|
This question already has an answer here:Why can't I pass constant arrays as arguments?(1 answer)Closed7 years ago.
In Fortran, one can pass an array constructed on the fly to a subroutine:
```
call sub_that_wants_3_elm_array((/1,2,3/),output_arg)
```
Is it possible to do something analogous in C? This seems awful... |
Yes. It's possible usingcompound literals(since C99).
E.g.
```
#include <stdio.h>
void fun(int *a)
{
printf("%d\n", a[2]); //prints 72
}
int main(void)
{
fun((int[]){1, 99, 72});
}
```
You can find some more examples from the links as well:
The New C: Compound LiteralsCompound Literals - gcc
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.