question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
This question already has answers here:What is an undefined reference/unresolved external symbol error and how do I fix it?(39 answers)Closed8 years ago.
I have two different projects in a single workspace and both projects are cpp projects. When I am calling cpp function from one project to another project but it is not working and showingundefined referenceto Function Name. at the time of linking.
Calling file is in .c with project name ABC and definition file is .cpp with project name CDE
Please help
|
Your question is a bit vague but the problem could be name mangling. Put your C++ function in anextern "C" { ... }block in order to give it C linkage and prevent the compiler from mangling the name.
|
I have the following code in server.c
```
while (1) {
char msg[1024];
recv(fd, msg, 1024, 0);
}
```
From client, first, I sent "hello world".
And then I received "hello world" in server.
I then sent "hexx" to server.
But I received "hexxo world" on server.
It seems as if msg wasn't cleared fully.
Please let me know what I'm doing wrong.
Cheers.
|
You are allocating 1024 bytes for message and never zeroing that data. You are just reading into the same buffer over and over. First pass it reads "hello world" in the second pass you are putting "hexx" in the same starting address resulting in "hexxo world"
As DoxyLover mentions you can null terminate the newly read string and get what you are looking for.
|
So I have a memory block that is fill with hex values, and I want to read in those hex values as Ascii. Unfortunately, I can't seem to figure out how to do this.
```
char* charstring = malloc(sizeof(uint16_t));
uint8_t test = 0x65;
sprintf(charstring, "%x ", test);
fprintf(Output, "%s", charstring);
free(charstring);
```
This just gives me a ton of "65", not the "e" I was expecting.
I know it's a simple question, but I've literally clicked every link on the front page of google and can't figure out my problem!
|
You get65because you are using%xas the format specifier, change it to%cfor the character value.
Note that you don't have enough space forcharstringfor the null terminator. Fix it.
|
Suppose I am given as input to a functionfoosome pointer*pLthat points to a pointer to a struct that has a pointer field next in it. I know this is weird, but all I want to implement in assembly is the line of code with the ** around it:
```
typedef struct CELL *LIST;
struct CELL {
int element;
LIST next;
};
void foo(LIST *pL){
**(*pL)->next = NULL;**
}
```
How do I implement this in ARM assembly? The issue comes from having nested startements when I want to store such as:
```
.irrelevant header junk
foo:
MOV R1, #0
STR R1, [[R0,#0],#4] @This is gibberish, but [R0,#0] is to dereference and the #4 is to offeset that.
```
|
The sequence would be similar to:
```
... ; r0 = LIST *pL = CELL **ppC (ptr2ptr2cell)
ldr r0,[r0] ; r0 = CELL *pC (ptr2cell)
mov r1,#0 ; r1 = NULL
str r1,[r0,#4] ; (*pL)->next = pC->next = (*pC).next = NULL
```
|
How to iterate through all tids of all threads of the current process? Is there some way that doesn't involve diving into/proc?
|
The code I am using, based on reading/proc
```
#include <sys/types.h>
#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>
```
Then, from inside a funcion:
```
DIR *proc_dir;
{
char dirname[100];
snprintf(dirname, sizeof dirname, "/proc/%d/task", getpid());
proc_dir = opendir(dirname);
}
if (proc_dir)
{
/* /proc available, iterate through tasks... */
struct dirent *entry;
while ((entry = readdir(proc_dir)) != NULL)
{
if(entry->d_name[0] == '.')
continue;
int tid = atoi(entry->d_name);
/* ... (do stuff with tid) ... */
}
closedir(proc_dir);
}
else
{
/* /proc not available, act accordingly */
}
```
|
This make no sense for me:
```
int start_tab[2];
printf("size of an array: %d\n", sizeof(start_tab));
8
```
Why 8?
How make it to be size of 2?
|
Please be noted,sizeofis an operator, not a function.sizeofreturns the size of the supplied datatype.
Why 8?
start_tabbeing of typeint [2], returns2 * sizeof (int)#or8.
How make it to be size of 2?
If you want to get thecountof element in the array, simply divide the total size by the size of a single element, like
```
sizeof(start_tab) / sizeof(start_tab[0])
```
# In your platform,sizeof(int)== 4.
|
I have the following code:
```
struct stest
{
int x;
unsigned char data[];
} x =
{
1, {"\x10\x20\x30\x00\x10"}
};
int main()
{
printf( "x.data: %d\n", (int)x.data[0] );
return 0;
}
```
Which works fine. However, I need to use the size of the "data".
If I do:
```
printf( "sizeof x.data: %d\n", (int)sizeof(x.data) );
```
I get the error:
invalid application of ‘sizeof’ to incomplete type ‘char[]’
Is there a way to get the size of "data" in this situation, or maybe a suggestion of an alternative method I could use?
The compiler I am using is gcc 4.6.3.
|
Since x.data is a null terminated char array you could just use strlen function.
```
printf( "sizeof x.data: %u\n", strlen(x.data)+1 );
```
This code will not work correctly if the array contains null. In this case you need to store length of the array in separate member of struct.
|
I have a one-dimensional representation of a matrix: of type
```
double *A1d;
```
You may assume that this data structure ismalloc'dand filled with double values and is of lengthMATRIX_SIZE * MATRIX_SIZE.
I would like to convert this data structure into a two-dimensional square matrix of typedouble**with row/column lengthMATRIX_SIZE
I am looking for something like:
```
double** A2D = vector_to_matrix(int sz, double* matrix_1d);
```
|
```
double** vector_to_matrix(int sz, double* matrix_1d) {
// The output 2d matrix to be returned.
double** matrix_2d = (double**)malloc(sz * sizeof(double*));
// Allocate memory.
for (int i = 0; i < sz; i++)
matrix_2d[i] = (double*)malloc(sz * sizeof(double));
// Copy from 1d matrix.
for (int i = 0; i < sz; i++)
for (int j = 0; j < sz; j++) matrix_2d[i][j] = matrix_id[i * sz + j];
return matrix_2d;
}
```
|
For example I want to check the following:
```
if((sample.x == 260 || sample.x == 261) && (sample.y==178 ||sample.y==179 ||) )
{ ...
}
```
How can I put it in a simpler way?(It's a lot of OR that I have to put in the if condintion, should I make a function? or how can I say something like :
```
if(sample.x == 10 between 20)//Thats my objective here
```
Thanks!
I am programming in C
|
You could make a macro for that.
```
// define macro between, you get X<=V && V<=Y
// X, Y are the limits, V is the variable you are evaluating
#define between(V, X, Y) ((X)<=(V) && (V)<=(Y))
```
this returns true ifvariable V is between X and Y, false otherwise.
Then you can use this as a normal function
```
if(between(sample.x, 10, 20) || between(sample.y, 30, 40)) {...}
```
More info about macroshere
|
Is it possible to make undefined type arrays in C, similarly to Object arrays ? If so, how ? Something like this,
```
undefinedtype ArrayName[200];
```
|
Not really. In C, when you create an array, the system allocates memory for your array. It needs to know how much memory to allocate. Objects of different types require different amounts of memory, so if you don't know what kind of objects will be in your array, you won't know how much memory to allocate.
However, you can make an array of pointers by using void* instead of undefinedtype. Then you can make those pointers point to any kind of object you want later.
|
i am new to C programming .... so there are mere chances you will find the question damn easy
```
char *ii;
int i=54;
ii=(char *)&i;
```
for what purpose is there (char *) and is using char pointer for int address is helpful in some way ? and is it will be exactly the same as with using int pointer ?
|
This question seems to assume that using achar*to hold the address of an integer has a valid purpose.
It does not, and is not a proper way to code.
There are cases where the data that a pointer points to is not known at compile time. And that can lead to code similar to this. But, as a general rule, it is not useful and should be avoided.
|
I would like to print first N numbers in BASE62 encoding. What's wrong in my code?
```
const char ALPHABET[63] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int main(void) {
int N = 50;
for (int i = 0; i < N; i++) {
int base62 = ALPHABET[i % 62];
printf("Base 62: %s\n", (char*)base62);
}
}
```
|
ALPHABETis an array of chars, so you should be fine with usingchar base 62 ...andprintf("Base 62: %c\n", base62);
Casting a normalintto pointer and passing that to printf as in the original code will lead to printf making invalid memory reads (undefined behavior).
|
I am using the Citrix XenServer C SDK to obtain values of host_cpu utlization.
Any idea what units this data is represented in the test/test_get_records.cGenerates the following output.. I am expecting percentile:
Please comment on how this figure relates to a percentage value.
|
Looking at the header file, it is a double.http://opensrcd.ca.com/ips/07400_4/include/xen/api/xen_host_cpu.h
Depending on your machine you might try%llfinstead of%lfbut...
I think you are supposed to use their helper functions to access the data. eg:
```
/**
* Get the utilisation field of the given host_cpu.
*/
extern bool
xen_host_cpu_get_utilisation(xen_session *session, double *result, xen_host_cpu host_cpu);
```
|
If I have a Button as a child control on a Window, is the Button responsible for painting itself (i.e. does it handle the WM_PAINT event in its Window Procedure), or is the parent Window responsible for drawing its child controls?
|
WM_PAINTis dispatched to all windows in order to paint themselves. The window procedure of the window receives the message and is then responsible for painting the window.
In the case of the button control, the window procedure registered by theBUTTONwindow class performs the painting.
|
I am making a program in which I am getting data from a serial device. The problem which I am facing is that the device gives me the wrong data until I run while(1) and then read the data. So I thought of running a for loop for 100000 times and then reading the data but still it was giving wrong data. I can only use while(1). So is there anyway I can stop while(1) after sometime like 7-10sec.?
please help,thanks.!!
|
I think it will help.
```
int i=0;
while(1){
// do your work.
if ( i == 100 ) break; // for an example.
i++;
}
printf("After While\n");
```
|
I have an assignment where I'm supposed to make a simple arithmetic calculator in C that takes an input of a number, an operator, and a second number and performs the operation and outputs it. Sounds pretty simple right?
I'm limited to using specificallygetchar()andputchar()for number input. This means that I have to read the whole input one char at a time... and I'm confused as to how I would read two chars of a number (9and1of91for example) as one number. Ifgetchar()read from right to left, this would be a different story. But unfortunately, it is not...
I would appreciate any pointers!
|
Here is some pseudo-code:c = getchar()
num = 0
while isdigit(c)
num = (num * 10) + (c - '0')
c = getchar()
This accumulates the number, recognizing that each new digit to the right effectively multiplies the digits seen already by 10. It stops accumulating when a non-digit is seen, so parsing strings like91+3works.
|
If I have a Button as a child control on a Window, is the Button responsible for painting itself (i.e. does it handle the WM_PAINT event in its Window Procedure), or is the parent Window responsible for drawing its child controls?
|
WM_PAINTis dispatched to all windows in order to paint themselves. The window procedure of the window receives the message and is then responsible for painting the window.
In the case of the button control, the window procedure registered by theBUTTONwindow class performs the painting.
|
I am making a program in which I am getting data from a serial device. The problem which I am facing is that the device gives me the wrong data until I run while(1) and then read the data. So I thought of running a for loop for 100000 times and then reading the data but still it was giving wrong data. I can only use while(1). So is there anyway I can stop while(1) after sometime like 7-10sec.?
please help,thanks.!!
|
I think it will help.
```
int i=0;
while(1){
// do your work.
if ( i == 100 ) break; // for an example.
i++;
}
printf("After While\n");
```
|
I have an assignment where I'm supposed to make a simple arithmetic calculator in C that takes an input of a number, an operator, and a second number and performs the operation and outputs it. Sounds pretty simple right?
I'm limited to using specificallygetchar()andputchar()for number input. This means that I have to read the whole input one char at a time... and I'm confused as to how I would read two chars of a number (9and1of91for example) as one number. Ifgetchar()read from right to left, this would be a different story. But unfortunately, it is not...
I would appreciate any pointers!
|
Here is some pseudo-code:c = getchar()
num = 0
while isdigit(c)
num = (num * 10) + (c - '0')
c = getchar()
This accumulates the number, recognizing that each new digit to the right effectively multiplies the digits seen already by 10. It stops accumulating when a non-digit is seen, so parsing strings like91+3works.
|
This is a piece of myCcode:
```
for (i=2; i<sequence_length+1; i++)
{
int tab_length = Newton(sequence_length, i);
start_tab[tab_length] = make_for_num(i, sequence_length, start_tab, tab_length);
}
```
My goal is to use updatedstart_tabvariable for every next step of forloop. Output of each iteration should be an input for the next one, but it isn't. How can I fix that?
|
You could use a recursive function.
|
I read that void pointers can be casted to implicitly from any pointer, but it seems like they don't work with structs, I made an example:
```
typedef struct FOO{
int *arr;
size_t size;
} FOO;
int main()
{
void * a;
FOO * b = (FOO*)malloc(sizeof(FOO));
a = b;
b->arr;//works, accessed arr
a->arr;//error: expression must have pointer-to-struct-or-union type
}
```
I can see thataandbhave the same address but I can't useaas if it was of the same type asb, why is that?
Another related question is, can absolutely any pointer be implicitly casted tovoid *? EvenFOO****tovoid*for example?
|
a->arr;is equivalent to(*a).arr;.ais ofvoid *type and it can't be dereferenced. You need to castatoFOO *before dereferencing.
```
((FOO *)a)->arr;
```
|
I'm find out a bit confusing thing in C code
```
struct SomeStruct {
// ...
void (*f)(const void *x);
};
void do_some( void f(const void *x) ) { // what?
struct SomeStruct* v;
// ...
v->f = f;
}
```
As I can understanddo_sometake function instead function pointer.
But what is difference withvoid do_some( void (*f)(const void *x) )in practice? When I should use this? Is this allowed in C++?
|
There is no difference. It's just syntactic sugar. It is allowed in both C and C++.
Function parameters are simply rewritten by the compiler as function pointer parameters, just as array parameters are rewritten by the compiler as pointer parameters.
For reference, here is an excerpt from the C standard, section 3.7.1:
```
g(int (*funcp)(void))
// ...
or, equivalently,
g(int func(void))
```
|
This is a piece of myCcode:
```
for (i=2; i<sequence_length+1; i++)
{
int tab_length = Newton(sequence_length, i);
start_tab[tab_length] = make_for_num(i, sequence_length, start_tab, tab_length);
}
```
My goal is to use updatedstart_tabvariable for every next step of forloop. Output of each iteration should be an input for the next one, but it isn't. How can I fix that?
|
You could use a recursive function.
|
I read that void pointers can be casted to implicitly from any pointer, but it seems like they don't work with structs, I made an example:
```
typedef struct FOO{
int *arr;
size_t size;
} FOO;
int main()
{
void * a;
FOO * b = (FOO*)malloc(sizeof(FOO));
a = b;
b->arr;//works, accessed arr
a->arr;//error: expression must have pointer-to-struct-or-union type
}
```
I can see thataandbhave the same address but I can't useaas if it was of the same type asb, why is that?
Another related question is, can absolutely any pointer be implicitly casted tovoid *? EvenFOO****tovoid*for example?
|
a->arr;is equivalent to(*a).arr;.ais ofvoid *type and it can't be dereferenced. You need to castatoFOO *before dereferencing.
```
((FOO *)a)->arr;
```
|
I'm find out a bit confusing thing in C code
```
struct SomeStruct {
// ...
void (*f)(const void *x);
};
void do_some( void f(const void *x) ) { // what?
struct SomeStruct* v;
// ...
v->f = f;
}
```
As I can understanddo_sometake function instead function pointer.
But what is difference withvoid do_some( void (*f)(const void *x) )in practice? When I should use this? Is this allowed in C++?
|
There is no difference. It's just syntactic sugar. It is allowed in both C and C++.
Function parameters are simply rewritten by the compiler as function pointer parameters, just as array parameters are rewritten by the compiler as pointer parameters.
For reference, here is an excerpt from the C standard, section 3.7.1:
```
g(int (*funcp)(void))
// ...
or, equivalently,
g(int func(void))
```
|
I know I can have a statement as such
```
strcat( a, b );
int alen = strlen( a );
printf("a and b concatenated = %s and its length is %d\n", a, alen );
```
However, I want to preserve a, so I am trying use something more like this:
```
strcat( a, b );
int xlen = strlen( x );
printf("a and b concatenated = %s and its length is %d\n", x, xlen );
```
How do I fix the first line with strcat so that it concatenates a and b into x?
|
You should use the following :-
```
strcpy(x,a);
strcat(x,b);
int xlen = strlen(x);
printf("a and b concatenated = %s and its length is %d\n", x, xlen );
```
Voila,and that's it.
|
Hello I am developing a simple protection for a Cocoa Mac Os X application for independent distribution. What would be the best place to store some secret hidden files on the user's disk to keep track of demo expiration ? also how to protect in case a user monitors the file system activity with tools such as FSEventer ? Thanks
|
Store it as a generic password in the user's keychain.
Keychain Services Programming Guide
|
I'm just a bit stuck as to why this doesn't work. Am I missing something obvious? This is what I am trying to do:
```
#define LENGTH 4;
new->array = malloc(sizeof(int)*LENGTH);
```
I'm using Xcode and getting errors for 'expected ")"' at the start of LENGTH and 'expected expression' at the end of LENGTH.
But this is ok:
```
int size = sizeof(int)*LENGTH;
new->array = malloc(size);
```
What is the reason why I cannot do the first one?
|
LENGTHgets replaced by4;, so you get
```
new->array = malloc(sizeof(int)*4;);
```
That is syntactically invalid. Remove the trailing;from the define:
```
#define LENGTH 4
```
Also note this has nothing to do withmalloc.
|
I have this code which is working fine:
```
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
struct in_addr addr;
if (argc != 2) {
fprintf(stderr, "%s <dotted-address>\n", argv[0]);
exit(EXIT_FAILURE);
}
if (inet_aton(argv[1], &addr) == 0) {
perror("inet_aton");
exit(EXIT_FAILURE);
}
printf("%s\n", inet_ntoa(addr));
exit(EXIT_SUCCESS);
}
```
What I want to achieve is print the value ofinet_aton()function. The description of function says that it returns a number, but when I try to print it, it says "cannot covert from address structure to decimal".
|
Using this instead of your lastprintfworked for me:
```
printf("%d\n", addr.s_addr);
```
|
I want to use the following script in my c program.
the user will be able to input an IP. after that i want to be sure, the input was right and ask the user
```
char eingabe;
printf("Is that the right input? y/n: ");
scanf("%s",&eingabe);
printf("your input was: %s\n", eingabe);
if(eingabe == 'y') {
printf("you klicked y");
} else {
printf("you clicked no");
}
```
|
Change
```
scanf("%s",&eingabe);
```
to
```
scanf(" %c",&eingabe);
```
and
```
printf("your input was: %s\n", eingabe);
```
to
```
printf("your input was: %c\n", eingabe);
```
because%cis the right format specifier for achar.%sis the format specifier for a string. The space before%cin thescanfskips any number of whitespace characters(' ',\netc) includeing none before scanning a character(%c).
|
I've to scan characters in string in order but in that example
```
char s[8]={"ab"};
char a,b;
sscanf(s,"%c", &a);
sscanf(s,"%c", &b);
printf("%c%c", a, b);
```
it prints aa. but i need to it prints ab. How can i fix it? Should I print string to file and read from file?
|
It printsaabecause this is exactly what you asked for.
How do you expect:
```
sscanf(s,"%c", &b);
```
To behave diffently from:
```
sscanf(s,"%c", &a);
```
If you want to scan a different portion of the string, you have to pass a different string tosscanf.
```
if(1 == sscanf(s,"%c", &a))
sscanf(s+1,"%c", &b);
```
But honestly, if you need to parse a stringcharbycharjust use pointer arithmetic...
|
```
int i;
for(i=7;i<6;i--)//loop does not execute
{
printf("*");
}
```
The above code should print one * but it does nothing. Shouldn'tit run same as for(i=7;i<8;i++) ?
Is this a logical error ? Please help.
|
Aforloop has 3 parts
```
for( init ; cond ; step )
```
When the execution reaches the loop,
initis executed.condis evaluated.If false, break the loopIf true, proceed to the next stepExecute the body of the loop.Dostep(in many cases, this is increment/decrement)Goto step 2
In your case ,iis set to 7. Then the conditioni<6is checked. Obviously,7<6is false. So the loop never gets executed.
AndNo.
```
for(i=7;i<6;i--)
```
and
```
for(i=7;i<8;i++)
```
aren't the same.
Perhaps you wanted to write
```
for(i=7;i>6;i--) //'>' instead of '<'
```
in which the loop will execute once.
|
I need to change window size in TCP header, but when I changing it and recalculate the checksum the final window is multiplying by window scale option. Where and in which structure I can find it and change?
|
You can't change the window scale after it has been negotiated during connection establishment. You need to set a large receive buffer on the socket prior to connecting it. In the case of a server, you need to set the receive buffer size on the listening socket, from whence it will be inherited by the accepted socket.
|
I have hundred of warnings like this when build withgcc:
```
foo.c:2690:5: note: in expansion of macro ‘PUT_UINT32’
PUT_UINT32(state, digest, 0);
```
How can I get rid of them?
-walso hide warnings that I still want to see
|
I assume you are usingclang: whenclangdetects an error or a warning in code expanded from a macro, it outputs one line for each macro whose expansion leads to the offending code. Fix the errors and warnings in the final code and these messages will disappear.
|
I am simulating a client/server interaction according toBeej's Guide to Network Programming. At the beginning of myserver.cfile I am defining a port number with:
```
#define PORT "21124"
```
However, I will be creating several servers from this file and I would like to change this constant based on some if-else logic. Is there a functionality in C to easily accomplish this such as:
```
if (serverNumber == 1) {
#define PORT "21124"
}
else if (serverNumber == 2) {
#define PORT "12412"
}
else {
#define PORT "12334"
}
```
This may be a duplicate, but I didn't see it in the search. I'm aCnoob.
|
"I would like to change this constant". That doesn't sound right, does it?
So, just use a variable likeint portand assign its value with a simple if-else block of statements, or with a switch.
|
I have stage server which I use it with Xmanager. In the stage sever,after whatever I choose using the mouse,a "^C" will appear automatically after $.For example ,I choose "system/" with mouse,and a "^C" soon appears in the command line.
It never happened before until yesterday I tried "Shift+Ctrl+V" which means "copy" after I choosing the command line which I wanted to copy, but it didn't work although I tried several times.And then the problem I described existed.
It's really confusing,and I don't whether "^C" has any bad effect.
How to resolve this problem?Anyone knows why it happened?
|
The reason causing this problem is that I opened youdao dictionary simultaneously with its function of catching words on the screen on. Just close it and the problem won't happen again. I don't know why maybe it has something to do with the software's compatibility.
|
I want to use the following script in my c program.
the user will be able to input an IP. after that i want to be sure, the input was right and ask the user
```
char eingabe;
printf("Is that the right input? y/n: ");
scanf("%s",&eingabe);
printf("your input was: %s\n", eingabe);
if(eingabe == 'y') {
printf("you klicked y");
} else {
printf("you clicked no");
}
```
|
Change
```
scanf("%s",&eingabe);
```
to
```
scanf(" %c",&eingabe);
```
and
```
printf("your input was: %s\n", eingabe);
```
to
```
printf("your input was: %c\n", eingabe);
```
because%cis the right format specifier for achar.%sis the format specifier for a string. The space before%cin thescanfskips any number of whitespace characters(' ',\netc) includeing none before scanning a character(%c).
|
I've to scan characters in string in order but in that example
```
char s[8]={"ab"};
char a,b;
sscanf(s,"%c", &a);
sscanf(s,"%c", &b);
printf("%c%c", a, b);
```
it prints aa. but i need to it prints ab. How can i fix it? Should I print string to file and read from file?
|
It printsaabecause this is exactly what you asked for.
How do you expect:
```
sscanf(s,"%c", &b);
```
To behave diffently from:
```
sscanf(s,"%c", &a);
```
If you want to scan a different portion of the string, you have to pass a different string tosscanf.
```
if(1 == sscanf(s,"%c", &a))
sscanf(s+1,"%c", &b);
```
But honestly, if you need to parse a stringcharbycharjust use pointer arithmetic...
|
```
int i;
for(i=7;i<6;i--)//loop does not execute
{
printf("*");
}
```
The above code should print one * but it does nothing. Shouldn'tit run same as for(i=7;i<8;i++) ?
Is this a logical error ? Please help.
|
Aforloop has 3 parts
```
for( init ; cond ; step )
```
When the execution reaches the loop,
initis executed.condis evaluated.If false, break the loopIf true, proceed to the next stepExecute the body of the loop.Dostep(in many cases, this is increment/decrement)Goto step 2
In your case ,iis set to 7. Then the conditioni<6is checked. Obviously,7<6is false. So the loop never gets executed.
AndNo.
```
for(i=7;i<6;i--)
```
and
```
for(i=7;i<8;i++)
```
aren't the same.
Perhaps you wanted to write
```
for(i=7;i>6;i--) //'>' instead of '<'
```
in which the loop will execute once.
|
I need to change window size in TCP header, but when I changing it and recalculate the checksum the final window is multiplying by window scale option. Where and in which structure I can find it and change?
|
You can't change the window scale after it has been negotiated during connection establishment. You need to set a large receive buffer on the socket prior to connecting it. In the case of a server, you need to set the receive buffer size on the listening socket, from whence it will be inherited by the accepted socket.
|
I have hundred of warnings like this when build withgcc:
```
foo.c:2690:5: note: in expansion of macro ‘PUT_UINT32’
PUT_UINT32(state, digest, 0);
```
How can I get rid of them?
-walso hide warnings that I still want to see
|
I assume you are usingclang: whenclangdetects an error or a warning in code expanded from a macro, it outputs one line for each macro whose expansion leads to the offending code. Fix the errors and warnings in the final code and these messages will disappear.
|
I am simulating a client/server interaction according toBeej's Guide to Network Programming. At the beginning of myserver.cfile I am defining a port number with:
```
#define PORT "21124"
```
However, I will be creating several servers from this file and I would like to change this constant based on some if-else logic. Is there a functionality in C to easily accomplish this such as:
```
if (serverNumber == 1) {
#define PORT "21124"
}
else if (serverNumber == 2) {
#define PORT "12412"
}
else {
#define PORT "12334"
}
```
This may be a duplicate, but I didn't see it in the search. I'm aCnoob.
|
"I would like to change this constant". That doesn't sound right, does it?
So, just use a variable likeint portand assign its value with a simple if-else block of statements, or with a switch.
|
I have stage server which I use it with Xmanager. In the stage sever,after whatever I choose using the mouse,a "^C" will appear automatically after $.For example ,I choose "system/" with mouse,and a "^C" soon appears in the command line.
It never happened before until yesterday I tried "Shift+Ctrl+V" which means "copy" after I choosing the command line which I wanted to copy, but it didn't work although I tried several times.And then the problem I described existed.
It's really confusing,and I don't whether "^C" has any bad effect.
How to resolve this problem?Anyone knows why it happened?
|
The reason causing this problem is that I opened youdao dictionary simultaneously with its function of catching words on the screen on. Just close it and the problem won't happen again. I don't know why maybe it has something to do with the software's compatibility.
|
I have been working on an Android app that does its functions in JNI. My problem is in a function where logcat displays until a button is pressed. I found where the problem occurs:
```
FILE *logcat = popen("su -c logcat threadtime", "r");
while (isRunning(running, env, thiz))
if (fgets(&line, sizeof(line), logcat) != NULL) //<--- HERE
appendLogWithToken(logger, line, env, thiz);
```
I have done some debugging and found out that thefgets()sleeps until another line is received. I have searched and found similar questions but no working answers. Are there any other functions that return null and don't wait for input, or is this fixable?
|
Jonathan gave an excellent explanation as to why this occur.
A simple fix in your case is to use logcat -d.
Adding the -d option will send EOF at the end of the current buffer and allow fgets to continue (instead of the default option that monitors the buffer endleslly )
|
This question already has answers here:Why are these constructs using pre and post-increment undefined behavior?(15 answers)Closed5 years ago.
I am a beginner in C.
When I try to run the following code :
```
#include <stdio.h>
int main(void) {
int a = 3, b;
b = printf("%d %d", a, a++);
a = printf(" %d", b);
printf(" %d", a);
return 0;
}
```
It shows me :
```
error: operation on 'a' may be undefined [-Werror=sequence-point]
b = printf("%d %d", a, a++);
^
```
But here I am changing the value of a only once. Why is there a sequence point error then ?
I am using -Wall -Werror flags.
|
It is true that you are changing the value ofaonly once but order of evaluation of argumentsaanda++is not guaranteed. Eitheraora++will be evaluated first resulting in undefined behavior.
|
I have the following code. I cannot determine the reason for the output it's giving.
```
char abc[14] = "C Programming";
printf("%s\n", abc+abc[3]-abc[4]);
```
output:rogramming
It is a quiz question with the following options: What would this print? a)C Programming b) rogamming c)Runtime Error d)Compilation Error
|
Perhaps it will be clearer if I put in stepping stonesv3andv4. These are used to calculate an offset into the string of 3 indices. So the print output begins atabc[3].
```
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char *argv[])
{
char abc[14] = "C Programming";
int v3 = abc[3];
int v4 = abc[4];
printf("%d - %d = %d\n", v3, v4, v3 - v4);
printf("%s\n", abc + v3 - v4);
return 0;
}
```
Program output:
```
114 - 111 = 3
rogramming
```
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed8 years ago.Improve this question
```
#include<stdio.h>
int main()
{
int i,x=10;
for(i=0;i<7;i++);
{
x++;
}
printf("%d",x);
}
```
Output :11
No matter how many times the for loop iterates, the value of x stays 11. Why is that ?
|
Remove the semicolon from here:
```
for(i=0;i<7;i++);
```
The semicolon makes theforloop have an empty body. It makes it equivalent to
```
for(i=0;i<7;i++){}
```
Including warning flags in your compiler(-Wextrain GCC) emits a warning about these kind of issues.
|
I have the following code. I cannot determine the reason for the output it's giving.
```
char abc[14] = "C Programming";
printf("%s\n", abc+abc[3]-abc[4]);
```
output:rogramming
It is a quiz question with the following options: What would this print? a)C Programming b) rogamming c)Runtime Error d)Compilation Error
|
Perhaps it will be clearer if I put in stepping stonesv3andv4. These are used to calculate an offset into the string of 3 indices. So the print output begins atabc[3].
```
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char *argv[])
{
char abc[14] = "C Programming";
int v3 = abc[3];
int v4 = abc[4];
printf("%d - %d = %d\n", v3, v4, v3 - v4);
printf("%s\n", abc + v3 - v4);
return 0;
}
```
Program output:
```
114 - 111 = 3
rogramming
```
|
Closed.This question isnot reproducible or was caused by typos. It is not currently accepting answers.This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may beon-topichere, this one was resolved in a way less likely to help future readers.Closed8 years ago.Improve this question
```
#include<stdio.h>
int main()
{
int i,x=10;
for(i=0;i<7;i++);
{
x++;
}
printf("%d",x);
}
```
Output :11
No matter how many times the for loop iterates, the value of x stays 11. Why is that ?
|
Remove the semicolon from here:
```
for(i=0;i<7;i++);
```
The semicolon makes theforloop have an empty body. It makes it equivalent to
```
for(i=0;i<7;i++){}
```
Including warning flags in your compiler(-Wextrain GCC) emits a warning about these kind of issues.
|
I am getting runtime error when I used array of size 10^5*10^5 (ex.int a[100000][100000]. As this array is consuming more memory, this may be one one of the reasons for runtime error.
How should I declare this array (2D array ex.int a[100000][100000]) so that I can cope with problem ofSIGSEGVruntime error?
Please, provide approach to declare such type of array?
|
Three ways to declare the large arrayint a[100000][100000]are:
Make the large array globalMake the large arraystatic:static int a[100000][100000];Usemalloc/callocand dynamically allocate the large array:int **a;
a=malloc(sizeof(int*)*100000);
for(int i=0;i<100000;i++)
a[i]=malloc(sizeof(int)*100000);
/*Use the array*/
for(int i=0;i<100000;i++)
free(a[i]);
free(a);
|
I am wrapping c library for Python using Cython.I have pointers to callable Python objects in my C code to call them back later from C code.How to ensure a callback is not garbage collected or deleted if I only have address.
|
Just__Pyx_INCREF(obj)the object you're holding -- this ensures it won't go away!Doremember to__Pyx_DECREF(obj)once you're done with it -- and, seehttps://github.com/cython/cython/wiki/refcountingfor details!-)
|
Taking a look atGCC's builtins, I noticed the use of the stringpopin function name (__builtin_popcount), etc. I've also seen other references to pop in other implementations.
When referring to set bits, why ispopused, and what does it mean?
|
It's short for "population" (i.e., the number of bits that are "populated" by being set to 1), and is also known as theHamming weight.
FromWikipedia:
The Hamming weight of a string is the number of symbols that are different from the zero-symbol of the alphabet used. It is thus equivalent to the Hamming distance from the all-zero string of the same length. For the most typical case, a string of bits, this is the number of 1's in the string. In this binary case, it is also called thepopulation count,popcountor sideways sum. It is the digit sum of the binary representation of a given number and the ℓ₁ norm of a bit vector.
|
The following code running compiler options-O3vs-O0results different output:
```
#include <stdlib.h>
#include <stdio.h>
int main(){
int *p = (int*)malloc(sizeof(int));
int *q = (int*)realloc(p, sizeof(int));
*p = 1;
*q = 2;
if (p == q)
printf("%d %d", *p, *q);
return 0;
}
```
I was very surprised with the outcome.
Compiling with clang 3.4, 3.5 (http://goo.gl/sDLvrq)
using compiler options-O0— output:2 2using compiler options-O3— output:1 2
Is it a bug?
Interestingly if I modify the code slightly
(http://goo.gl/QwrozF) it behaves as expected.
```
int *p = (int*)malloc(sizeof(int));
*p = 1;
```
Testing it on gcc seems to work fine.
|
After therealloc,pis no longer valid.
|
This question already has answers here:passing arg 1 of `foo' from incompatible pointer type(3 answers)Closed8 years ago.
warning: passing arg 1 of `printTokens' from incompatible pointer type
```
void printTokens(const char** tokens);
char** readTokens(FILE* stream);
int main(int argc, char *argv[])
{
FILE* fp = fopen(argv[1], "r");
char** tok = readTokens(fp);
printTokens(tok);
getchar();
return 0;
}
```
what's wrong? the paramtertokischar**andprintTokensreceiveschar**
|
const char**andchar**are not the same because ofconst, but you can use type cast.
So change
```
printTokens(tok);
```
to
```
printTokens((const char**)tok);
```
|
I was going throughPthreads Programmingby Bradford Nichols, on Page number177I noticed this code:
```
static char work_buffer[100];
void reverse_string(in_str)
char *in_str;
{
...
...
}
```
What is the third line of code doing here?
|
Third line states that the parameterin_starofreverse_stringis of typechar *. Its an old K&R style of parameter declaration.
|
I now know how it's done in one line, altough I fail to realise why my first draft doesn't work aswell. What I'm trying to do is saving the lower part into a different variable, shifting the higher byte to the right and adding the two numbers via OR. However, it just cuts the lower half of the hexadecimal and returns the rest.
```
short int method(short int number) {
short int a = 0;
for (int x = 8; x < 16; x++){
if ((number & (1 << x)) == 1){
a = a | (1<<x);
}
}
number = number >> 8;
short int solution = number | a;
return solution;
```
|
You are doing it one bit at a time; a better approach would do it with a single operation:
```
uint16_t method(uint16_t number) {
return (number << 8) | (number >> 8);
}
```
The code above specifies 16-bit unsigned type explicitly, thus avoiding issues related to sign extension. You need to include<stdint.h>(or<cstdint>in C++) in order for this to compile.
|
While reading about pointers I found a pointer variable is used to indicate an array like this:
```
char* chrArray;
int* intArray;
```
After that I foundcharArray++andintArray++used in code to indicate the next element ofcharArrayandintArray. But so far I knowcharin C is 1 byte andintin array is 4 byte. So I can not understand how the increment operator behave here. Can anyone please explain it.
|
This is handled by the compiler that knows the type of the pointer, thus can increment the address it stores by the relevant size, whether it is a char, an int or any other type.
|
From an article:
"GNU CC recognizes floating-point numbers written not only in the usual decimal notation, such as 1.55e1, butalso numbers such as 0x1.fp3 written in hexadecimal format. In that format the 0x hex introducer and the p or P exponent field are mandatory. The exponent is a decimal number that indicates the power of 2 by which the significand part will be multiplied.Thus 0x1.f is 1 15/16, p3 multiplies it by 8, and the value of 0x1.fp3 is the same as 1.55e1. "
It seems to say 0x1.fp3 is evaluated as = (1 + 15/16 ) * 2^3
Where the 15/16 came from ?
|
Since it's hexadecimal format, then0.1means1/16,0.2means2/16, ...0.ameans10/16, ...,0.fmeans15/16.
|
I am currently making a Library simulation program where theIndexof the array is theBookIDof books available.
What I want to do is assign a linked-list / clist to everyIndexof the array so I can store whichborrowerIDhas loaned out specific books.
I have all of theCListlibrary files and to create aCListI can type the following code.
```
clist *xs;
xs = new_clist();
```
My array is currently
```
borrower[1000];
```
For each index I want to add create anew_clist().
|
You can do the following:
```
clist* borrower[1000];
int i;
for(i = 0; i<1000; i++){
borrower[i] = new_clist();
}
```
|
This question already has answers here:passing arg 1 of `foo' from incompatible pointer type(3 answers)Closed8 years ago.
warning: passing arg 1 of `printTokens' from incompatible pointer type
```
void printTokens(const char** tokens);
char** readTokens(FILE* stream);
int main(int argc, char *argv[])
{
FILE* fp = fopen(argv[1], "r");
char** tok = readTokens(fp);
printTokens(tok);
getchar();
return 0;
}
```
what's wrong? the paramtertokischar**andprintTokensreceiveschar**
|
const char**andchar**are not the same because ofconst, but you can use type cast.
So change
```
printTokens(tok);
```
to
```
printTokens((const char**)tok);
```
|
I was going throughPthreads Programmingby Bradford Nichols, on Page number177I noticed this code:
```
static char work_buffer[100];
void reverse_string(in_str)
char *in_str;
{
...
...
}
```
What is the third line of code doing here?
|
Third line states that the parameterin_starofreverse_stringis of typechar *. Its an old K&R style of parameter declaration.
|
I now know how it's done in one line, altough I fail to realise why my first draft doesn't work aswell. What I'm trying to do is saving the lower part into a different variable, shifting the higher byte to the right and adding the two numbers via OR. However, it just cuts the lower half of the hexadecimal and returns the rest.
```
short int method(short int number) {
short int a = 0;
for (int x = 8; x < 16; x++){
if ((number & (1 << x)) == 1){
a = a | (1<<x);
}
}
number = number >> 8;
short int solution = number | a;
return solution;
```
|
You are doing it one bit at a time; a better approach would do it with a single operation:
```
uint16_t method(uint16_t number) {
return (number << 8) | (number >> 8);
}
```
The code above specifies 16-bit unsigned type explicitly, thus avoiding issues related to sign extension. You need to include<stdint.h>(or<cstdint>in C++) in order for this to compile.
|
I dont understand why the "1<<5" in the following snippet of code, didn't find anything on google
```
gpio_output_set((1<<5), 0, (1<<5), 0);
```
Why not use 5? or 32? :)
Thanks for the help
|
"Why not use 32?"
Because nobody (including person who wrote the code, one year later) knows whatgpio_output_set(32)means. 32 in this case would be what's known as a "magic number", which is programmer slang for a hard-coded number which just sits there in your code, with no rational explanation why, it just magically gets the job done. It is very bad programming practice.
1<<5on the other hand, is the industry de facto standard way of saying "bit number 5". The intention of the programmer is clear.
Always strive to write self-documenting code, whenever possible.
|
I'm creating graphs with the graphviz's cgraph library. For example, the following snippet of C code
```
Agraph_t *g = agopen("MyGraph", Agdirected, NULL);
Agnode_t *a = agnode(g, "A", TRUE);
Agnode_t *b = agnode(g, "B", TRUE);
Agedge_t *e = agedge(g, a, b, "", TRUE);
agwrite(g, stdout);
```
generates this dot graph
```
digraph MyGraph {
A -> B;
}
```
which is rendered like this
```
(A)
↓
(B)
```
What I'd like to know ishow can I programmatically set the compass pointsthe edges must be anchored. The dot graph I'd like to get is:
```
digraph MyGraph {
A:ne -> B:sw
}
```
which eventually could be rendered as
```
(B)
↗
(A)
```
Thanks.
|
Finally I found the answer by myself. This is what I needed:
```
agsafeset(e,"tailport","nw","");
agsafeset(e,"headport","se","");
```
|
I have such hierarchy:
```
main()
{
int i;
myStruct *devices = NULL;
myFunc1(&devices);
for (i = 0; i < 5; i++)
{
printf("MAC: %s, Name: %s, COD: %s\n\r", devices[i].field1, devices[i].field2, devices[i].field3);
}
}
void myFunc1(myStruct **devices)
{
myFunc2(devices);
}
void myFunc2(myStruct **devices)
{
int i;
*devices = malloc(sizeof(myStruct) * 5);
for (i = 0; i < 5; i++)
{
(*devices[i]).field1 = "test1";
(*devices[i]).field2 = "test2";
(*devices[i]).field3 = "test3";
}
}
```
At main when I access devices[i] with i = 0, it is ok, but when i > 0 SegFault happens, and I can not understand how to access it correctly.
|
Because of theoperator precedencethe expression*devices[i]is parsed as*(devices[i])which is not quite what you want. You want to use(*devices)[i]instead.
|
```
#include"header.h"
int main(){
function();
return 0;
}
```
above is simplified form of my code. I implemented function() in header.h file, and put it in the same directory with this code.c file.
I heard that "gcc -c code.c" is "compile but no linking" option, but this code need linking with header.h file. So I guess -c option will flag an error, while it didn't. Though, without -c option it flags an error. Can anyone explain how this -c options works?
|
Header files have nothing to do with linking. Linking is combining multiple object files and libraries into an executable.
Header files are processed by the compiler, as part of generating an object file. Therefore,gcc -cwill process header files.
|
is there any preprocessor directive or other methods to check if the machine being run is 32 bit or 64 bit in C? I've tried googling this, but the problem with C is it brings up results for C#, C++, etc.. Also, I would prefer if this worked on Windows, Linux, and Mac.
|
The obvious way to do this at run time.
```
#include <limits.h>
#include <stdio.h>
int main()
{
printf("%d bits\n", (int)(CHAR_BIT * sizeof(void *)));
return 0;
}
```
Technically, this is not 100% guaranteed to work. Practically, this will work with most modern compilers - it is unusual for a void pointer to be represented using a number of bits that differs from that of the underlying system architecture.
To do a compile time check, there is no standard way. It is necessary to resort to macros that are specific to your compiler/preprocessor. You will therefore need to read relevant documentation.
|
I am new to C, and I am trying to initialize array elements at run time, according to user input (so if the user inputs 4, then array[0]=4).
I have the following code:
```
#include<stdio.h>
#define MAX 10
#define maxValue 100
int array[MAX];
int n;
int main(void){
scanf("%d", n); //asks for array value
if (n <= maxValue)
{
array[0] = n;
}
return 0;
}
```
The code compiles, but triggers an access violation.
What's wrong?
|
You should be passing &n to scanf.
```
scanf("%d", &n);
```
As Jonathan pointed out, this is easily caught by a compiler warning. For gcc you can use-Wallwhich will show you:
```
warning: format specifies type 'int *' but the argument has type
'int' [-Wformat]
scanf("%d", n); //asks for array value
~~ ^
```
|
I'm studying operating systems and I encountered both the terms ISR and interrupt handler. Are they two words for the same mechanism? If not, what is the difference?
|
There is no difference in Interrupt handler and ISR.Wikisays that:
In computer systems programming,an interrupt handler, also known as an interrupt service routine or ISR, is a callback function [...]
|
InC, what's the meaning of an underscore as a macro parameter?
```
#define FUNC(_) VALUE
```
Is it a dummy argument? any example for a use-case in which it'll fit?
|
The_has no special meaning, I suppose they used it because it looks like if the argument is not there.
The_is just a valid identifier, and hence it's taken so the macro requires one parameter, but it keeps the macro definition looking as if there was no parameter.
```
#define FUNC(ignoredParameter) VALUE
```
would be exaclty the same.
|
This question already has an answer here:Fclose a file that is already fclose(1 answer)Closed8 years ago.
Can the following code result in undefined behavior?
```
FILE *fp;
fopen_s(&fp, "abc.bin", "rb");
fclose(fp);
fclose(fp); // accidentally closed an already closed file.
```
I know that calling free on an already freed up array results in UB. Hence I ask.
|
Quote fromman fclose:
The behaviour of fclose() is undefined if the stream parameter is an illegal pointer, or is a descriptor already passed to a previous invocation of fclose().
So yes, it is undefined behavior.
|
I wrote this code in C:
```
double x1 = 7.52, x2 = 7, x3 = 8;
int m = 0;
double sum = x1 + x2*m + x3*m*m;
printf("%lf", m, sum);
```
but sum is always 0 no matter what the value of m that i changed..
why doesnt it make normal calculation ?
thanks
|
Because your are printingmwhich isintwith the"%lf"specifier which is fordouble.
And you are also passing more arguments toprintf()than format specifiers, which means that you are not enabling compiler warnings, you should, specially if you are a beginner.
Change this
```
printf("%lf", m, sum);
```
to
```
printf("m = %d\nsum = %f\n", m, sum);
```
and see what I mean.
|
I'm trying to create an array of words. What's the difference between creating array like this:
```
char* myWords[10];
```
and
```
char* myWords = malloc(10*sizeof(char *))
```
I'm assuming that since the first one happens automatically, that the memory is reaped at the end of the function execution. Is that correct?
|
These are very different types.
The first creates an array of pointers in the usual (automatic) way. The 10 pointers are valid until the function end. They don't point to anything valid with this alone, but can each point to a separate string that can be accessed from each element of the array.
The second allocates a chunk of memory to a single pointer to a character. Thus you would expect it to point to a string (up to 40 or 80 bytes typically). The memory is valid until you free it, but the pointer is automatic just like the first. (Note that an array of character pointers decays tochar **and notchar *.)
|
I note the questionColorful text using printf in Cgives a good example of setting coloured text on the standard console output in Windows. Is there something similar that allows output to be underlined? Or possibly even bolded or italicised?
EDIT: I tried Lundin's answer on using COMMON_LVB_UNDERSCORE with no luck. Attempting to use AddFontResource() to add arial italic font to try italics gives an error that there is anundefined reference to __imp_AddFontResourceA
|
It is not possible to do so using any standard C functions, as the C language doesn't even recognize the presence of a screen.
With Windows APIconsole functionsyou can change colors, underline and some other things. The particular function you are looking for is calledSetConsoleTextAttributejust as in the post you linked. Change itsattributesto includeCOMMON_LVB_UNDERSCORE.
|
I need to scan the 32 hex number from command line and populated it into a uint8_t [16] array, I tried scanning the string and convert it to hex but its really a hassle since i cant find a function that does that, whats the best way to do this?
|
```
uint8_t get_int(char c)
{
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'A' && c <= 'F') return 10 + c - 'A';
if (c >= 'a' && c <= 'f') return 10 + c - 'a';
return -1;
}
int main(void)
{
char buff[33];
size_t size;
size_t i;
uint8_t *output;
fgets(buff, sizeof buff, stdin);
size = strlen(buff) / 2;
output = malloc(size);
for (i= 0; i < size; ++i)
output[i] = get_int(buff[2*i]) * 16 + get_int(buff[2*i+1]);
for (i= 0; i < size; ++i)
printf("%u ", output[i]);
return 0;
}
```
ideone link
|
For testing I copied following sample code [https://developer.apple.com/library/ios/documentation/CoreFoundation/Conceptual/CFCollections/Articles/creating.html]and compiled it:
```
#import <CoreFoundation/CoreFoundation.h>
CFStringRef strs[3];
CFArrayRef anArray;
strs[0] = CFSTR("String One");
strs[1] = CFSTR("String Two");
strs[2] = CFSTR("String Three");
anArray = CFArrayCreate(NULL, (void *)strs, 3, &kCFTypeArrayCallBacks);
```
Now I got following error: "No matching function for call to CFArrayCreate"
Why it is not compilable and how to implement it that it is compilable?
|
The type of the second parameter ofCFArrayCreate()isconst void **. So, change the call to:
```
anArray = CFArrayCreate(NULL, (const void **)strs, 3, &kCFTypeArrayCallBacks);
```
This is really only a problem in C++, because it is a lot stricter about converting to and fromvoid*. In C,void*converts to other pointer types freely.
|
I have a lengthy hexadecimal string data,The data contents are RGB which can stand for X Y Z.Now How can I extracted the 3D model from the RGB color space?OpenCV helps? Or some other library.Now I can come up with a idea.First find the min cube of the colors.Then use scan line to find out the useful points.Then combine the points to surface. Is there a more mature program?
|
Your data is a cloud of 3D points (COP). The Point Cloud Library - PCL:pointclouds.orgoffer various tools for processing such data.
|
I made a C program. And I made a go file with go functions defined.
In the C program, I called go functions. Is go called from C compiled or interpretted?
|
I made a C program. And I made a go file with go functions defined. In the C program, I called go functions
You made a Go program which calls C functions (the other way around is not yet possible.) Then you're apparently calling Go functions from C again which is a bit weird and doesn't make much sense most of the time. Seehttps://stackoverflow.com/a/6147097/532430.
I'm going to assume you used gccgo tocompileyour program. Because if you used Go's gc then there wouldn't be any confusion about what language your program is written in.
Is go called from C compiled or interpretted?
It's compiled. gccgo is a Go front-end for GCC. And GCC stands for GNUCompilerCollection.
|
I'm telling other people thatcc -DFOOis just the same ascc -DFOO=1but I'm not quite confident if all compilers support this. So is it a standard for C compilers?
(As inspired by the accepted answer, found the recent POSIXc99standard, 2016 edition. Just for reference.)
|
It's not a standard for C compilers, though it is a standard for POSIX-compliant systems. Seethe cc manual.
|
If i have an array like this one:
```
int * array = ...
```
and if i want to delete it's content, what is the fastest and most efficient way to do this in C ?
|
If by "deleting the content" you mean zeroing out the array, usingmemsetshould work:
```
size_t element_count = ... // This defines how many elements your array has
memset(array, 0, sizeof(int) * element_count);
```
Note that having a pointer to your array and no additional information would be insufficient: you need to provide the number of array elements as well, because it is not possible to derive this information from the pointer itself.
|
I have one Tcp/Ip with ssl server enabled with epoll so it can handle ten thousand connections simultaneously. When i tried to test the server,i created thousand clients using thread. when i tried to connect with the server,after certain time connect() return ETIMEOUT. How to overcome this error?
|
you could change the socket attributes for recv and xmit timeout values Probably the same way you set the keepalive attribute
|
```
#include <stdio.h>
#include <math.h>
double hypotenuse( double side1, double side2 );
int main( void )
{
double a, b;
printf( "Enter the values of the two sides: " );
scanf( "%f %f", &a, &b );
printf( "\nThe length of hypotenuse is: %f", hypotenuse( a, b ) );
getchar();
getchar();
return 0;
}
double hypotenuse( double side1, double side2 )
{
double c;
c = (side1 * side1) + (side2 * side2);
return sqrt( c );
}
```
The above program works when I usefloat a, b;instead ofdouble a,b;. Why?
|
In your code, you use
```
scanf( "%f %f", &a, &b );
```
But%fis used for afloat,not adouble. Try%lffor adouble.
|
I want to link my .a library with CMake as I am used to with :cc main.c -L/usr/lib64 -lmlx -L/usr/lib64/X11 -lXext -lX11I use Clion from JetBRAINS.
I tried in my CMake :
```
target_link_libraries(fdf /usr/lib/x86_64-linux-gnu/libX11.a)
target_link_libraries(fdf /usr/lib/x86_64-linux-gnu/libXext.a)
```
|
Rewrite your
```
target_link_libraries(fdf /usr/lib/x86_64-linux-gnu/libX11.a)
target_link_libraries(fdf /usr/lib/x86_64-linux-gnu/libXext.a)
```
as:
```
target_link_libraries(fdf)
link_directories("/usr/lib/x86_64-linux-gnu/")
target_link_libraries(X11)
target_link_libraries(Xext)
```
As you mentioned in your answer, it might be that you have to shuffle the order of the last 2 lines
and so on.
|
I was gettingrealloc(): invalid next sizefor a program. So I just coded this to understand what's happening.
```
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *inp;
printf("%lu ",sizeof(inp));
char *res = (char*)malloc(15*sizeof(char*));
printf("%lu ",sizeof(res));
res = "hello world";
printf("%lu\n",sizeof(res));
return 0;
}
```
And surprisingly it outputs8 8 8. Can anyone explain why is it like that? Why is it 8 by default? And howmalloc()effects size ofinp?
|
sizeof(inp)gives you the size of pointer (8 bytes, 64-bits), not the storage under that pointer.
|
I note the questionColorful text using printf in Cgives a good example of setting coloured text on the standard console output in Windows. Is there something similar that allows output to be underlined? Or possibly even bolded or italicised?
EDIT: I tried Lundin's answer on using COMMON_LVB_UNDERSCORE with no luck. Attempting to use AddFontResource() to add arial italic font to try italics gives an error that there is anundefined reference to __imp_AddFontResourceA
|
It is not possible to do so using any standard C functions, as the C language doesn't even recognize the presence of a screen.
With Windows APIconsole functionsyou can change colors, underline and some other things. The particular function you are looking for is calledSetConsoleTextAttributejust as in the post you linked. Change itsattributesto includeCOMMON_LVB_UNDERSCORE.
|
I'm taking in an ouput folder name as an argument with argv[] and then executing the following code:
```
mkdir(outputname, "0777");
```
And sometimes it will work fine and create the folder with the correct permissions but occasionally the folder will get created and I won't be able to access the folder. Is this a common problem problem with a simple fix?
|
You're sending a string tomkdirfor the mode, and this is the wrong type. If you include the correct headers the compiler should warn you about this. The fix is simple enough,
```
#include <sys/stat.h>
#include <sys/types.h>
...
mkdir(outputname, 0777);
```
|
I have found in some codeNULLpointer is defined as follows -
```
#define NULL ((char *)0)
```
I found these code compiles fine. But I did not understand how this works. Can anyone please explain how 0 is casted to acharpointer?
And is it valid to use it as a FILE pointer making null -
```
FILE *fp = NULL;
```
|
The C library Macro NULL is the value of a null pointer constant.It may be defined as((void*)0), 0 or 0Ldepending on thecompiler vendor.Depending on compiler,declaration of NULL can be
```
#define NULL ((char *)0)
```
or
```
#define NULL 0L
```
or
```
#define NULL 0
```
And is it valid to use it as a FILE pointer making null-->
Yes.
|
I have anarray[768]but now I have only256(from0to255) samples in this array. I want to copy each value from0to255and fill this array better, I mean:
```
[1][2][3] - > [1][1][1][2][2][2][3][3][3]
```
How I can do that? Is there a library function that can do this?
|
I don't recall any known library function capable of doing this.
If you want to do it in-place, I'd do it from right to left (i.e. tail to head), Ithinkthis is the only way to do it in-place:
```
int i, j;
for (i = 255, j = 767; i > 0; i--) {
for (int k = 0; k < 3; k++) {
array[j--] = array[i];
}
}
```
If you don't need to do it in-place, this would suffice:
```
for (int i = 0, j = 0; i < 256; i++) {
for (int k = 0; k < 3; k++)
new_array[j++] = array[i];
}
```
|
This question already has answers here:incompatible types when assigning to type 'char[128]' from type 'char *' [duplicate](2 answers)Closed8 years ago.
I want to assign a struct value (that can be max 50 characters) from standard input but am getting the error:
Incompatible types when assigning to type 'char[50]' from type 'char
*'
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_LEN 50
struct msgbuf {
char mtext[MAX_LEN];
};
int main (int argc, char *argv)
{
struct msgbuf m;
char in[MAX_LEN];
scanf ("%s", in);
m.mtext = in;
}
```
|
Arrays have no the copy assignment operator. You have to copy arrays element by element. You can use standard functionstrcpydeclared in header<string.h>that to copy strings. For example
```
#include <string.h>
//...
strcpy( m.mtext, in );
```
|
I'm looking for the equivalent of this, without the surrounding single quotes:
```
#define SPACEBAR ' '
```
How do I do this? For any other character I would use either the character itself or its corresponding escape character. To my knowledge, however, there's no escape character for the spacebar. Is there some sort of hex code I can use? Please help.
|
Is there some sort of hex code I can use?
The ASCII code for Space is32or0x20. If you want to useSPACEBARlike a constant, you can#defineit to be:
```
#define SPACEBAR 32
```
or
```
#define SPACEBAR 0x20
```
Caveat
The above encoding will work for systems that use ASCII and UTF-8 encoding. For systems that use EBCDIC encoding, the decimal value to encode Space is 64 (Thanks are due to @BasileStarynkevitch for pointing that out).
|
Can anyone help me understand why this is not working how I would expect? Not sure why my return value gets truncated when I try to assign the value to a new pointer.
CODE
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *getname(){
char *name;
printf("Please enter your name: ");
scanf("%s", &name);
printf("The value being returned is: %s\n", &name);
return name;
}
int main(){
char *name;
name = getname();
printf("The value in main function: %s\n",&name);
return 0;
}
```
OUTPUT
```
Please enter your name: test1234
The value being returned is: test1234
The value in main function: test�
```
|
Don't use the ampersand (&) when you pass a pointer toscanfwith "%s".&takes the address of its operand. A pointer is already an address.
|
I looked at other answers, but was not able to find an answer.I want to compare the last character of a string to the literal "%".
```
strcpy(ch, fName[strlen(fName) - 1]);
printf("%d\n", strcmp(ch, "%"));
```
I want to compile with the cl command line compiler (MicroSoft), and get warnings:
```
cbx_test1.c(43) : warning C4047: 'function' : 'const char *' differs in levels of indirection from 'char'
cbx_test1.c(43) : warning C4024: 'strcpy' : different types for formal and actual parameter 2
```
There is something wrong with my code, that's obvious. But what?
|
The issue in your case is,fName[strlen(fName) - 1]is of typechar, not aconst char *, as needed bystrcpy(). Also, we don't know about the type ofchused here.
ConsideringfNameis an array of typechar, what you want here is
```
if ('%' == fName[strlen(fName)-1])
//do something
```
|
Why can't I use "long long int" with "int" in my C code?
```
int main(void) {
long long int a;
int b;
a = 1000000000;
b = 3200;
printf("long long int a = %d\n int b = %d", a, b);
return 0;
}
```
long long int a = 1000000000int b = 0
|
You have to use the correct format specifier in the printf function
```
printf("long long int a = %lld\n int b = %d", a, b);
```
Otherwise the function behaviour is undefined.
It seems that in the given situation the function considers the value of the long long int object pushed on the stack of the function as an argument like two objects of type int.
|
Where is the difference between the twovoid*tolongcasting/converting (code taken from Advanced Programming in Unix Environment) and why is it possible/allowed to write the 2nd case:
```
int complong(const void *arg1, const void *arg2)
{
long l1 = *(long *)arg1;
long l2 = *(long *)arg2;
// ...
}
```
vs
```
void* thr_fn(void *arg)
{
long idx = (long)arg;
// ...
}
```
|
When you castvoid*tolong*, you get a pointer pointing to a long value with the same address of the original pointer. When you castvoid*tolong, you are taking the address that the pointer points to as a number.
|
Why can't I use "long long int" with "int" in my C code?
```
int main(void) {
long long int a;
int b;
a = 1000000000;
b = 3200;
printf("long long int a = %d\n int b = %d", a, b);
return 0;
}
```
long long int a = 1000000000int b = 0
|
You have to use the correct format specifier in the printf function
```
printf("long long int a = %lld\n int b = %d", a, b);
```
Otherwise the function behaviour is undefined.
It seems that in the given situation the function considers the value of the long long int object pushed on the stack of the function as an argument like two objects of type int.
|
Where is the difference between the twovoid*tolongcasting/converting (code taken from Advanced Programming in Unix Environment) and why is it possible/allowed to write the 2nd case:
```
int complong(const void *arg1, const void *arg2)
{
long l1 = *(long *)arg1;
long l2 = *(long *)arg2;
// ...
}
```
vs
```
void* thr_fn(void *arg)
{
long idx = (long)arg;
// ...
}
```
|
When you castvoid*tolong*, you get a pointer pointing to a long value with the same address of the original pointer. When you castvoid*tolong, you are taking the address that the pointer points to as a number.
|
I have got a firmware (.raw) file which has to be written in serial flash. One way is to create a header file out of it i.e. a string array with the file content and then in code read this buffer and write it in serial flash.
In linux do we have any tool/command to create a header file with proper formatting. I am finding it toough to do it manually. The size of raw file is around 5mb.
|
In linux you can use xxd command for this functionality.
Usage: xxd -i fname > abc.h
This will create a new header file with proper formatting.
|
Lets say I havechar array[10]and[0] = '1',[1] = '2',[2] = '3', etc.
How would i go about creating(int) 123from these indexes, using C?
I wish to implement this on an arduino board which is limited to just under 2kb of SRAM. so resourcefulness & efficiency are key.
With thanks to Sourav Ghosh, i solved this with a custom function to suit:
```
long makeInt(char one, char two, char three, char four){
char tmp[5];
tmp[0] = one;
tmp[1] = two;
tmp[2] = three;
tmp[3] = four;
char *ptr;
long ret;
ret = strtol(tmp, &ptr, 10);
return ret;
}
```
|
I think what you need to know isstrtol(). Read detailshere.
Just to quote the essential part
long int strtol(const char *nptr, char **endptr, int base);Thestrtol()function converts the initial part of the string innptrto along integer value according to the givenbase, which must be between2and36inclusive, or be the special value0.
|
I am bit confused about assigning a value to variable and literal constants.
For example:
```
int age = 20;
```
ageis a variable, and20is the value assigned to it.
And:
```
int AGE = 20;
```
AGEis literal constant,20is the value assigned to it.
What is the difference? Will constants take the same two bytes in main memory as variables?
|
You are confused indeed:
```
int age = 20;
```
assigns integer value 20 to a variableage.
```
int AGE = 20;
```
assigns integer value 20 to a variableAGE.
There's no difference.
|
I got the user id to add it to the file path. But am having trouble creating the file. How do I add the user id to the file path? I usedstrcpybut that does not seem to work. Here is my code.
```
mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
register struct passwd *pw;
register uid_t uid;
uid = geteuid ();
pw = getpwuid (uid);
char str[1000];
strcpy(str, "/home/" );
strcpy(str, pw->pw_name );
strcpy(str, "/Documents/test.txt" );
int openFile = creat(str, mode);
```
|
Three times strcpy() ? maybe you wanted:
```
strcpy(str, "/home/");
strcat(str, pw->pw_name);
strcat(str, "/Documents/test.txt");
```
? Or even better:
```
int ret;
ret = snprintf(str, sizeof str, "%s/%s/%s"
, "/home" , pw->pw_name, "Documents/test.txt");
if (ret >= sizeof str) {... error...}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.