question
stringlengths 25
894
| answer
stringlengths 4
863
|
---|---|
I know that things have to be defined before they are used, but I am getting an "unknown type name error."
This is myNodedefinition:
```
struct Node {
position* p;
struct Node* next;
struct Node* prev;
};
```
This is my declaration (on line 96):
```
Node* hashtable[HashArraySize];
```
I get this error message:
```
P1.c:96:1: error: unknown type name ‘Node’
Node* hashtable[HashArraySize];
```
|
Unlike C++ which treatsstructtags as new type names, C requires an explicit typedef if you wish to useNodewithoutstruct:
```
typedef struct Node Node;
```
Alternatively, you could usestruct Nodein your declaration:
```
struct Node* hashtable[HashArraySize];
```
|
Can we use an array as an argument of another array?
I tried it inCprogramming language in Visual studio 2013 and It doesn't work!
|
For an array, as of c99, this isnotan valid operation
```
int main(void)
{
int vec[3]={1,2,3};
int sel[2]={1,2};
vec[sel]; // Invalid, will cause compilation to fail
return 0;
}
```
In order to select all of the variables you would have to loop through the array
```
int main(void)
{
int vec[3]={1,2,3};
int sel[2]={1,2};
int i;
int indv;
for(i=0;i<2;i++)
{
indv=vec[sel[i]];
## dosomething to indv
}
return 0;
}
```
|
I am studyingstructandtypedefand am totally new to coding
```
typedef struct
{
uint8_t ID;
uint8_t TanID;
uint8_t ProductID;
uint8_t SetlTme;
uint8_t NoOfStep
}product_Config;
typedef product_Config *product_Config_Ptr;
```
I am not getting what is last line is meant for
typedef product_Config *product_Config_Ptr;
|
Atypedefdefines an alias for a type.
In your exampletypedef Tank_Config *Tank_Config_Ptr;DeclaresTank_Config_Ptras an alias forTank_Config *.
So the following definitions are equivalent.
```
Tank_Config *ptr1;
Tank_Config_Ptr ptr2;
```
That being said, it is considered bad practice to hide a pointer inside of atypedef. It masks the fact that a pointer is being used and can cause confusion to readers of the code.
|
```
void test(void *a)
{
int *h = a; //error
}
int main(int argc, char const* argv[])
{
int z = 13;
test(&z);
return 0;
}
```
If I want to keep the void *a for test function, how can I get error line working?
|
I am able to compile and run the following withgccwithout warning or error:
```
#include <stdio.h>
void test(void *a)
{
int *h = a;
printf("test: %d\n", *h);
}
int main(int argc, char const* argv[])
{
int z = 13;
test(&z);
return 0;
}
```
The only conceivable reason you would be getting an error on the line you indicated is that you are using a C++ compiler (g++maybe?). If I try that I get the following error:
```
error: invalid conversion from ‘void*’ to ‘int*’
```
If you need to use a C++ compiler, you need to explicitly castato anint *:
```
int *h = (int *) a;
```
That one change allows this code to compile withg++as well.
|
I know that things have to be defined before they are used, but I am getting an "unknown type name error."
This is myNodedefinition:
```
struct Node {
position* p;
struct Node* next;
struct Node* prev;
};
```
This is my declaration (on line 96):
```
Node* hashtable[HashArraySize];
```
I get this error message:
```
P1.c:96:1: error: unknown type name ‘Node’
Node* hashtable[HashArraySize];
```
|
Unlike C++ which treatsstructtags as new type names, C requires an explicit typedef if you wish to useNodewithoutstruct:
```
typedef struct Node Node;
```
Alternatively, you could usestruct Nodein your declaration:
```
struct Node* hashtable[HashArraySize];
```
|
Can we use an array as an argument of another array?
I tried it inCprogramming language in Visual studio 2013 and It doesn't work!
|
For an array, as of c99, this isnotan valid operation
```
int main(void)
{
int vec[3]={1,2,3};
int sel[2]={1,2};
vec[sel]; // Invalid, will cause compilation to fail
return 0;
}
```
In order to select all of the variables you would have to loop through the array
```
int main(void)
{
int vec[3]={1,2,3};
int sel[2]={1,2};
int i;
int indv;
for(i=0;i<2;i++)
{
indv=vec[sel[i]];
## dosomething to indv
}
return 0;
}
```
|
I am studyingstructandtypedefand am totally new to coding
```
typedef struct
{
uint8_t ID;
uint8_t TanID;
uint8_t ProductID;
uint8_t SetlTme;
uint8_t NoOfStep
}product_Config;
typedef product_Config *product_Config_Ptr;
```
I am not getting what is last line is meant for
typedef product_Config *product_Config_Ptr;
|
Atypedefdefines an alias for a type.
In your exampletypedef Tank_Config *Tank_Config_Ptr;DeclaresTank_Config_Ptras an alias forTank_Config *.
So the following definitions are equivalent.
```
Tank_Config *ptr1;
Tank_Config_Ptr ptr2;
```
That being said, it is considered bad practice to hide a pointer inside of atypedef. It masks the fact that a pointer is being used and can cause confusion to readers of the code.
|
Is there any way in the GObject world to detect uninitialized pure virtual function at compile time?
I'd like to call a pure virtual method without checking it first.
```
/* pure_virtual_method must be non NULL */
base->pure_virtual_method();
```
But if it's not initialized, it will just SegV.
|
I don’t believe there is a way to perfectly check this at compile time, as (for example) your code could be linked into another library, a subclass derived from your class which defines the virtual method, and the implementation of the virtual method set toNULL(explicitly, or implicitly through not initialising it) in the subclass.
The conventional way to handle this is at runtime:g_assert (base->pure_virtual_method != NULL);
base->pure_virtual_method ();
Some static analysis tools may be able to check thisg_assert()constraint at compile time, although given the highly dynamic nature of subclassing in GObject, that’s unlikely.
|
I'm struggling to find I way to get the following string using the string.h functions memset(...), memcpy(...) and strcat(...):
0000001234abcd
I'm required to use memcpy and I can not find a way to do so without returning to the begining of the string.
```
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void main () {
char string [15];
memset((void *)string,'0',6*sizeof(char));
memcpy(string,"1234",4);
strcat(string,"abcd");
printf("String: %s\n",string);
}
```
Output-> String: 123400abcd
If anyone comes up with an idea, I would appreciate it so much.
|
You have two main issues:
forget to specify offset on use ofmemcpynot having string null terminated when applyingstrcat
Try this:
```
char string [15] = {0};
memset(string,'0',6);
memcpy(string + 6,"1234",4);
strcat(string,"abcd");
printf("String: %s\n",string);
```
Output: 0000001234abcd
|
I'm at the very beginning of learning to code (specifically C).
While writing a function which is counting the chars of an array for studying purposes, I was questioning myself (and I'm pretty sure about it), if there is the possibility to simplify this iteration:
```
int stringlength(char* s)
{
int i = 0;
while (s != NULL && *(s + i) != '\0')
i++;
return i;
}
```
I would like to keep thei++within the iteration itself (for loop?).
I'm appreciating any hint you guys got for me. If you find something question unrelated which I'm doing wrong - please let me know.
|
```
if(s == NULL)
return 0;
int i;
for(i = 0; s[i] != '\0'; i++);
```
This should solve your purpose, I believe.
EDIT:Adding a NULL check for the inputchar*sinceNULLcould be a possible value.
|
I know the difference betweenself.xxxand_xxxBut I don't understand the difference betweenself->_xxx = yyyand_xxx = yyy
Is it only a matter of writing in ObjC and C?
|
When accessing an ivar there is no difference betweenself->_ivarand_ivarin terms of resulting compiled code.
Only use case I can think of where it matters is if you have another local or global variable with the same name in the same scope, and you want to use the ivar.
|
Insendto:
```
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags,
const struct sockaddr *dest_addr, socklen_t addrlen);
```
From this call I have the socket descriptor of the sending socket, is there a way to get the socket descriptor of the receiver fromconst struct sockaddr *dest_addr
|
No. It is not possible. The socket descriptor you are asking to be retrieved is the socket descriptor of the receiver which for all that we know may be in some other process running in a totally different machine.
Also, I can't think of a reason as to what can be achieved by getting that socket descriptor.
|
Like consider I declare two pointers NULL. Then if I compare them, the result is true. But if we consider NULL to be "nothing" then how can we say that two "nothings" are equal? Is that for some specific reason? Any help appreciated. :)
|
In C, two null pointers of any type are guaranteed to compare equal. The macroNULLis defined asan implementation-defined null pointer constant, which inC99can be portably expressed as the integer value 0 converted implicitly or explicitly to the typevoid *.
|
I have a issue with a while loop.
```
while(!PORTB.F4); //Waiting for Echo
T1CON.F0 = 1; //Timer Starts
while(PORTB.F4); //Waiting for Echo goes LOW
T1CON.F0 = 0; //Timer Stops
```
does this equal to,
```
while(!PORTB.F4){
T1CON.F0 = 1;
}
while(PORTB.F4){
T1CON.F0 = 0;
}
```
|
No.while(!PORTB.F4);basically means "ExecutePORTB.F4until it returns/equals true".
Here's what (I think) your code does, based on the comments:
```
while (!PORTB.F4); // Wait for PORTB.F4 to equal 1 (true)
T1CON.F0 = 1; // When PORTB.F4 equals 1, set T1CON.F0 to true
while (PORTB.F4); // Wait for PORTB.F4 to equal 0 (false)
T1CON.F0 = 0; // When PORTB.F4 equals 0, set T1CON.F0 to false
```
|
Like consider I declare two pointers NULL. Then if I compare them, the result is true. But if we consider NULL to be "nothing" then how can we say that two "nothings" are equal? Is that for some specific reason? Any help appreciated. :)
|
In C, two null pointers of any type are guaranteed to compare equal. The macroNULLis defined asan implementation-defined null pointer constant, which inC99can be portably expressed as the integer value 0 converted implicitly or explicitly to the typevoid *.
|
I have a issue with a while loop.
```
while(!PORTB.F4); //Waiting for Echo
T1CON.F0 = 1; //Timer Starts
while(PORTB.F4); //Waiting for Echo goes LOW
T1CON.F0 = 0; //Timer Stops
```
does this equal to,
```
while(!PORTB.F4){
T1CON.F0 = 1;
}
while(PORTB.F4){
T1CON.F0 = 0;
}
```
|
No.while(!PORTB.F4);basically means "ExecutePORTB.F4until it returns/equals true".
Here's what (I think) your code does, based on the comments:
```
while (!PORTB.F4); // Wait for PORTB.F4 to equal 1 (true)
T1CON.F0 = 1; // When PORTB.F4 equals 1, set T1CON.F0 to true
while (PORTB.F4); // Wait for PORTB.F4 to equal 0 (false)
T1CON.F0 = 0; // When PORTB.F4 equals 0, set T1CON.F0 to false
```
|
I want to create and write to a file in a specific location on my computer. I have a fairly large project going, so I will just post the part in which I am stuck on.
```
f = fopen(FileName, "w");
```
FileName= the variable that contains a file name that I am going to write onto.
The problem is that it's creating and storing this file in the same directory location as my project. I want to store it in a subdirectory calledIndividualthat is located in that same directory. Any ideas?
|
You can solve in two methods:
Method 1)Change directory (e.g.usechdir()method)
Method 2)Add thepathonto the start of the filename.
|
Normally when a foo() have memory problem the whole program will simply core dump, crash. But does C have any protection ways to guarantee a program will not crash, just goto a state or simply return, when core dump happens inside foo()?
|
Can not say for try and catch statement in c but yes you can write signal handler to catch segfault.
Here is a link.How to catch segmentation fault in Linux?
|
I would like to know if it is possible to open a directory and then work with fopen to open a file from it. Like in the example:
I have a MAINDIR and inside of it I have file.txt so I would like to do the following:
```
void openFile(const char * filename)
{
opendir(MAINDIR);
fopen(filename, "r");
}
int main()
{
openFile("file.txt");
return 0;
}
```
I know i could do:fopen("path/to/main/dir/filename.txt", "r")but i want something more generic. Open a directory and then make every fopen work inside that directory
Thanks
|
You can change your working directory usingchdir(const char *)e.g:
```
chdir("/your/path/")
```
|
Can anyone explain me what is the difference between this:
```
typedef struct{
char a[10];
int b;
char c[8];
...
}test;
```
and this:
```
typedef struct test{
char a[10];
int b;
char c[8];
...
}test;
```
Thanks
|
```
typedef struct{
char a[10];
int b;
char c[8];
...
}test;
```
The above defines an anonymous struct and immediatelytypedefs it to the type aliastest.
```
typedef struct test{
char a[10];
int b;
char c[8];
...
}test;
```
This however, creates a struct namedstruct testas well as adding atypedeffor it.
In the first case, you will not be able to forward declare thestructif you need to.There's also aphilosophy(which I happen to agree with to a point), thattypedefing all structures by default makes code less readable, and should be avoided.
|
I've tried to create a matrix in C and have some input value, but I don't know why it throws me a "segmentation error". This is my code:
```
#include <stdio.h>
#include <stdlib.h>
int main() {
int i;
int j;
int **a;
a = malloc(5 * sizeof(int));
for (i = 0; i < 5; i++) {
a[i] = malloc(4 * sizeof(int));
}
for (i = 0; i < 5; i++) {
for (j = 0; j < 4; j++) {
scanf("%d", (a[i][j]));
}
}
return 0;
}
```
|
Given the answer by @Bathsheba, this is what your code should look like:
```
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int (*a)[4] = malloc( sizeof(int[5][4]) );
for(int i=0;i<5;i++)
{
for(int j=0;j<4;j++)
{
scanf("%d", &a[i][j]);
}
}
free(a);
return 0;
}
```
|
I want to show a progress bar in my program so I add this
```
#include <stdio.h>
#include <unistd.h>
int main() {
puts("begin");
for (int i = 0; i < 100; i++) {
printf("%d%% finished.\r", i);
fflush(stdout);
usleep(100000);
}
puts("end");
}
```
when it outputs tostdoutit shows nicely a line indicating the current progress.
However if I direct its output to a file, then all the lines withprintf("%d%% finished.\r", i);are missing.
Is it possible to keep all the lines in a file?
|
You can't really use formatting like that when output is redirected to a file, because output to the file only writes forward, it never writes backwards.
If you're on a POSIX system (like Linux or macOS) then you can useisattyto detect if your writing to an actual terminal or not, and change your output formatting accordingly.
|
It seems simple but I don't know how to do this.
What I have tried isprintf("%d.", i);but since the real code needs padding, the real code turns like thisprintf("%-4d.", i);and therefore it goes like this:"1 ."What I want is"1. "Any solutions?
Edit: If you can't see what I mean, I want the spaces after the dot, not before the dot. This is all for the sake of tidy output.
Another edit: I've also tried adding spaces after the dot itself, it looks horrible since it always print the same amount of spaces. With indentation, it controls the space output.
|
You are basically doing string manipulations and then padding the result. Create a temporary buffer to hold the string, and then pad that when you print it.
```
char buf[20];
snprintf(buf, sizeof(buf), "%d.", i);
printf("%-5s", buf);
```
|
i'm trying to run a simple program with Codeblocks 16.11. I get stuck trying to read a char from a file in the following code...
```
FILE *fo;
FILE *ft;
char c;
if ((fo = fopen("mayus.txt", "r")) == NULL){
perror("opening mayus");
}
int m;
m= fread(c, 1, 1, fo);
printf("I just read for the first time with result m = %d\n",m);
```
my file mayus.txt its just a txt with "AbCDEFGHIjK" wrote inside. I'm expecting to see a printf with m=1, but i keep getting m=0 in the console.
|
First check thefreadprototype:
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
and som= fread(c, 1, 1, fo);is wrong
What you need is
```
m = fread(&c, 1, 1, fo); // the first param should be a pointer to the buffer
```
|
How can I fix this warning?
```
typedef void (*VF_A)(PST_A); // Warning here: parameter names (without types) in function declaration
typedef struct ST_A_ {
...
VF_A vf_a;
} ST_A, *PST_A;
```
|
This question is similar toResolve circular typedef dependency?, but yours is slightly different in that you have a pointer to a function instead of a struct. Use the strategy fromthis answer.
The idea behind the problem is that you are trying to declare a new type and also define a struct at the same time. The solution is to separate these two:
```
typedef struct ST_A_ ST_A, *PST_A; // PST_A points to some struct, defined later
typedef void (*VF_A)(PST_A); // use PST_A to define VF_A
struct ST_A_ { VF_A vf_a; }; // now define the struct PST_A points to
```
|
I'm trying to check the number of set bits is 2 or more in negation of number. I'm trying to do that with checking if number is power of 2. But it's not working with negation of number. This is my code:
```
unsigned long int x = ~x; //x is given number
if(!(x & (x - 1))) printf("it have only one set bit);
```
Do you have any sugestion?
|
One of the best solutions for finding the number of set bits (the population) in an unsigned integer representation of a number is with theStanford Bit Twiddling Hack:
```
/* get number of 1's in binary number (population - pop) */
int getn1s (unsigned v) {
v = v - ((v >> 1) & 0x55555555); // reuse input as temporary
v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // temp
return (((v + (v >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24;
}
```
It has been published in a number of variations, and there is a general form available for up to 128-bit numbers as well.
|
I am trying to swap the value of two integers using pointers, see code below:
```
void swapArgs(int *a, int *b) {
int *temp = &b;
b = &a;
a = &temp;
printf("Swapped Arguments: A=%d, B=%d\n", *a, *b);
}
```
When the printf is executed, the resulting values are huge numbers. Can anyone explain to me what is wrong with my code? Still new to pointers.
|
The problem is that you need to copy the values, not the pointers:
```
int temp = *b;
*b = *a;
*a = temp;
```
Note:Your code is assigning pointers of wrong type -&aisint**, whilebisint*(i.e. the number of asterisks does not match). Your compiler should have given you warnings about that. Fixing them would fix the problem.
|
I am doing some string workshop for my c learning. There is a problem, where you ask for a user input let say "bob" and the code is to lower its ASCII code so it becomes "ana". I am at loss on how I go about doing this. Would it be something like
```
int main() {
char str[10];
char test[10];
int i;
printf("Enter a string: ");
scanf("%s", str);
while(str[i]!='\0') {
test[i]=str[i]; i++;
}
}
```
If I were to print this it only gives me the ASCII code and not the letters associated with it. How would I take the ASCII code and turn it into letters? Or is there a better method for it
|
You want:
```
test[i] = orig[i] - 1;
```
If I were to print this it only gives me the ASCII code
That just means you are not printing it correctly. This should work:
```
printf("orig: %s, transformed: %s\n", orig, test);
```
|
I have an issue with the portability of my code between french and english computers. Indeed, english uses point to separate double, as french uses comma.
The problem is that I can't read a number written in english (with a point) on a french computer, because it expects a comma.
What's the good way to do it ?
I though about making a french and an english file, but I think a better solution should exist
My code for the line with the double is actually :
```
errcd *= fscanf(file, "%lf\n", &N->biais1->l[i]);
```
|
you could read the number in as a character string and then convert it to a double....
```
int n;
double N;
char dummy[100];
fscanf("%s",dummy);
for (n=0;n<100;n++)
{ /* here you need to make a conversion , to . (or . to ,) */
if (dummy[n]==',') dummy[n]='.';
if (dummy[n]==\0) break;
}
N = atof(dummy);
```
|
I'm trying to check the number of set bits is 2 or more in negation of number. I'm trying to do that with checking if number is power of 2. But it's not working with negation of number. This is my code:
```
unsigned long int x = ~x; //x is given number
if(!(x & (x - 1))) printf("it have only one set bit);
```
Do you have any sugestion?
|
One of the best solutions for finding the number of set bits (the population) in an unsigned integer representation of a number is with theStanford Bit Twiddling Hack:
```
/* get number of 1's in binary number (population - pop) */
int getn1s (unsigned v) {
v = v - ((v >> 1) & 0x55555555); // reuse input as temporary
v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // temp
return (((v + (v >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24;
}
```
It has been published in a number of variations, and there is a general form available for up to 128-bit numbers as well.
|
I am trying to swap the value of two integers using pointers, see code below:
```
void swapArgs(int *a, int *b) {
int *temp = &b;
b = &a;
a = &temp;
printf("Swapped Arguments: A=%d, B=%d\n", *a, *b);
}
```
When the printf is executed, the resulting values are huge numbers. Can anyone explain to me what is wrong with my code? Still new to pointers.
|
The problem is that you need to copy the values, not the pointers:
```
int temp = *b;
*b = *a;
*a = temp;
```
Note:Your code is assigning pointers of wrong type -&aisint**, whilebisint*(i.e. the number of asterisks does not match). Your compiler should have given you warnings about that. Fixing them would fix the problem.
|
I am doing some string workshop for my c learning. There is a problem, where you ask for a user input let say "bob" and the code is to lower its ASCII code so it becomes "ana". I am at loss on how I go about doing this. Would it be something like
```
int main() {
char str[10];
char test[10];
int i;
printf("Enter a string: ");
scanf("%s", str);
while(str[i]!='\0') {
test[i]=str[i]; i++;
}
}
```
If I were to print this it only gives me the ASCII code and not the letters associated with it. How would I take the ASCII code and turn it into letters? Or is there a better method for it
|
You want:
```
test[i] = orig[i] - 1;
```
If I were to print this it only gives me the ASCII code
That just means you are not printing it correctly. This should work:
```
printf("orig: %s, transformed: %s\n", orig, test);
```
|
I have an issue with the portability of my code between french and english computers. Indeed, english uses point to separate double, as french uses comma.
The problem is that I can't read a number written in english (with a point) on a french computer, because it expects a comma.
What's the good way to do it ?
I though about making a french and an english file, but I think a better solution should exist
My code for the line with the double is actually :
```
errcd *= fscanf(file, "%lf\n", &N->biais1->l[i]);
```
|
you could read the number in as a character string and then convert it to a double....
```
int n;
double N;
char dummy[100];
fscanf("%s",dummy);
for (n=0;n<100;n++)
{ /* here you need to make a conversion , to . (or . to ,) */
if (dummy[n]==',') dummy[n]='.';
if (dummy[n]==\0) break;
}
N = atof(dummy);
```
|
I want the program to ask the user for a number, and if the user does not enter a number the program will say "input not a integer."
Thx for the help guys!
|
I propose this (it doesn't handle integer overflow):
```
#include <stdio.h>
int main(void)
{
char buffer[20] = {0}; // 20 is arbitrary;
int n; char c;
while (fgets(buffer, sizeof buffer, stdin) != NULL)
{
if (sscanf(buffer, "%d %c", &n, &c) == 1)
break;
else
printf("Input not integer. Retry: ");
}
printf("Integer chosen: %d\n", n);
return 0;
}
```
EDIT: Agreed with chux suggestions below!
|
I declare mpz variables and initialise them in a void function.
It's not working.
For example:
```
mpz_t a;
init();
...
void init(){
mpz_init(a);
....
}
```
No error.
```
init();
...
void init(){
mpz_t a;
mpz_init(a);
}
```
An error occurs.
|
From the little bit of code you have, the difference seems to be the scope of the variablea. What is the point of callingmpz_init(a)on a variable with only local scope (within yourinit()function)? Afterinit()returns,adisappears. If you need it for anything else later, the variablea, and presumably some of the side effects frommpz_init(), won't exist. If you want the side effects ofmpz_init()to persist past the end ofinit(), it must take effect on some structure that also persists past the end ofinit(). In your first example,ais declared with global scope, so it persists for the entirety of your program.
|
While browsing through the Linux kernel code, I came across something like this.
```
struct dma_chan {
int lock;
const char *device_id;
};
static struct dma_chan dma_chan_busy[MAX_DMA_CHANNELS] = {
[4] = { 1, "cascade" },
};
```
what is this -[4] = { 1, "cascade" },- usage implying ?
Note : Kernel version is 2.6.32
|
This is adesignated initializer.It initializes the fifth element to{ 1, "cascade" }explicitly, the other ones are default-initialized.
|
I declare mpz variables and initialise them in a void function.
It's not working.
For example:
```
mpz_t a;
init();
...
void init(){
mpz_init(a);
....
}
```
No error.
```
init();
...
void init(){
mpz_t a;
mpz_init(a);
}
```
An error occurs.
|
From the little bit of code you have, the difference seems to be the scope of the variablea. What is the point of callingmpz_init(a)on a variable with only local scope (within yourinit()function)? Afterinit()returns,adisappears. If you need it for anything else later, the variablea, and presumably some of the side effects frommpz_init(), won't exist. If you want the side effects ofmpz_init()to persist past the end ofinit(), it must take effect on some structure that also persists past the end ofinit(). In your first example,ais declared with global scope, so it persists for the entirety of your program.
|
While browsing through the Linux kernel code, I came across something like this.
```
struct dma_chan {
int lock;
const char *device_id;
};
static struct dma_chan dma_chan_busy[MAX_DMA_CHANNELS] = {
[4] = { 1, "cascade" },
};
```
what is this -[4] = { 1, "cascade" },- usage implying ?
Note : Kernel version is 2.6.32
|
This is adesignated initializer.It initializes the fifth element to{ 1, "cascade" }explicitly, the other ones are default-initialized.
|
While browsing through the Linux kernel code, I came across something like this.
```
struct dma_chan {
int lock;
const char *device_id;
};
static struct dma_chan dma_chan_busy[MAX_DMA_CHANNELS] = {
[4] = { 1, "cascade" },
};
```
what is this -[4] = { 1, "cascade" },- usage implying ?
Note : Kernel version is 2.6.32
|
This is adesignated initializer.It initializes the fifth element to{ 1, "cascade" }explicitly, the other ones are default-initialized.
|
The code i'm looking for is the following :
We have a source number100, a destination number,50and we have10steps.
100 ----> 50 in 10 steps.
How can i find the value X, corresponding tothe number i have to subto 100, 10 times to have 50. I found :dest*steps/srcbut didn't work...
Regards.
|
It's as simple as this
```
X = (src-dest)/NumOfSteps
```
|
So when I create an array in the programming language c, what are all of the elements initially initialized to? For instance,
```
char array[5];
```
Creates an array with 5 elements. What are the elements initially? I printed the elements out, but it seemed to be random, so are they just created randomly, or is there a method to how they are made?
|
"What are the elements initially" will depend on where and how your array is defined.
A automatic array defined in block scope will contain garbage. Meanwhile, a static array will be initialized with zeros.
```
char a[5]; /* zeros */
int main()
{
static char b[5]; /* zeros */
char c[5]; /* garbage */
}
```
If the array is declared as a struct member, then the above rules apply to the definition of the containing struct object.
|
A simple question. I have a functionint function(void). Are the following statements the same:
```
a. if( function() == somevalue ) //somevalue is integer
b. if( (function()) == somevalue )
c. if( (ret = function()) == somevalue ) //where ret is an integer
```
|
All three of them are functionally equivalent as far as comparing the return value is concerned.
(a) and (b) are equivalent whereas (c) lets you save the return value fromfunction(inret) if you need later. Unless you need the return value offunction()later for some other purpose, I'd recommend using (a).
|
What's the shortest way I can do an if..else statement to check if all int array elements are equal to certain numbers? For example in pseudocode:
```
if (allElementsOfIntArray == -1)
//do something
else if (allElementsOfIntArray == 1)
//do something else
```
I have another variable that isconst int arraySize
My Arduino code is getting really messy at this point so I'm just trying to find the shortest way to implement this so it doesn't look like a mess to others that have to read it.
|
```
bool all_are(int* i_begin, std::size_t sz, int x)
{
const int* i_end = i_begin + sz;
for(; i_begin != i_end; ++i_begin)
if(*i_begin != x) return false;
return true;
}
```
```
if (all_are(my_array, arraySize, -1))
//do something
else if (all_are(my_array, arraySize, 1))
//do something else
```
|
This question already has answers here:Why does C have a distinction between -> and .?(7 answers)Closed6 years ago.
What is the difference between->and.while calling variables in a structure?I have seen both of them used in various scenarios but couldn't identify the difference between them.
|
->means you have a variable that points to a piece of memory containing the struct. To access its members, you must dereference the pointer and then add the offset to the member. the->does that for you.the.means your variableisthe structure and you only need to add the offset to the member.
As user Eliot B points out, if you have a pointersto a struct, then accessing the memberelemcan be done in two ways:s->elemor(*s).elem.
With(*s)you have an expression that "is" the struct and you now use the dot-operator to accesselem.
|
I want to read lines from stdin with variable length until the end of input. The example input would be something like this:
```
#.###############
#...#...........#
#.###.#####.#.###
#...........#...#
###############.#
```
but with various lengths of rows and columns.
What is the best way to read it into 2d array except for reading it as chars?
|
Assuming you're running on a POSIX-compliant system, you can usethegetline()functionto read lines of almost arbitrary length (only limited by available memory). Something like this should work:
```
char *line = NULL;
size_t bytes = 0UL;
for ( int ii = 0;; ii++ )
{
ssize_t bytesRead = getline( &line, &bytes, stdin );
if ( bytesRead <= 0L )
{
break;
}
lineArray[ ii ] = strdup( line );
}
free( line );
```
You'll have to add error checking and take care oflineArrayyourself.
|
I am learning the pointers in C. I am little confused about how below program is working
```
int main()
{
int x=30, *y, *z;
y=&x;
z=y;
*y++=*z++;
x++;
printf("x=%d, y=%p, z=%p\n", x, y, z);
return 0;
}
```
output is
```
x=31, y=0x7ffd6c3e1e70, z=0x7ffd6c3e1e70
```
yandzare pointing to the next integer address of variablex.
I am not able to understand how this line is working
```
*y++=*z++;
```
can someone please explain me how this one line is understood by C?
|
*y++=*z++;actually means
```
*y = *z;
y += 1*(sizeof(int)); //because int pointers are incremented by 4bytes each time
z += 1*(sizeof(int)); //because int pointers are incremented by 4bytes each time
```
So pointed value does not affected, pointers are incremented by one.
|
How can I convert char array into its ascii decimal value.
This array:
```
uint8_t character[4];
character[0] = '1';
character[1] = '2';
character[2] = '3';
character[3] = '4';
```
To:
```
uint32_t value = 49505152
```
Thanks! and if possible convert it back again.
|
How can I convert char array into its ascii decimal value.
'1'is49. So'1' * 100 + '2'is4950. I suggest a for loop.
Thanks! and if possible convert it back again.
49505152 % 100is52,49505152 / 100is495051
Again, a for loop would be useful.
With this infos, I guess you will complete your homework in no time.
|
I have the following code and I would like it to break after entering the sentinel number only once but at the moment I have to input the sentinel number twice for the code to break. Any ideas?
```
#include <stdio.h>// Include a standard C Library
#define Sentinel_Numb -1
int main(){
int ID[360];
float seconds[360];
int i = 0;
printf("please enter the ID and how many seconds to calculate enter -1 when done\n");
while (1)
{
scanf_s("%d",&ID[i]);
scanf_s("%f",&seconds[i]);
if( ID[i] == Sentinel_Numb || seconds[i] == Sentinel_Numb){
break;
}
i++;
}
return 0;
}
```
|
Change to:
```
scanf_s("%d",&ID[i]);
if (ID[i] == Sentinel_Numb)
break;
scanf_s("%f",&seconds[i]);
if (seconds[i] == Sentinel_Numb)
break;
```
|
Let's say the user is prompted for the date - e.g.Friday.
How can that string be used to correctly compare with another sting?
```
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t current_time;
struct tm * time_info;
char timeString[9];
time(¤t_time);
time_info = localtime(¤t_time);
strftime(timeString, sizeof(timeString), "%A", time_info);
printf("%s\n",timeString);
if (timeString == "Friday")
{printf("Weekday");
}
else
{printf("not weekday");
}
return 0;
}
```
The program keeps printing outnot weekday.
|
Usestrncmp()instead of comparing the string with==:
```
if (strncmp(timeString,"Friday",7) == 0)
{printf("Weekday");
}
```
See this in action at tutorialspoint.com:Friday
Currently, it is Thursday (for ~50% of the world) - so try this one:Thursday
|
I have some legacy code that does this all over the place:
```
int fd; // open a file
if(fd == -1)
{
close(fd);
}
```
This looks very wrong to me.
Is closing an invalid file descriptor valid?
|
According to manual:
Upon successful completion, a value of 0 is returned. Otherwise, a
value
of -1 is returned and the global integer variable errno is set to indicate the error.
and then:
The close() system call will fail if:
[EBADF] fildes is not a valid, active file descriptor.
Then nothing harmful will happen.
|
I saw the following Makefile online (here):
```
hello:
clean:
$(RM) hello
```
When there is a hello.c file in the same directory with the Makefile,makecommand in Terminal buildshelloexecutable. Whenmake cleanis run,helloexecutable is removed byrm -f helloinstead. So,$(RM) hellomeansrm -f hellohere.
What does $(FOO) mean? Is it a special syntax of Makefile, or something bash command?Can I run other commands as well as $(RM), like $(PWD)?
|
It's a Makefile variable. There are explicit variables (which are defined inside a Makefile) and implicit variables (defined by make, can be overriden by you).
You can see a list of implicit variables with this flag:
```
make -p
```
some of the most common variables can be found at:10.3 Variables Used by Implicit Rules
You can expand a variable with the syntax$(NAME)or${NAME}
|
This question has been asked before, but from what I have seen it's all people that are misusing'a.b'to get pointer values. I AM using'a->b'but it is still throwing this error.
Here's my code, it's meant to be a dynamic stack:
Header file:
```
typedef struct etCel{
element *ele;
struct cel *suiv;
} cel;
typedef cel* pile;
pile init_pile();
int affiche_pile(pile *p);
```
.c file:
```
pile init_pile(pile *p){
return NULL;
}
int affiche_pile(pile *p){
printf("Valeurs de la pile:\n");
while(p!=NULL){
affiche_element(p->ele);
printf("\n");
p=*(p->suiv);
}
return 1;
}
```
|
```
typedef cel* pile;
```
and
```
int affiche_pile(pile *p){
```
This leads to believe thatpis now a pointer to a pointer. Expand the declarations and you get
```
cel* *p;
```
So either you change the function signature toint affiche_pile(pile p)ortypedef cel pile
|
Let's say the user is prompted for the date - e.g.Friday.
How can that string be used to correctly compare with another sting?
```
#include <stdio.h>
#include <time.h>
int main(void)
{
time_t current_time;
struct tm * time_info;
char timeString[9];
time(¤t_time);
time_info = localtime(¤t_time);
strftime(timeString, sizeof(timeString), "%A", time_info);
printf("%s\n",timeString);
if (timeString == "Friday")
{printf("Weekday");
}
else
{printf("not weekday");
}
return 0;
}
```
The program keeps printing outnot weekday.
|
Usestrncmp()instead of comparing the string with==:
```
if (strncmp(timeString,"Friday",7) == 0)
{printf("Weekday");
}
```
See this in action at tutorialspoint.com:Friday
Currently, it is Thursday (for ~50% of the world) - so try this one:Thursday
|
I have some legacy code that does this all over the place:
```
int fd; // open a file
if(fd == -1)
{
close(fd);
}
```
This looks very wrong to me.
Is closing an invalid file descriptor valid?
|
According to manual:
Upon successful completion, a value of 0 is returned. Otherwise, a
value
of -1 is returned and the global integer variable errno is set to indicate the error.
and then:
The close() system call will fail if:
[EBADF] fildes is not a valid, active file descriptor.
Then nothing harmful will happen.
|
I saw the following Makefile online (here):
```
hello:
clean:
$(RM) hello
```
When there is a hello.c file in the same directory with the Makefile,makecommand in Terminal buildshelloexecutable. Whenmake cleanis run,helloexecutable is removed byrm -f helloinstead. So,$(RM) hellomeansrm -f hellohere.
What does $(FOO) mean? Is it a special syntax of Makefile, or something bash command?Can I run other commands as well as $(RM), like $(PWD)?
|
It's a Makefile variable. There are explicit variables (which are defined inside a Makefile) and implicit variables (defined by make, can be overriden by you).
You can see a list of implicit variables with this flag:
```
make -p
```
some of the most common variables can be found at:10.3 Variables Used by Implicit Rules
You can expand a variable with the syntax$(NAME)or${NAME}
|
This question has been asked before, but from what I have seen it's all people that are misusing'a.b'to get pointer values. I AM using'a->b'but it is still throwing this error.
Here's my code, it's meant to be a dynamic stack:
Header file:
```
typedef struct etCel{
element *ele;
struct cel *suiv;
} cel;
typedef cel* pile;
pile init_pile();
int affiche_pile(pile *p);
```
.c file:
```
pile init_pile(pile *p){
return NULL;
}
int affiche_pile(pile *p){
printf("Valeurs de la pile:\n");
while(p!=NULL){
affiche_element(p->ele);
printf("\n");
p=*(p->suiv);
}
return 1;
}
```
|
```
typedef cel* pile;
```
and
```
int affiche_pile(pile *p){
```
This leads to believe thatpis now a pointer to a pointer. Expand the declarations and you get
```
cel* *p;
```
So either you change the function signature toint affiche_pile(pile p)ortypedef cel pile
|
I wanna ask how it can not get integer from a string
for example, here are my code:
```
int main() {
char str[] = "ababbababa-1998";
int nr = atoi(str);
printf("%d\n", nr);
return (EXIT_SUCCESS);
}
```
when running, it print out 0 but not 1998, how can I fix it ?
|
In your case you can usestrtok.
```
int main() {
char str[] = "ababbababa-1998";
char * const first_part = strtok(str, "-");
if (first_part == NULL) {
return 1;
}
char * const second_part = strtok(NULL, "-");
if (second_part == NULL) {
return 1;
}
int nr = atoi(second_part);
printf("%d\n", nr);
return 0;
}
```
You can look atWhy is there no strtoi in stdlib.h?for error check atoi.
|
For percentage in form "x.%x", the first x <= 3 bits, the second x == 2 bits
```
a1 = 93.11;
a2 = 33.72;
a3 = 30.69;
b1 = 0.00;
b2 = 0.00;
b3 = 0.00;
printf("%3.2f%% %3.2f%% %3.2f%%\n", a1, a2, a3); // wrong, how to modify?
printf("%3.2f%% %3.2f%% %3.2f%%\n", b1, b2, b3);
```
Output:93.11% 33.72% 30.69%0.00% 0.00% 0.00%But the output is not right. How to align to make output below:
|
I believe you want:
```
printf("%5.2f%% %5.2f%% %5.2f%%\n", a1, a2, a3);
printf("%5.2f%% %5.2f%% %5.2f%%\n", b1, b2, b3);
```
The5means, print at least 5 characters.
```
12345
93.11 <== 5 total characters, counting the decimal point.
0.00 <== 5 total characters, first char is a [space]
```
Link to IDEOne Code
The output is:
```
93.11% 33.72% 30.69%
0.00% 0.00% 0.00%
```
|
Closed.This question needsdebugging details. It is not currently accepting answers.Edit the question to includedesired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.Closed6 years ago.Improve this question
Please, can someone help me with how to calculate a simple log2 in C? I tried with this code, but it does not work:
```
printf( "log( %f ) = %f\n", x, log2(x) );
```
|
```
#include <stdio.h>
#include <math.h>
int main() {
double x = 42.0;
printf( "log( %f ) = %f\n", x, log2(x) );
return 0;
}
```
OUTPUT
```
% ./a.out
log( 42.000000 ) = 5.392317
%
```
|
i've try to compile this simple program, it will alloc a dyamic array and return it with a multiple of 5 in every location. but it doesn't work, it report me an error in the pointer.
```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[]) {
int n;
int i;
int* ptra;
scanf("%d", &n);
ptra = malloc(n*(sizeof(int)));
for(i=0; i<=n; i++){
ptra[i] = (5*(i+1));
printf("%d\n", ptra[i]);
}
return 0;
}
```
|
Index range forptramust be from0ton-1(both inclusive). But here:
```
for(i=0;i<=n;i++){
```
you are going out of bounds, which isundefined behaviour. Change it to:
```
for(i = 0; i < n; i++) {
```
Note: Always check the return of all the standard functions for failures (scanf()andmalloc()in your code).
|
I have a situation where I need to convert a hex string0x8aaaf200to auint32_t. I first tested it on my local machine (Linux Debian box).
```
// str contains "0x8aaaf200"
uint32_t var = (uint32_t)strtol(str, NULL, 0);
printf("conversion: %x \n\n", var); // prints 8aaaf200
```
I then ran it on a different machine (Android based), but to my surprise, the output comes out to be7fffffff. I think it may be related touint32_tsize on different machines.
Does anyone have a suggestion on how to fix it ? I can't change theuin32_ttype usage, as it is part of code written by someone else.
|
You are actually getting LONG_MAX (which is 2147483647 or 0x7FFFFFFF) as return value, which happens when the value passed to strtol is greater than LONG_MAX. You should use the unsigned type to represent that number on your machine. Please use function strtoul() in place of strtol.
|
I'm trying to compare a string with another string and if they match I want the text "That is correct" to output but I can't seem to get it working.
Here is the code:
```
int main ()
{
char * password = "Torroc";
char * userInput;
printf("Please enter your password: ");
scanf("%s", userInput);
if (strcmp(password, userInput) == 0) {
printf("That is correct!");
}
}
```
|
In your code, userInput pointer does not have provision to hold the string that you are about to pass using the scanf call. You need to allocate space for the cstring userInput in your stack, before you try to save/assign any string to it. So...
You need to change the following code:
```
char * userInput;
```
to:
```
char userInput[200];
```
Here, 200 is just an arbitrary value. In your case, please select the max. length of the string + 1 for the (\0).
|
Works fine except skips first character in string name. Can anyone explain what I am not seeing?
```
#include "stdio.h"
/*
*BN
*/
int main(void) {
// Disable stdout buffering
//setvbuf(stdout, NULL, _IONBF, 0);
struct data {
char name[40];
char street[50];
char city[30];
char state[3];
char zip[6];
float salary;
};
struct data p = {
scanf("%s %s %s %s %s %f", &p.name, &p.street, &p.city, &p.state, &p.zip, &p.salary)
};
printf(" Name:%s\n Street:%s\n City:%s\n State:%s\n Zipcode:%s\n Salary:%.2f", p.name, p.street, p.city, p.state, p.zip, p.salary);
return 0;
}
```
|
Initialize your structure asstruct data p;then you do thescanf.
```
struct data p;
scanf("%s%s%s%s%s%f", &p.name, &p.street, &p.city, &p.state, &p.zip, &p.salary);
```
You can check somestructstuff here.
|
Why do i get negative number when executing this?
```
unsigned int a = 1 << 31;
printf("%d",a);
```
I already checked size of integer on my computer and it is 4 Bytes. So my integer number is consisted of 32 bits and doing 31 shifts to the left I should get until the most significant bit. That means that it should be positive number, but i always get negative.
What I get : -2147483648
What I expected : Some positive number ( probably 1073741824)
What am I missing here?
|
The problem isn't the fact that you're bit shifting. You are simply not printing in the corresponding format.
%d or %i is for printing int, and thus when you try to print your unsigned int, it is converted into an signed int.
See here:What is the format specifier for unsigned short int?
orhttps://www.le.ac.uk/users/rjm1/cotter/page_30.htm
|
I'm trying to create a dbus service using sdbus (sd-bus?), that will respond with an fd representing a socket.
My client is able to receive strings and ints, so I have the basics covered. What I am looking for is how to package the fd as an "h" type in the response message.
|
It seems that there is no magic required.
The server creates the socket and replies to the client in the most apparent way (pseudo code):
```
fd = socket(AF_UNIX, SOCK_STREAM, 0);
sd_bus_reply_method_return(message, "h", fd);
```
The client just had to dup() the incoming fd and is then able to access it:
```
int fd;
int dup_fd;
sd_bus_message_read(message, "h", &fd);
dup_fd = dup(fd);
```
|
I'm trying to compare a string with another string and if they match I want the text "That is correct" to output but I can't seem to get it working.
Here is the code:
```
int main ()
{
char * password = "Torroc";
char * userInput;
printf("Please enter your password: ");
scanf("%s", userInput);
if (strcmp(password, userInput) == 0) {
printf("That is correct!");
}
}
```
|
In your code, userInput pointer does not have provision to hold the string that you are about to pass using the scanf call. You need to allocate space for the cstring userInput in your stack, before you try to save/assign any string to it. So...
You need to change the following code:
```
char * userInput;
```
to:
```
char userInput[200];
```
Here, 200 is just an arbitrary value. In your case, please select the max. length of the string + 1 for the (\0).
|
Works fine except skips first character in string name. Can anyone explain what I am not seeing?
```
#include "stdio.h"
/*
*BN
*/
int main(void) {
// Disable stdout buffering
//setvbuf(stdout, NULL, _IONBF, 0);
struct data {
char name[40];
char street[50];
char city[30];
char state[3];
char zip[6];
float salary;
};
struct data p = {
scanf("%s %s %s %s %s %f", &p.name, &p.street, &p.city, &p.state, &p.zip, &p.salary)
};
printf(" Name:%s\n Street:%s\n City:%s\n State:%s\n Zipcode:%s\n Salary:%.2f", p.name, p.street, p.city, p.state, p.zip, p.salary);
return 0;
}
```
|
Initialize your structure asstruct data p;then you do thescanf.
```
struct data p;
scanf("%s%s%s%s%s%f", &p.name, &p.street, &p.city, &p.state, &p.zip, &p.salary);
```
You can check somestructstuff here.
|
I'm making a simple 'game' with ncurses in C, and for name input I usegetnstr. I have the following code:
```
printw("What is your name? ");
char name[10];
int namelen = getnstr(name, 10);
```
Now, I want to allow max 10 characters, and I want to use the length of the name for the border columns. However,namelenis 0 for some reason (I thoughtgetnstrreturned the length).
How can I get the correct length of the name? So if I insert Josh as name I get 4.sizeof(name)returns 10 so it's no use.
|
Why not do this :
```
char s[10];
scanf("%10s", s);
printf("Length : %d\n", (int) strlen(s));
```
Forstrlen, do#include <string.h>first.
|
I have some code:
```
int strlen_rec(char arr[])
{
if(arr[0]=='\0')
return 0;
else
return 1 + strlen_rec(&arr[1]) ;
}
```
The line
```
return 1 + strlen_rec(&arr[1]) ;
```
is confusing me. Can someone explain what it does?
|
This function counts the length of a string using recursion. It may look confusing since it's using an array like a pointer.&ar[1]is increasing the pointer (calling the function with the address of the next byte). C strings are terminated with a null byte which isn't included in the length so it returns 0 when reached.
|
I found several code snippets for disabling GCC optimization for dedicated code parts.
with pragma GCC optimize(0)
But I could not found something like that for Greenhils compiler.
Is there no such option?
|
From the manual:
```
#pragma ghs Ostring
Turns on optimizations. The optional string may contain any or all of the following letters:
L — Loop optimizations
M — Memory optimizations
S — Small (but Slow) optimizations
#pragma ghs ZO
Disables all optimizations, starting from the next function.
```
|
I likely don't understand thesprintffunction.
```
char s[30];
int i;
scanf("%d",&i);
sprintf(s,i); /*->warning: makes pointer from int*/
```
|
sprintfaccepts the targetchar[]as the first argument, and the rest of the arguments are thesame asprintf, orscanf's(format string first, then additional args if present).
So, in your case, it would simply be:
```
char s[30];
int i;
scanf("%d",&i);
sprintf(s, "%d", i);
```
For an input of 3,swould become '3'.
Withsprintf(s, "%d%d", i, i);, it would become '33'.
The reason it tried to interpretias a pointer in your example, was that itexpecteda (char) pointer (the format string).
|
It is convenient for programmers to implement rpc client and server on Linux by using command rpcgen to generate the client stub and the server stub automaticly.
Now I want to implement a rpc client on Windows to call procedures from the server on Linux. In Linux, we can use command likegcc -Wall -o test_client test_client.c test_clnt.cto generate excutable program of the client, but how can I manage it on Windows?
|
Windows has its own version ofRPC. It works fine between Windows boxes only.
For interoperability you need to look at CORBA or WCF.
|
How to reduce the expression? If I am right, x assign 0 if only x = 0; otherwise x assign 1. However, How can it do shorten?
```
x = (x = 0) ? 0 : 1
```
|
Assuming that you meantx == 0, this is pretty short:
```
x = !!x;
```
Explanation:
Ifxis0,!xis1, so!!xis0.Ifxis not0,!xis0, so!!xis1.
Ifx = 0is intentional, the code is undefined.
But you can make a shorter version that is well-defined and which I believe captures the writer's intention:
```
x = 1;
```
since the value ofx = 0is0.
|
I want to makevarargsfunction for freeing multiple pointers at once, mostly to clean up the code. So I have:
```
void free_all( ... ) {
va_list arguments;
/* Initializing arguments to store all values after last arg */
// but there are no args!
va_start ( arguments, ????? );
/* we expect the caller to send last argument as NULL **/
void* pointer = va_arg ( arguments, void* );
while( (pointer = va_arg ( arguments, void* ))!=NULL ) {
free(pointer);
}
va_end ( arguments ); // Cleans up the list
}
```
So what to put inva_start ( arguments, ????? )?
|
It's simply not possible. You MUST have a non vararg argument, always. In your case
```
void free_all(void *first, ...);
```
could work.
|
I have to count the length of binary representation of an integer.
I've tried something like this:
```
int binaryLength(int n)
{
int i = 32;
while (i > 0)
{
if (n >> i & 1) break;
else i--;
}
return i;
}
```
But when i have number like 9 (1001), this function returns me 32.
|
I'd abandon the loop approach if I were you.
Here's the fastest way I know of - coded specifically for a 32 bitint. It will not work for a negative integer (the bit patterns for negative integers are platform dependent anyway). Add an extra line for a 64 bitint; the scheme ought to be obvious.
```
int binaryLength(int n)
{
int i = 0; // the minimum number of bits required.
if (n >= 0x7FFF) {n >>= 16; i += 16;}
if (n >= 0x7F) {n >>= 8; i += 8;}
if (n >= 0x7) {n >>= 4; i += 4;}
if (n >= 0x3) {n >>= 2; i += 2;}
if (n >= 0x1) {n >>= 1; i += 1;}
return i;
}
```
|
Consider the following code:
```
const char* text = "hi";
printf("%s\n",text);
printf("%p\n", &text);
printf("%p\n", text);
```
From where does everyprintftakes the value it prints?
What are the differences?
|
So let's remember that a pointer is a memory address.textis, as I suspect you know, a pointer to the first (or 0th, depending on how you like to think about it) block of a char array. The&is the "address" operator, which returns the memory address (that is, a pointer to...) whatever comes after it. Since the literal pointer value oftextis itself some kind of data, it has to be stored somewhere in memory. So&textreturns the address of where the value oftextis stored. Like this:
|
When I try to compile my file, I have this error:
```
/tmp/ccN3Rs5C.o : Dans la fonction « BellmanFord » :
bellman.c:(.text+0x27c) : référence indéfinie vers « min »
collect2: error: ld returned 1 exit status
```
I searched on several forums without success.
The problem is my function?
|
You might be missing one of the following:
Compilation of the file that contains the function definition, orMissing to the link the file that contains compilation output (from
the above step).
For a quick overview of compilation and linking process, see thishttps://www3.ntu.edu.sg/home/ehchua/programming/cpp/gcc_make.html#zz-1.4
|
I have 4 bytes:
```
buffer_RX[3]= \x70;
buffer_RX[4]= \xb4;
buffer_RX[5]= \xc5;
buffer_RX[6]= \x5a;
```
I want to concatenate them in order to have such representation 0x70b4c55a:
I already did thisplaintext[1]= (rx_buffer[3]<<8)|rx_buffer[4];This is the result that I have:70b4
```
plaintext[1]= (rx_buffer[3]<<8)|(rx_buffer[4]<<8)|(rx_buffer[5]<<8)|rx_buffer[6]
```
It doesn't work.
Please I need help.
|
This is one way to do it :
```
plaintext[1] = (buffer_RX[3] << 24) |
(buffer_RX[4] << 16) |
(buffer_RX[5] << 8) | buffer_RX[6];
```
|
I want to use Xcode for C/C++ project.
I don't care about build/compilation, all i want is to use it as editor.
Needs:
- Find symobol , References , callers etc
I've opened a console project, i can search for a symbol in the same file but nothing else. (for example, right click + jump to definition gives me a question mark ('?').
Any pointer to what needs to be done ?
Thanks,
Shaul.
|
From my experience, XCode is not designed to work well with C++. For example, you'll find that simple refactoring, such as renaming a function and automatically renaming usages, doesn't work well with XCode. I find AppCode works a lot better for (Obj)C++ development. Worth a look.
|
When I try to compile my file, I have this error:
```
/tmp/ccN3Rs5C.o : Dans la fonction « BellmanFord » :
bellman.c:(.text+0x27c) : référence indéfinie vers « min »
collect2: error: ld returned 1 exit status
```
I searched on several forums without success.
The problem is my function?
|
You might be missing one of the following:
Compilation of the file that contains the function definition, orMissing to the link the file that contains compilation output (from
the above step).
For a quick overview of compilation and linking process, see thishttps://www3.ntu.edu.sg/home/ehchua/programming/cpp/gcc_make.html#zz-1.4
|
I have 4 bytes:
```
buffer_RX[3]= \x70;
buffer_RX[4]= \xb4;
buffer_RX[5]= \xc5;
buffer_RX[6]= \x5a;
```
I want to concatenate them in order to have such representation 0x70b4c55a:
I already did thisplaintext[1]= (rx_buffer[3]<<8)|rx_buffer[4];This is the result that I have:70b4
```
plaintext[1]= (rx_buffer[3]<<8)|(rx_buffer[4]<<8)|(rx_buffer[5]<<8)|rx_buffer[6]
```
It doesn't work.
Please I need help.
|
This is one way to do it :
```
plaintext[1] = (buffer_RX[3] << 24) |
(buffer_RX[4] << 16) |
(buffer_RX[5] << 8) | buffer_RX[6];
```
|
I want to use Xcode for C/C++ project.
I don't care about build/compilation, all i want is to use it as editor.
Needs:
- Find symobol , References , callers etc
I've opened a console project, i can search for a symbol in the same file but nothing else. (for example, right click + jump to definition gives me a question mark ('?').
Any pointer to what needs to be done ?
Thanks,
Shaul.
|
From my experience, XCode is not designed to work well with C++. For example, you'll find that simple refactoring, such as renaming a function and automatically renaming usages, doesn't work well with XCode. I find AppCode works a lot better for (Obj)C++ development. Worth a look.
|
I'm using a for loop to search for the smallest value present within an array and printing that value out. I want to print out what position that value is in in the array (0-9), how would I do this?
```
int smallest = array[0];
for (counter = 0; counter < 10; counter++) {
if (smallest > array[counter]) {
smallest = array[counter];
}
}
printf("The smallest value stored within the array is %d", smallest);
```
|
You just need another variable (initialized "0") in which you store the value of "counter" each time the if condition is true like below:
```
int smallest = array[0];
int position = 0;
for (counter = 0; counter < 10; counter++) {
if (smallest > array[counter]) {
smallest = array[counter];
position = counter;
}
}
printf("The smallest value stored within the array is %d and position = %d", smallest, position);
```
|
I've recently begun usinga new ELF loader. The loader requires you to link your applications withld -r.
The problem is that GCC no longer warns me of undefined functions, and then the loader (obviously) fails to find them.
How do I link withld -r, and get the undefined symbols method.
I am usingld -rfor relocation purposes, so a different way to include relocations will also work for me.
|
In your makefile, define an intermediate target where you link with all the optionsbutthe-rone, to a file in the temporary directory (so you're sure not to use it).
If this phase succeeds, then proceed to the real link with the-roption.
|
I was trying some C codes in Dev C++ and Visual C++.
For Example:
```
int t =6;
printf("\nt = %d ",&t);
```
The output is :
```
t = 2358848
```
why is it so ? How can I get the value of t?
|
&tgives you theaddress oft, not its value.
To print the value do:
```
printf("\nt = %d ", t);
```
|
As far as I can tell I've followed the advice given by other users, but I still get a segfault when I try to return a pointer to an array. The printf in main returns nothing, so I'm guessing that the pointer isn't to anything on the heap?
```
#include <stdio.h>
#include <stdlib.h>
int * stringy(int length){
int *ptr = malloc(sizeof(int)*length);
int i;
for(i = 0; 1 < length; i++){
ptr[i] = i;
}
return(ptr);
}
void main(int argc, char **argv){
int strlen = 12;
int *newptr = stringy(strlen);
printf("%d\n",newptr[0]);
free(newptr);
}
```
|
It seems like there is a typo in your code. Instead of
```
for(i = 0; 1 < length; i++){
```
, it looks like you meant
```
for(i = 0; i < length; i++){
```
|
I bet what I want to do isn't that hard, but I'm not figuring it out on my own.
I want to calculate bytes per second over a number of milliseconds in C language code without use of float or double.
For instance using only integers, how can I compute bytes per second if 123000 bytes came in the past 1300ms?
Thanks
|
I assume you are using 32 bit system and int is 32 bit data type. Also consider round-off for integer data type
Here is the code for reference.
```
int main()
{
int bytes_count = 123000; /* total bytes captured */
int time_in_ms = 1300; /* capture end time - start time */
int byte_rate_per_second = (bytes_count * 1000)/ time_in_ms; /* It will round-off as it's integer type*/
int roundoff = ((bytes_count % time_in_ms) * 10)/time_in_ms; /*gives roundoff in one point precision. Use recursion for more precision*/
return 0;
}
```
|
I want to scan some words, and put them in a string array, then print it. But all i got is some memory garbage...
```
char arrayOfWords[50][50];
char array2[50][50];
int i;
for (i=0; i<5; i++)
{
scanf ("%s" , arrayOfWords[i]);
array2[i][50] = arrayOfWords[i];
}
for (i=0; i<5; i++)
{
printf ("%s\n" , array2[i]);
}
return 0;
```
|
You can't just copy strings using the assignment operator (=).
Change:
```
array2[i][50] = arrayOfWords[i];
```
to:
```
strcpy(array2[i], arrayOfWords[i]);
```
|
If I have a .jar file with a compiled scala method, is there any way to call it from a C/C++ dll ? How can I do this? I have only been able to find infos on the opposite.
|
A Scala program (once compiled) is a Java class. So follow this suggestion:How to access the Java method in a C++ application
|
I wrote a program in C to check if the entered number is divisible by 100, but I've run into a problem. If I enter a number with 11 digits or more (with the last two digits being zeroes, of course), it says the number is not divisible by 100, even though it is. Help?
```
#include <stdio.h>
#include <conio.h>
int main()
{
long int a;
printf("Enter the number: ");
scanf("%d" , &a);
if(a%100==0)
{printf("This number is divisible by 100");}
else
{printf("This number is not divisible by 100");}
getch();
}
```
|
Your number just doesn't fit intolong inttype, so the actual number you get is not what you expect. Try usingunsigned long long, but be aware that numbers greater than2^64 - 1won't fit anyway. Also, you should usescanf("%llu", &a)in this case
|
For some reason this condition is not passing as true even tho the variable watch is showing var equal.
```
if(arr[r1][1] != NULL) {
t_plat = arr[r1][1];
t_ver = arr[r1][2];
if((arr[r2][1] == t_plat) && (arr[r2][2] == t_ver))
```
|
As you can see yourself from the screenshot the objectarr[r2][1]stores value0xb01a70while the objectt_platstores value0xb01770.
Thus if you compare the values stored in these objects like
```
if((arr[r2][1] == t_plat) )
```
you will getfalsewithout doubts. The values are unequal each other.
What are these values? They are pointers to first characters of strings. If you want to compare the strings themselves pointed to by the pointers you have to use standard C functionstrcmpdeclared in header<string.h>.
Thus you should write
```
if( strcmp( arr[r2][1], t_plat ) == 0 && strcmp( arr[r2][2], t_ver ) == 0 )
```
|
I have 2d array filled with random numbers.
For example:
```
#define d 4
int main(void)
{
int a[d][d];
int primary[d], secondary[d];
size_t i, j;
srand(time(NULL)); /* fill array with random numbers */
for (i = 0; i < d; i++)
{for (j = 0; j < d; j++)
a[i][j] = rand() % 100;
}
```
How to change diagonals . For example :
```
1 0 0 0 2 2 0 0 0 1
0 3 0 4 0 0 4 0 3 0
0 0 5 0 0 to 0 0 5 0 0
0 6 0 7 0 0 7 0 6 0
8 0 0 0 9 9 0 0 0 8
```
Task is to print random matrix of d size then change diagonals placement using cycle and print it again.However i`m not getting how cycle should look like.
Appreciate any hints or examples.
|
Loop whilej < d / 2and then swap the values:
```
for (i = 0; i < d; i++) {
for (j = 0; j < d / 2; j++) {
int temp = a[i][j];
a[i][j] = a[i][d - j -1];
a[i][d - j -1] = temp;
}
}
```
|
Closed. This question needsdetails or clarity. It is not currently accepting answers.Want to improve this question?Add details and clarify the problem byediting this post.Closed6 years ago.Improve this question
To be more specific, the code is like this
```
main()
{
int a; int b;
func(&a,&b);
}
void func(int *x,int *y)
{
func1(...); // i need to pass x,y in func1
}
void func1(int ,int ) { ... }
```
The arguments x,y came from my main and i dont know how to pass them to func1, in order to modify them in the scope of this function
|
You simply pass them on, but in order for func1 to be able to modify and pass them back you must change func1 to accept pointers.
Your prototype for func1 must be changed to:
```
void func1(int* a, int* b);
```
Then:
```
void func(int *x,int *y) {
func1(x, y);
}
```
|
This question already has answers here:How to initialize all members of an array to the same value?(26 answers)Closed6 years ago.
I need to initialize a fixes size arrays quite often, like so:
```
for( uint16_t q=0; q<SIZE; q++ )
array[q]=value;
```
Array is defined asfloat array[SIZE];
Is there a nicer way of doing this, replacing with a macro or similar?
p.s.
Not allowed to usemem___calls.
|
C doesn't have built-in way to initialize the entire array to some non-zero value.
If you use GCC, it hasDesignated Initializersextension. You can use it like:
```
float widths[] = { [0 ... 99] = 3.14 };
```
This set all of the elements to3.14.
|
Just curious to know what is the difference between such constructions (fortext,data,rodata,bssetc) in linker script:
```
.data :
{
*(.data)
}
.data :
{
*(.data*)
}
.data :
{
*(.data.*)
}
```
In all cases we gatherdatasections from all object files, but the devil is in the detail.
Fast test showed that addresses inmapfile differ and in turn it influences the size of executable file.
I tried to find the information inlddocumentationbut found nothing (or just missed it).
I guess that it should be something very simple (so calledobvious).
Any ideas will be highly appreciated.
|
In any place where you may use a specific file or section name, you may also use a wildcard pattern.
It works like a regular pattern
*(.data)- .data sections,Example:.data*(.data*)- .data* section,Example:.dataTEST*(.data.*)- .data.* section,Example:.data.TEST
Find more info here
|
Basically I have to create a program in whichlais given a parameter, and then I have some specific commands that have to be used to sort them numbers in la into another array,lb.
I suppose my prototype should be something like:
```
int functioname(la) {
//something here
}
```
My question is how to use malloc to create thelbbig enough to fit all the numbers inla, I have tried to use something like:
```
lb = malloc(sizeof(la));
```
but it doesn't seem to work out.
Thank you!
|
I figured this out:
```
int pushswap(int *la) {
int *lb;
int cnt;
cnt = 0;
while(la[cnt])
cnt++;
lb = malloc(sizeof(int)*cnt + 1)
}
```
|
If I write something like this in a C99 header:
```
static inline void f()
{
static int x = 0;
// Do something with x
}
```
Is it guaranteed that each module including this header gets a separate instantiation off()and its own instantiation ofx?
|
Yes, by definition, that's whatstaticmeans. The fact that it's in a header is irrelevant. Conceptually, the C preprocessor createsonefile to compile per.cfile as if you had just (re)typed all the text in the header into the.cyourself.
|
```
#include<STDIO.H>
```
It is in upper case but the program (compiles and) runs without any error in C language, but C is case sensitive — how this is possible?
```
#include<STDIO.H>
#include<CONIO.H>
main()
{
printf("hello");
getch();
}
```
|
This works if you are using Windows or another operating system that ignores case on its file system. It doesn't work on Linux and other Unix flavours, because they do care about case (by default).
When you add an include statement like#include <any_file.h>, then the C-compiler will ask the operating system to open fileany_file.h.
If your operating system doesn't care about case, then it will open any file that matches the pattern. If it, for instance, finds a file namedaNy_fILe.H, it will open the file and present it to the C compiler.
The C-compiler will interpret the content of the file - this is the case-sensitive bit of the C language.
|
Basically I have to create a program in whichlais given a parameter, and then I have some specific commands that have to be used to sort them numbers in la into another array,lb.
I suppose my prototype should be something like:
```
int functioname(la) {
//something here
}
```
My question is how to use malloc to create thelbbig enough to fit all the numbers inla, I have tried to use something like:
```
lb = malloc(sizeof(la));
```
but it doesn't seem to work out.
Thank you!
|
I figured this out:
```
int pushswap(int *la) {
int *lb;
int cnt;
cnt = 0;
while(la[cnt])
cnt++;
lb = malloc(sizeof(int)*cnt + 1)
}
```
|
If I write something like this in a C99 header:
```
static inline void f()
{
static int x = 0;
// Do something with x
}
```
Is it guaranteed that each module including this header gets a separate instantiation off()and its own instantiation ofx?
|
Yes, by definition, that's whatstaticmeans. The fact that it's in a header is irrelevant. Conceptually, the C preprocessor createsonefile to compile per.cfile as if you had just (re)typed all the text in the header into the.cyourself.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.