question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
I am learning C and am having trouble passing the pointer of a 2D array to another function that then prints the 2D array. Any help would be appreciated.
```
int main( void ){
char array[50][50];
int SIZE;
...call function to fill array... this part works.
printarray( array, SIZE );
}
void printarr... |
char **doesn't represent a 2D array - it would be an array of pointers to pointers. You need to change the definition ofprintarrayif you want to pass it a 2D array:
```
void printarray( char (*array)[50], int SIZE )
```
or equivalently:
```
void printarray( char array[][50], int SIZE )
```
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
Zlibis freely available and reusable, even in proprietary software. (Here is the license.) There is no reason to try and recreate it.
|
I'm wondering if there is a gcc macro that will tell me the Linux kernel version so I can set variable types appropriately. If not, how would I go about defining my own macro that does this?
|
Thelinux/version.hfile has a macro calledKERNEL_VERSIONwhich will let you check the version you want against the current linux headers version (LINUX_VERSION_CODE) installed. For example to check if the current Linux headers are for kernelv2.6.16or earlier:
```
#include <linux/version.h>
#if LINUX_VERSION_CODE <= KE... |
The codes are
```
i=0;
while (fscanf(fp, "%[^,],%[^,],%[^\n]\n", &a,&b,&c) == 3) i++;
```
the file is
```
abc,def,ghi
cdb,adf,wea
adf,adf,wee
```
but the result are
```
a=abc
b=def,ghi
c=cdb
```
what is the problem? thank you.
|
Try
```
while (fscanf(fp, "%[^,],%[^,],%[^\n]\n", a,b,c) == 3) i++;
```
You are declaring a, b, and c to be arrays. What you want is to pass the pointer to the arrays intofscanf. You need to either specify the pointer asaor as&a[0].
[EDIT]
The following program works for me. Can you try it?
```
#include <stdio.h>... |
I have a question regarding passing c string into function.
If I have a function:
```
void reverse(char* c){
//here is the reverse code
}
```
In the main:
```
int main(){
char* c1="abcd";
char c2[5]="abcd";
char * c3=new char[5];
c3="abcd";
}
```
In my test, only c1 is not allow to pass into the fu... |
Your code is C++, not C;new char[5]is a syntax error in C.
C and C++ are two different languages. In C++, string literals areconst, and passing a string literal to a function that takes achar*argument is an error. You should have gotten an error message (which you haven't bothered to show us) from your C++ compiler.... |
I have a byte array:
```
byte data[2]
```
I want to to keep the 7 less significant bits from the first and the 3 most significant bits from the second.
I do this:
```
unsigned int the=((data[0]<<8 | data[1])<<1)>>6;
```
Can you give me a hint why this does not work?
If I do it in different lines it works fine.
|
Can you give me a hint why this does not work?
Hint:
You have two bytes and want to preserve 7 less significant bits from the first and the 3 most significant bits from the second:
```
data[0]: -xxxxxxx data[1]: xxx-----
```
-'s represent bits to remove, x's represent bits to preserve.
After this
```
(data[0]... |
i have created a Linux network app with C and it kind of works
except that it every time i run it , it binds to a new Random port
```
//Create Socket
int socket_desc;
socket_desc=socket(AF_INET,SOCK_STREAM,0);
if (socket_desc==-1)
perror("Create socket");
struct sockaddr_in address;
address.sin_family = AF_INET;
a... |
You need to use port number greater than 1024. Port numbers less then 1024 are reserved ports and are used by standard services.
|
I have an array of box2d bodies, initialized like this:
```
b2Body *touchedBodies[10];
```
I need to populate it with several b2Bodies, and I want to set the next b2Body into the first available place -- the place where I haven't put a b2Body yet. So I'm looking for something like this:
```
touchedBodies[touchedBod... |
You could use a dynamic container like the Vector.
You could store the index of the last inserted element.
```
// sample without failsave
int openSpot = 0;
touchedBodies[openSpot] = someB2Body;
openSpot++;
```
You could initialize this array with nullpointer and then iterate through.
```
// sample without failsav... |
I want to get the IP address of the client who’s just connected into my server running WinSock2. I’m using C.
|
You could get the client's IP-address and port via the call toaccept().
Just pass in the appropriate data into the last two parameters.
```
struct sockaddr_in sa = {0}; /* for TCP/IP */
socklen_t socklen = sizeof sa;
... = accept(..., (struct sockaddr *) &sa, &socklen);
```
For detailsplease read here.
|
man getdensts says that in d_off an offset to next struct dirent is kept. But what should be kept in this field for last dirent? I was unable to find this SVr4 standard to look there, but man says nothing
|
"SVr4" meansUnix System V Release 4. Solaris is based on that, andSolaris says:
Thed_offentry contains a value which is interpretable only by the filesystem that generated it. It may be supplied as an offset tolseek(2)to find the entry following the current one in a directory.
If you look at theexample in the Linux ... |
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
The bitwiseANDoperator(&)compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
So if (button & 1) is 1 thenif(button & 1)==1evaluatestrueotherwise evaluates tofalse.
|
I am studying the FAT32 manual, now i want to write a program to browse the device. How to read a specific sector of the device, i do not want to load the entire device as a file into memory, please suggest some system call's to get started.
|
Find the block device in/dev/, then your system calls areopen,lseek, andread. Higher level stuff likefopen,fseek, andfreadwill work too.Everything is a file.
|
I have a algorithm question here. There are 10 threads in the system and you are given a link list with 10 K elements in it. How do you do the thread synchronization (addition deletion etc.) so that it is optimized for performance? Using a mutex for the list is not advisable as it will slow down performance.
|
If all the positions are accessed with the same frequency and you can modify the list node, you can add a mutex for every node:
```
typedef struct node{
char* data;
struct listNode *next;
pthread_mutex_t lock;
} listNode ;
```
Also depends on the size of the data of the node. If it´s very small, this may ... |
I want to input some strings and sort them alphabetically, at most 100 strings and the length of each string is less than 50, but I get a Segmentation fault.
```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int comp(const void * a, const void * b)
{
return strcmp (*(const char **) a, *(const char *... |
change
```
return strcmp (*(const char **) a, *(const char **) b);
...
qsort(sequences, nr_of_strings, sizeof(char *), comp);
```
to
```
return strcmp ((const char *) a, (const char *) b);
...
qsort(sequences, nr_of_strings, sizeof(char [50]), comp);
```
|
I need to connect more than one keyboard/mouse with a single computer. Manymouse library can identify different mouses, but is there a library which can identify different keyboards?
I mean, when I press Key "E", the program can tell me which keyboard the KeyPress event is from. With C#, the SDGToolkit can do it, is ... |
Know the solution. I can use a hid library to detect different keyboard. Here is an explanation :http://nanlee.wordpress.com/2013/06/12/manykeyboard-using-java-hid-api-to-handle-multiple-keyboard-input/
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
I have a text file called new.txt a... |
usestrstr()to detect the position ofvinoopand then the first position is the position returned bystrstr()+strlen(vinoop)
And then use againstrstr()to detectreguin the string (second position) and then you can extract string between theses 2 positions withstrncpy()
|
I'm trying to adapt the following working code:
http://www.cplusplus.com/reference/cstring/strtok/
as follows:
```
#include <stdio.h>
#include <string.h>
int main (int argc, const char * argv[]) {
char input[10];
scanf("%s", input);
char * pch;
pch = strtok(input, " ");
while (pch != NULL)
{
... |
The%sconversion stops at the first whitespace.
Print your stringbeforecallingstrtok()on it; it will be only"test".
Also, as pointed out by@Paul R, you need to think about the buffer size you're using. 10 characters is very small.
|
Beginner question. I have the following code:
```
char input[10];
scanf("%s", &input);
```
My compiler throws the following warning:
```
warning: format '%s' expects type 'char *', but argument 2 has type 'char (*)[10]'
warning: format '%s' expects type 'char *', but argument 2 has type 'char (*)[10]'
```
Chan... |
Because an array already can be used as a pointer, so you don't need to the address-of operator.
If you read the warning message again, you will see that when you use the address-of operator on the array, you get a pointer to the array.
|
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
The bitwiseANDoperator(&)compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
So if (button & 1) is 1 thenif(button & 1)==1evaluatestrueotherwise evaluates tofalse.
|
I am studying the FAT32 manual, now i want to write a program to browse the device. How to read a specific sector of the device, i do not want to load the entire device as a file into memory, please suggest some system call's to get started.
|
Find the block device in/dev/, then your system calls areopen,lseek, andread. Higher level stuff likefopen,fseek, andfreadwill work too.Everything is a file.
|
I have a algorithm question here. There are 10 threads in the system and you are given a link list with 10 K elements in it. How do you do the thread synchronization (addition deletion etc.) so that it is optimized for performance? Using a mutex for the list is not advisable as it will slow down performance.
|
If all the positions are accessed with the same frequency and you can modify the list node, you can add a mutex for every node:
```
typedef struct node{
char* data;
struct listNode *next;
pthread_mutex_t lock;
} listNode ;
```
Also depends on the size of the data of the node. If it´s very small, this may ... |
I want to input some strings and sort them alphabetically, at most 100 strings and the length of each string is less than 50, but I get a Segmentation fault.
```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int comp(const void * a, const void * b)
{
return strcmp (*(const char **) a, *(const char *... |
change
```
return strcmp (*(const char **) a, *(const char **) b);
...
qsort(sequences, nr_of_strings, sizeof(char *), comp);
```
to
```
return strcmp ((const char *) a, (const char *) b);
...
qsort(sequences, nr_of_strings, sizeof(char [50]), comp);
```
|
I need to connect more than one keyboard/mouse with a single computer. Manymouse library can identify different mouses, but is there a library which can identify different keyboards?
I mean, when I press Key "E", the program can tell me which keyboard the KeyPress event is from. With C#, the SDGToolkit can do it, is ... |
Know the solution. I can use a hid library to detect different keyboard. Here is an explanation :http://nanlee.wordpress.com/2013/06/12/manykeyboard-using-java-hid-api-to-handle-multiple-keyboard-input/
|
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened,visit the help center.Closed10 years ago.
I have a text file called new.txt a... |
usestrstr()to detect the position ofvinoopand then the first position is the position returned bystrstr()+strlen(vinoop)
And then use againstrstr()to detectreguin the string (second position) and then you can extract string between theses 2 positions withstrncpy()
|
I'm trying to adapt the following working code:
http://www.cplusplus.com/reference/cstring/strtok/
as follows:
```
#include <stdio.h>
#include <string.h>
int main (int argc, const char * argv[]) {
char input[10];
scanf("%s", input);
char * pch;
pch = strtok(input, " ");
while (pch != NULL)
{
... |
The%sconversion stops at the first whitespace.
Print your stringbeforecallingstrtok()on it; it will be only"test".
Also, as pointed out by@Paul R, you need to think about the buffer size you're using. 10 characters is very small.
|
Beginner question. I have the following code:
```
char input[10];
scanf("%s", &input);
```
My compiler throws the following warning:
```
warning: format '%s' expects type 'char *', but argument 2 has type 'char (*)[10]'
warning: format '%s' expects type 'char *', but argument 2 has type 'char (*)[10]'
```
Chan... |
Because an array already can be used as a pointer, so you don't need to the address-of operator.
If you read the warning message again, you will see that when you use the address-of operator on the array, you get a pointer to the array.
|
This question already has answers here:Why does this program give segmentation fault?(3 answers)Closed10 years ago.
I wrote a string copy program using pointer,but it got a segmentation fault,don't know why.
Thanks
here is my code:
```
#include<stdio.h>
void strcp(char *s,char *t){
while(*s++=*t++)
;
... |
dis pointing to a string literal it is undefined behavior to write to a string literal. You could alternatively definedas follows:
```
char d[]="this is destination";
```
Also you need to fix theprintfand loop from this:
```
while(d++){
printf("%s " ,*d);
}
```
to this:
```
printf("%s " ,d);
```
and you can ... |
I'm trying to increase the size of an array dynamically. Is there any standard C or C++ function, which appends additional space at the end of an array or removes it?
I know, this is difficult, since it cannot be assured that there is enough space at the end on the heap. But shouldn't this be the job of an operating s... |
The function you're looking for isrealloc()in C, which is also present in the C++ STL asstd::realloc
Though as you mentioned C++, you could also go for an standard container likestd::vectorwhich encapsulate the associated memory management.
|
This question already has answers here:Accessing arrays by index[array] in C and C++(2 answers)Closed10 years ago.
I am dealing pointers in c and when i run the following code i get "l" as the output! Why?
```
char *s = "Hello, World!";
printf("%c", 2[s]);
```
What does 2[s] signify?
|
2[s]is same ass[2]because compiler convert both into*(2 + s)
here is a good link for you:why are both index[array] and array[index] valid in C?
|
I am working on a project within C code and trying to use a ternary if statement but its always returning false and I don't understand why.
The ternary if statement is:
```
(reportParameterArray[P_TARGET] == '\0') ? reportParameterArray[P_TARGET] : "HELLO"
```
What I am trying to do is ifreportParameterArray[P_TARG... |
The ternary operation takes the form
```
condition ? when true : when false;
```
e.g
```
(var == 2) ? "Var equals 2!" : "Var doesn't equal 2!";
```
Hence you have your condition backwards.
|
The PIC is a16F630
```
#FUSES NOWDT, INTRC_IO, PROTECT, NOBROWNOUT, MCLR, CPD, NOPUT
#use delay(clock=4000000)
#use fast_io(A)
```
later, in a function:
```
#asm nop nop nop nop nop #endasm
```
Which C compiler could have been used to compile this code?
|
Looks like theCCS PIC MCU C compiler.
As you can see at the link its pre-processor supports#FUSES,#USE,#ASMand#ENDASM.
|
```
#define DEBUG_BREAK(a)\
if ((a)) \
{\
__asm int 3;\
}
```
I have defined a macro as above, and try to use it
```
#include "test_define.h"
int main()
{
DEBUG_BREAK(1 == 1);
return 0;
}
```
But this sample will not compile. The compiler would complain the parenthesis is not closed. If I add anothe... |
The macro
```
#define DEBUG_BREAK(a)\
if ((a)) \
__asm int 3;
```
works fine but
```
#define DEBUG_BREAK(a)\
if ((a)) \
{\
__asm int 3;\
}
```
doesn't! And I think anyone could guess why!! The new line operator is the problem making guy!
It takes
```
__asm int 3;\
}
```
as
```
__asm int 3; }
``... |
I need to know how can I add 2 "hours" as integer?
It is 24-h format
```
int add2Hours(int _time1,int _time2)
{
}
```
sample: 13:45 is: (hhmm) 1345
1345 + 30 returns 1415
|
Your time is inhhmmformat, separate thehhandmmpart. Then add the parts separately.
```
int add2hours(int _time1, int _time2)
{
int hh1, hh2, mm1, mm2;
int rHH,rMM, res;
hh1 = _time1/100;
hh2 = _time2/100;
mm1 = _time1 % 100;
mm2 = _time2 % 100;
rMM = mm1 + mm2;
rHH = rMM/60;
rMM = ... |
What's the simplest way to copy the unix file permissions of a file and set them to another file? Is there a way to store a file's permissions to a variable and then use that variable to set those permissions to another file?
|
Sure. Usestat()andchmod()(may need root).
```
#include <sys/stat.h>
struct stat st;
stat("/foo/bar.txt", &st);
chmod("/baz/quirk.jpg", st.st_mode);
```
|
This question already has answers here:How to access a local variable from a different function using pointers?(10 answers)Can a local variable's memory be accessed outside its scope?(21 answers)Closed10 years ago.
```
char* f()
{
char s[100];
//....function body code
return s;
}
```
Why should it not be written lik... |
sis a local variable that only exists within the function.
Once the function exits,sno longer exists, and its memory will be re-allocated to other parts of your program.
Therefore, your function is returning a pointer to a random meaningless block of memory.
|
I want to get at the value in server_rec.module_config. Does request_rec have any sort of reference to the server_rec? I am not seeing one in the httpd.h file but I could be missing it.
Basically I want to access the configuration file for the module while in my handler and I know I can do that with ap_get_module_con... |
After more looking around I finally managed to come across it.
In the request_rec there is a variable called server which is a server_rec*. So to access the config file you would use
```
ap_get_module_config(r->server->module_config, &my_module)
```
where r is the request_rec passed into the handler.
|
In Dennis Ritchie I found this,
```
struct rect r , *rp = r;
```
then these four expressions are equivalent :
r.pt1.xrp->pt1.x(r.pt1).x(rp->pt1).x
because operators associate left to right.Shouldn't it be struct rect *rp = &r?
|
Absolutely -- the address operator is required,otherwise you get a compile-time error:
```
incompatible types when initializing type ‘struct rect *’ using type ‘struct rect’
```
|
I am reading files in a directory using :
```
glob_t* globlist;
// initialization.
glob(pattern, GLOB_ERR | GLOB_BRACE, NULL, globlist);
```
This works well, but now the order of processing for each file is relevant, so I would like to know if there is a specific ordering for the matches, or if there is none, if it ... |
As quoted from the man pagehere
The pathnames shall be in sort order as defined by the current setting of the LC_COLLATE category;
|
I have some C code which reads in the contents of a HTML form from STDIN and, at the moment tokenizes the string.
```
fgets(formip, 1024, stdin);
pch = strtok (formip,"=&");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, "=&");
printf ("<br>\n");
}
```
This produces output like this:
``... |
You can usestrcmpto check if the strings are equal or not, it is important not to skip the next call tostrtokotherwise you will end up in an infinite loop:
```
while (pch != NULL )
{
if( strcmp( pch, "value") != 0 && strcmp(pch, "checkbox") != 0)
{
printf ("%s\n",pch);
printf ("<br>\n");
... |
I would like to combine a struct and a byte array in a union. The compiler is gcc.
Is the following considered good/save code for a 32bit embedded controller (AVR)?
Do I have to worry about the byte aligment?
```
#include <stdint.h>
typedef int8_t S8;
typedef union {
struct {
S8 a;
S8 b;
... |
I think what you're showing is fine, but you should be worried if you ever use an array ofs_tas there might be padding at the end.
You can tell GCC to "pack" the struct using the extension__attribute__syntax. Add__attribute__((packed))before the final;.
|
Is it possible to check which db2 code page is used in communication between ODBC connector and db2 database from c program using ODBC api?
|
It's indicated by the connection attribute SQL_ATTR_CLIENT_CODEPAGE.
Here's the function to obtain it:SQLGetConnectAttr
|
I already know thatif(nan != nan) -> TRUE, which is quite logical(sqrt(-1)has to be unequal to0/0).
The following line of code is also logical:
```
if(nan > 90.0f) -> FALSE
```
...nanis not a number, thus it cannot be greater or smaller than a number.
However, I do not understand whyif(nan >= 90.0f) -> TRUE?!?!
I... |
This would appear to be a compiler bug[1]. You should report it to Tasking.
[1] From what I can see (http://www.tasking.com/products/c166/), Tasking does not claim conformance to IEEE-754, so this behavior may not actually be contrary to their published documentation. It is, however, contrary to common sense and go... |
Why the following code return error when variable is declared global.
```
int add(int x, int y) {
return x+y;
}
int ab = add(10, 20);
int main(void) {
printf("%d", ab);
}
```
But if I call like this:
```
int add(int x, int y) {
return x+y;
}
int main(void) {
int ab = add(10, 20); // Variable d... |
Initializers for global variables must beconstant, they can't be an arbitrary expression.
|
This question already has answers here:Set variable text column width in printf(2 answers)Closed10 years ago.
I'm pretty sure there's no way to do this, but I was wondering, so here goes...
Say I get several int values from the user, and I know for a fact that the 1st
value is the largest.
Any way I can use the len... |
Do it like so:
```
int n = <some value>;
int i = (int) log10(n) + 1;
printf("%*d", i, n);
```
The*serves as a placeholder for thewidthbeing passed as an argument toprintf().
|
When freeing memory in C and C++, do I only need the memory address or does it require any specific variable?
So if I were to do something such as:
```
int* test()
{
int* x = new int(5);
return x;
}
int main(int argc, char** argv)
{
int* y = test();
delete y;
return 0;
}
```
Would this cause ... |
No, there wouldn't be any leaks there, but then again, neither would there be in
```
int test()
{
return 5;
}
int main(int argc, char** argv)
{
int y = test();
return 0;
}
```
Avoid dynamic allocation if you can.
|
This question already has answers here:C sizeof a passed array [duplicate](7 answers)Closed10 years ago.
Within a function I have declared an array:
```
int char_count_array[118] = {0};
```
Later on, I pass this array to a function and calculate the following:
```
int xx = sizeof(char_count_array);
int xy = sizeo... |
If you are passing it to a function, it's most likely going in asint*instead ofint[118]. So yoursizeofis returning the size of a pointer. When you pass C arrays to functions, it's conventional to also pass the number of elements.
```
my_func( arr, sizeof(arr)/sizeof(arr[0]) );
```
|
I want to use array of 4 dimension.
```
int A[80][80][80][80];
```
When I try to use it I get Segmentation fault (core dumped).
For example:
```
for(i=0;i<80;i++)
for(j=0;j<80;j++)
for(k=0;k<80;k++)
for(l=0;l<80;l++)
A[i][j][k][l]=i+j+k+l;
printf("%d\n",A[0][1][2][3]);
```
|
That's a pretty huge array -40,960,000 * sizeof(int)bytes. If you're declaring it on the stack, you're sure to be overflowing available stack memory. Try heap allocating it instead.
```
int* A = malloc(80 * 80 * 80 * 80 * sizeof(int));
/* use A */
free(A);
```
Or, better, as John Bode suggested
```
int (*A)[80][8... |
I have written a shared library (.so) for an android emulator. It is supposed to read and write to the /dev file of a sensor device. I have an app which list the emulators sensors and prints their readings. I have pushed the sensors.goldfish.so file to the emulator through adb, so my question is how do I find out if m... |
When you read/write to the sensor, you could also write to a text log something like "reading from sensor value %d" and "writing to sensor value %d".
Example (not tested):
```
FILE *f;
f = fopen("/sdcard/log.txt", "a");
if (isReading) {
fprintf(f, "reading\n");
}
else {
fprintf(f, "writing\n");
}
fclose(f);
... |
I have a rounding function,
```
float myround(float x, int places)
{
float const shift = powf(10.0f, places);
x *= shift;
x = floorf(x + 0.5f);
x /= shift;
return x;
}
```
When I try to round of numbers to lets say 4 decimal places and then print the number with
```
printf("%f ", x);
```
I get the ... |
You can't round floats, you can only print them to a specific precision. All floats are always "unrounded", although you can obviously change the value to more closely approximate a rounded amount.
|
I was writing a small text matching program in C, which basically checks for the presence of a few characters in some strings (in form of char arrays). Its working now and I have a code block like this:
```
if (c == 'A') return 1;
else if (c == 'B') return 1;
else if (c == 'C') return 1;
....
....
else if (c == 'Z') ... |
I'd recommend doing the following:
```
#include <ctype.h>
...
return isupper(c)
```
Instead of manually checking all of them. The standard C library functions are reasonably fast so performance should be acceptable.
|
Let's asume I have a struct as follows:
```
struct person {
int age;
char name[24];
} person;
```
and the user gives an argument which struct member the program should read../program age
```
int main(int argc, char **argv) {
int i;
i = person.argv[1];
printf("%i\n", i);
}
```
this is obviously ... |
C does not support run-time reflection in any way that would make that easy to get to work. I suspect the best you can do is to write a code-generator that writes the string-to-struct member selection function.
|
Iread, that the best way to place functions is to create .h file with function prototypes, some .c file with those functions (including their bodies) and normal .c file with main().
This is how my simple project looks:it works properly, but how Visual Studio knows how to link them properly? In GCC I can control the or... |
You shouldn't need to control the order - the compiler does that. If the files are in the project, the linker will do its job.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
You have to specify the size if you are going to define array float in this way:
```
float array[4];
```
You can define the array without the size. but it should be in this way:
```
float array[] = {3.544, 5.544, 6.544, 6.544};
```
see the following topic for more details:How to initialize all members of an array ... |
In Master Algorithm with C, the author has declared the structure of a chained hash table like below:
```
typedef struct CHTbl_ {
int buckets;
int (*h)(const void *key);
int (*match)(const void *key1, const void *key2);
void (*destroy)(void *data);
int ... |
Thetableis aListpointer, and is being used to represent an array ofLists. It is probably being initialized like this:
```
htbl->table = malloc(sizeof(List) * htbl->buckets);
```
|
I have no idea how to achieve this, but I have a HTML form, with several different elements in it.
For testing, right now, all I would like to do is write a piece of C code that will take anything that is submitted and print this out on the screen.
I can write my own parsing code - I just cannot work out how to get ... |
Assuming you have a web server configured to allow you to do CGI, your HTML form needs to be written to eitherGETorPOSTthe form data to the CGI script. You can then implement a CGI script in C to process the form data.
As a starter CGI script, you can simply echo whatever is provided in the input as the output.
```
... |
Void variable has nothing to do and also void pointer can only be pointed with casting.
So void pointer is used when we actually don't know where and of which data type we want to point. But what is of void variable?
Any practical example?
|
In Cvoidcan't be considered a data type, it is a keyword used as a placeholder in place of a data type to show that actually there is no data.
For example consider the functionvoid f(void);. Here the keyword void is used to mean the absence of any parameters passed and returned values.
Butvoid *ptr;is different in m... |
I want to check if a string is a number with this code. I must check that all the chars in the string are integer, but the while returns always isDigit = 1. I don't know why that if doesn't work.
```
char tmp[16];
scanf("%s", tmp);
int isDigit = 0;
int j=0;
while(j<strlen(tmp) && isDigit == 0){
if(tmp[j] > 57 && t... |
Forget about ASCII code checks, useisdigitorisnumber(seeman isnumber). The first function checks whether the character is 0–9, the second one also accepts various other number characters depending on the current locale.
There may even be better functions to do the check – the important lesson is that this is a bit mo... |
I want to make some shared library settings using pkg-config that would be applied when any ".c" file is compiled inside a directory. How do I access the name of the file in the make rule?
For example, if these are files in a directory
```
foo1.c
bar.c
foobar.c
```
If I runmake foobar, I want an object filefoobarge... |
If any of your C-files in that directory don't depends on others, you may write such makefile:
```
CC = gcc
LDFLAGS = -l...
DEFINES = -D...
CFLAGS = -Wall -Werror ...
%: %.c
$(CC) $(LDFLAGS) $(CFLAGS) $(DEFINES) $< -o $@
```
|
What does a number argument inprintfwithout quotes do?
e.g.printf( 3 + "goodbye");results in output dbye. Why do I get this output?
|
3 + "goodbye"is equivalent to&"goodbye"[3]- in other words it's just a pointer to the fourth element of "goodbye" and so your example will print "dbye".
|
You know when we do embedded system development,we'll burn a root file systemfirst(likecramfsetc.) and then burn a Linux kernel.Since there's already a file system in the Linux kernel, why should we burn a root file system first?
|
Linux kernel contains scheduler code, memory management driver, file system management driver, generic device drivers, IPC driver, network driver, architecture specific device drivers, firmware code and kernel headers etc.File system is not part of linux kernel. But file system managing drivers are part of linux kerne... |
A function prototype is
int alt_irq_register (alt_u32 id,
void* context,
void (*isr)(void*, alt_u32));
What does the last part mean? What is the*isrdoing?
|
It is a pointer to a function. You must use a function as parameter of thealt_irq_registerfunction. Example:
```
void irq_handler(void *ptr, alt_u32 val) { /* my function */
/* I'm handling the interupt */
}
int alt_irq_register (alt_u32 id, void* context, void (*isr)(void*, alt_u32));
```
In your code, you must... |
Let's asume I have a struct as follows:
```
struct person {
int age;
char name[24];
} person;
```
and the user gives an argument which struct member the program should read../program age
```
int main(int argc, char **argv) {
int i;
i = person.argv[1];
printf("%i\n", i);
}
```
this is obviously ... |
C does not support run-time reflection in any way that would make that easy to get to work. I suspect the best you can do is to write a code-generator that writes the string-to-struct member selection function.
|
Iread, that the best way to place functions is to create .h file with function prototypes, some .c file with those functions (including their bodies) and normal .c file with main().
This is how my simple project looks:it works properly, but how Visual Studio knows how to link them properly? In GCC I can control the or... |
You shouldn't need to control the order - the compiler does that. If the files are in the project, the linker will do its job.
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.Questions asking for code mustdemonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and theexpectedresults. See also:Stack Overflow question checklistClosed9 ... |
You have to specify the size if you are going to define array float in this way:
```
float array[4];
```
You can define the array without the size. but it should be in this way:
```
float array[] = {3.544, 5.544, 6.544, 6.544};
```
see the following topic for more details:How to initialize all members of an array ... |
In Master Algorithm with C, the author has declared the structure of a chained hash table like below:
```
typedef struct CHTbl_ {
int buckets;
int (*h)(const void *key);
int (*match)(const void *key1, const void *key2);
void (*destroy)(void *data);
int ... |
Thetableis aListpointer, and is being used to represent an array ofLists. It is probably being initialized like this:
```
htbl->table = malloc(sizeof(List) * htbl->buckets);
```
|
I have no idea how to achieve this, but I have a HTML form, with several different elements in it.
For testing, right now, all I would like to do is write a piece of C code that will take anything that is submitted and print this out on the screen.
I can write my own parsing code - I just cannot work out how to get ... |
Assuming you have a web server configured to allow you to do CGI, your HTML form needs to be written to eitherGETorPOSTthe form data to the CGI script. You can then implement a CGI script in C to process the form data.
As a starter CGI script, you can simply echo whatever is provided in the input as the output.
```
... |
Void variable has nothing to do and also void pointer can only be pointed with casting.
So void pointer is used when we actually don't know where and of which data type we want to point. But what is of void variable?
Any practical example?
|
In Cvoidcan't be considered a data type, it is a keyword used as a placeholder in place of a data type to show that actually there is no data.
For example consider the functionvoid f(void);. Here the keyword void is used to mean the absence of any parameters passed and returned values.
Butvoid *ptr;is different in m... |
I want to check if a string is a number with this code. I must check that all the chars in the string are integer, but the while returns always isDigit = 1. I don't know why that if doesn't work.
```
char tmp[16];
scanf("%s", tmp);
int isDigit = 0;
int j=0;
while(j<strlen(tmp) && isDigit == 0){
if(tmp[j] > 57 && t... |
Forget about ASCII code checks, useisdigitorisnumber(seeman isnumber). The first function checks whether the character is 0–9, the second one also accepts various other number characters depending on the current locale.
There may even be better functions to do the check – the important lesson is that this is a bit mo... |
I want to make some shared library settings using pkg-config that would be applied when any ".c" file is compiled inside a directory. How do I access the name of the file in the make rule?
For example, if these are files in a directory
```
foo1.c
bar.c
foobar.c
```
If I runmake foobar, I want an object filefoobarge... |
If any of your C-files in that directory don't depends on others, you may write such makefile:
```
CC = gcc
LDFLAGS = -l...
DEFINES = -D...
CFLAGS = -Wall -Werror ...
%: %.c
$(CC) $(LDFLAGS) $(CFLAGS) $(DEFINES) $< -o $@
```
|
What does a number argument inprintfwithout quotes do?
e.g.printf( 3 + "goodbye");results in output dbye. Why do I get this output?
|
3 + "goodbye"is equivalent to&"goodbye"[3]- in other words it's just a pointer to the fourth element of "goodbye" and so your example will print "dbye".
|
You know when we do embedded system development,we'll burn a root file systemfirst(likecramfsetc.) and then burn a Linux kernel.Since there's already a file system in the Linux kernel, why should we burn a root file system first?
|
Linux kernel contains scheduler code, memory management driver, file system management driver, generic device drivers, IPC driver, network driver, architecture specific device drivers, firmware code and kernel headers etc.File system is not part of linux kernel. But file system managing drivers are part of linux kerne... |
In Master Algorithm with C, the author has declared the structure of a chained hash table like below:
```
typedef struct CHTbl_ {
int buckets;
int (*h)(const void *key);
int (*match)(const void *key1, const void *key2);
void (*destroy)(void *data);
int ... |
Thetableis aListpointer, and is being used to represent an array ofLists. It is probably being initialized like this:
```
htbl->table = malloc(sizeof(List) * htbl->buckets);
```
|
I have no idea how to achieve this, but I have a HTML form, with several different elements in it.
For testing, right now, all I would like to do is write a piece of C code that will take anything that is submitted and print this out on the screen.
I can write my own parsing code - I just cannot work out how to get ... |
Assuming you have a web server configured to allow you to do CGI, your HTML form needs to be written to eitherGETorPOSTthe form data to the CGI script. You can then implement a CGI script in C to process the form data.
As a starter CGI script, you can simply echo whatever is provided in the input as the output.
```
... |
Void variable has nothing to do and also void pointer can only be pointed with casting.
So void pointer is used when we actually don't know where and of which data type we want to point. But what is of void variable?
Any practical example?
|
In Cvoidcan't be considered a data type, it is a keyword used as a placeholder in place of a data type to show that actually there is no data.
For example consider the functionvoid f(void);. Here the keyword void is used to mean the absence of any parameters passed and returned values.
Butvoid *ptr;is different in m... |
I want to check if a string is a number with this code. I must check that all the chars in the string are integer, but the while returns always isDigit = 1. I don't know why that if doesn't work.
```
char tmp[16];
scanf("%s", tmp);
int isDigit = 0;
int j=0;
while(j<strlen(tmp) && isDigit == 0){
if(tmp[j] > 57 && t... |
Forget about ASCII code checks, useisdigitorisnumber(seeman isnumber). The first function checks whether the character is 0–9, the second one also accepts various other number characters depending on the current locale.
There may even be better functions to do the check – the important lesson is that this is a bit mo... |
I want to make some shared library settings using pkg-config that would be applied when any ".c" file is compiled inside a directory. How do I access the name of the file in the make rule?
For example, if these are files in a directory
```
foo1.c
bar.c
foobar.c
```
If I runmake foobar, I want an object filefoobarge... |
If any of your C-files in that directory don't depends on others, you may write such makefile:
```
CC = gcc
LDFLAGS = -l...
DEFINES = -D...
CFLAGS = -Wall -Werror ...
%: %.c
$(CC) $(LDFLAGS) $(CFLAGS) $(DEFINES) $< -o $@
```
|
What does a number argument inprintfwithout quotes do?
e.g.printf( 3 + "goodbye");results in output dbye. Why do I get this output?
|
3 + "goodbye"is equivalent to&"goodbye"[3]- in other words it's just a pointer to the fourth element of "goodbye" and so your example will print "dbye".
|
You know when we do embedded system development,we'll burn a root file systemfirst(likecramfsetc.) and then burn a Linux kernel.Since there's already a file system in the Linux kernel, why should we burn a root file system first?
|
Linux kernel contains scheduler code, memory management driver, file system management driver, generic device drivers, IPC driver, network driver, architecture specific device drivers, firmware code and kernel headers etc.File system is not part of linux kernel. But file system managing drivers are part of linux kerne... |
A function prototype is
int alt_irq_register (alt_u32 id,
void* context,
void (*isr)(void*, alt_u32));
What does the last part mean? What is the*isrdoing?
|
It is a pointer to a function. You must use a function as parameter of thealt_irq_registerfunction. Example:
```
void irq_handler(void *ptr, alt_u32 val) { /* my function */
/* I'm handling the interupt */
}
int alt_irq_register (alt_u32 id, void* context, void (*isr)(void*, alt_u32));
```
In your code, you must... |
I'm developing a basic program for multicasting frames on a wireless network to determined stations, based on some rules. I uselorconto handle the injection part, but I also need to look for which stations are present (both APs and clients).
I've googled a lot about how to do this, and I found thatiwlib.handlinux/wir... |
It looks that this is near impossible, so I decided to grab wireless packets with libpcap (pcap/pcap.h), and build a list based on its headers (src, dst, bssid).
This helped me a bit with the developing:http://www.tcpdump.org/pcap.html
|
What are the perils of not callingsetsid()when daemonizing a process?
|
When a user logs out from a session, all processes associated with that session are killed. For processes that are daemons you do not want this to happen. The solution is to call setsid. Provided that the daemon is not already a process group leader (which it will not be following the fork performed above), this will:... |
I need to check if in my file there are duplicates entries, in C.
Sample file:
```
/proc/proc1 1000
/proc/proc2 2000
/proc/proc1 3000
```
I need to solve like this:
```
/proc/proc1 1000 3000
/proc/proc2 2000
```
The path (/proc/proc*) can include spaces likes: /proc/proc hello/foo
HereI wrote something to handle... |
```
#include <stdio.h>
#include <string.h>
int main(void){
char str[]= "/proc/proc hello/foo 4000";
char path[256];
char pid[10];
char *p;
p=strrchr(str, ' ');
strcpy(pid, p+1);
*p='\0';
strcpy(path, str);
printf("%s\n", path);// /proc/proc hello/foo
printf("%s\n", pid);// 400... |
As we can print the ASCII code and increment it in C
--> e.g:
```
{
char ch='A';
ch++;
printf("%d",ch);
}
```
this will output "66" on the console.
How can this be done in C++ ??
|
Yes, just cast it to anintbefore you output it, so that it isn't interpreted as a character:
```
char ch = 'A';
ch++;
std::cout << static_cast<int>(ch);
```
Note, however, that this isn't guaranteed to output the value corresponding to the character'B'. If your execution character set is ASCII or some other sane cha... |
I keep getting this error when compiling my program. This is just a small part of my code, so if needed I will provide the rest of the code. Any ideas on why this is occuring?
```
void strip_quotes(char s[]) {
if (s[0]=='"') s=s+1;
if (s[strlen(s)-2]=='"') s[strlen(s)-2]=NULL;
}
```
|
You are setting a character ofstoNULL. The proper way to add a null character to a string is to use'\0'.
To explain the message,NULLis likely defined as(void*)0, so when you assign it, you are convertingvoid*tochar, hence the warning.
|
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened,visit the he... |
That's pretty speculative. But one good reason is becausevoidis not an empty value; it's the absence of a value. For instance, a function with a signature ofint f(void)takes zero arguments, not one.
|
I have twolexfiles with functionsxxlex()andyylex()and I have oneyaccgrammar file. I wanted on a grammatical rule to always invokexxlex(). Butxxlex()is only called once, and I want it to be invoked always. How do I do it?
|
By default, Yacc grammars callyylex()to obtain new tokens.
If you want to callxxlex()some of the time, then you arrange to call it fromyylex()at the appropriate times.
If you wantxxlex()to be called every time, then either rename ityylex()and rename the originalxxlex()tozzlex(), or usebison -p xxso that everything (... |
In all of the gtk examples I've read, callbacks are always static functions. I think I remember reading somewhere that there is a reason for that, but I can't find it now.
Must GTK callback functions be static? How come? What would go wrong if I defined them in a different control unit?
|
No. Nothing bad will happen if you make your callback functions not static.
|
I'm trying to write a program that will read the first character in a text file. If I use./a.out myfile.txtit works as intended but if I use./a.out <myfile.txtI getSegmentation fault: 11. The reason why I'm trying to include the<is because this what is in the spec of the assignment. The below code is just a simplified... |
No, nor should you try. Files redirected this way will appear atstdinand you should use that instead (hint: checkargc).
|
I was trying to execute a file which uses the math library(more specifically it was using the sqrt() function). So I typed gcc fileName.c -o fileName, it kept saying "undefined reference to `sqrt'". But then when I was googling, someone said to add -lm at the end of my gcc call, but I don't understand why, can someone... |
C compilation has two distinct steps: compilation to object code, and linking. In compilation to object code, files are compiled as they are, and any external symbols (like those you get by including a header) are left as "blanks." The next stage, linking, is where those blanks are filled in. For many libraries, you h... |
I'm trying to use a few dynamic library I have written but gcc seems to be unable to find them and I'm not understanding why that is. The files libresistance.so, libcomponent.so and libpower.so are all located in /usr/lib the default location for dynamic libs in Linux as I understand it. So what I'm doing wrong?
C fi... |
I found the answer, to be able the compile the program gcc need the .h files and for it to find them they need to be placed in /usr/include.
|
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
```
while (1) {
scanf("%d", &n0);
if (n0==0) break;
...
}
```
|
I'm trying to write a program that will read the first character in a text file. If I use./a.out myfile.txtit works as intended but if I use./a.out <myfile.txtI getSegmentation fault: 11. The reason why I'm trying to include the<is because this what is in the spec of the assignment. The below code is just a simplified... |
No, nor should you try. Files redirected this way will appear atstdinand you should use that instead (hint: checkargc).
|
I was trying to execute a file which uses the math library(more specifically it was using the sqrt() function). So I typed gcc fileName.c -o fileName, it kept saying "undefined reference to `sqrt'". But then when I was googling, someone said to add -lm at the end of my gcc call, but I don't understand why, can someone... |
C compilation has two distinct steps: compilation to object code, and linking. In compilation to object code, files are compiled as they are, and any external symbols (like those you get by including a header) are left as "blanks." The next stage, linking, is where those blanks are filled in. For many libraries, you h... |
I'm trying to use a few dynamic library I have written but gcc seems to be unable to find them and I'm not understanding why that is. The files libresistance.so, libcomponent.so and libpower.so are all located in /usr/lib the default location for dynamic libs in Linux as I understand it. So what I'm doing wrong?
C fi... |
I found the answer, to be able the compile the program gcc need the .h files and for it to find them they need to be placed in /usr/include.
|
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable,visit the help cen... |
```
while (1) {
scanf("%d", &n0);
if (n0==0) break;
...
}
```
|
```
printf("Hello%cWorld\n", '\r');
```
Outputs:
```
World
```
Because'\r'moves the cursor to the beginning of the line
Can I trust that all terminals have this behavior?
|
lib curses will tell you the capabilities of your terminal.
|
I am dying here. So I have a complex number(-4.9991 + 15.2631i). In matlab if I do
```
angle(-4.9991 + 15.2631i) = 1.8873
```
I thought that angle basically calculated like
```
atan(15.2631/-4.9991) = -1.2543
```
Why are these different? I need to write a c function that calculates the angle of a complex number... |
```
-1.2543 + Pi(radians) = 1.8873 (with rounding)
```
As pointed out by others, useatan2()
|
I recently faced an interview question on what's the hidden problem with the following code. I was unable to detect it .Can anyone help?
```
#include<stdio.h>
int main(void)
{
char buff[10];
memset(buff,0,sizeof(buff));
gets(buff);
printf("\n The buffer entered is [%s]\n",buff);
return 0;
}
``... |
The functiongetsaccepts a string from stdin and does not check the capacity of the buffer.This may result in buffer overflow. The standard functionfgets()can be used here.
|
I created a 2D character array using malloc and have been trying to assign its values to '\0'.
```
char **predicate_array = malloc(no_of_lines_in_data_map);
for(int i = 0; i < no_of_lines_in_data_map; i++){
predicate_array[i] = malloc(1024 * sizeof(char));
predicate_array[i][0] = '\0';
}
```
However, when I ... |
the parameter of the first malloc don't fit your 2d-array.
fix it as below
```
char **predicate_array = (char **)malloc(no_of_lines_in_data_map*sizeof(char *));
```
|
I am attempting to convert a negative angle (in degrees) to positive. But I am getting a compile error saying:
test.cpp invalid operands of types 'double' and 'int' to binary 'operator%'test.cpp invalid operands of types 'float' and 'int' to binary 'operator%'
My code:
```
double to_positive_angle(double angle)
{
... |
This version works for all possible inputs, not just ones greater than 3600000, and solves the%issue you were experiencing.
```
double to_positive_angle(double angle)
{
angle = fmod(angle, 360);
if (angle < 0) angle += 360;
return angle;
}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.