question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
There are a few sources files in my project that are automatically generated by a tool. Unfortunately, these sources cause GCC to issues some warnings which is quite inconvenient. Is there a way to tell GCC to ignore warnings for these source files, without modifying the sources? They shouldn't be modified because, as... |
That is possible if you are building project through a makefile. You will just have to create different rules for those files. For example by creating another set of CFLAGS.
|
I am trying to learn pointers and I just encountered a situation I do not understand.
```
int main()
{
int num[3][2]={3,6,9,12,15,18};
printf("%d %d",*(num+1)[1],**(num+2));
}
```
As per what I have learnt the output should be :
```
12 15
```
but actually it is:
```
15 15
```
Why? Please clarify as to how th... |
In your data,
```
int num[3][2]={3,6,9,12,15,18};
```
equivalent to:
```
int num[3][2]={{3,6},{9,12},{15,18}};
```
i.e.
```
num[0][0] = 3
num[0][1] = 6
num[1][0] = 9
num[1][1] = 12
num[2][0] = 15
num[2][1] = 18
```
thus,
```
*(num+1)[1]
= *(*(num+1+1))
= num[2][0]
=15
```
and,
```
**(num+2))
= num[2][0]
=15
... |
Glibc provides the very handybacktrace()andbacktrace_symbols()functions, which can help getting the stack trace of the current function programmatically (see here).
Does the Windows API provide any similar functions?
|
Yes, take a look at the functionCaptureStackBackTrace(). UseSymFromAddr()and its counterparts to get meaningful symbol names.
|
Given an API like this :
write_data(uint32_t address,uint8_t *data)
how can I transmit a constant to my embedded device, like 0x001 ?
|
You create a variable and assign the constant to it. Then you pass a pointer to the variable.
|
Can someone please help me understand how to code lex and yacc file for a C program to parse goto and blocks(labels).
Here is some example I found on the net:
```
<statement> ::=
<variable> <inc> <semi>
| <variable> <assign> <null> <semi>
| <goto> <label> <semi>
```
But how to uniquely identify label. Can someone... |
<label>here really means a symbol - an identifier - which must correspond to a label definition somewhere else for the program to be correct.
|
This question already has answers here:What does void mean in C, C++, and C#?(15 answers)Closed8 years ago.
What is the value that is stored in void()? Basically it is used before a function which doesnot return anything. But does simply void holds any value?
|
Void is an incomplete type which, by definition, can't be an lvalue.
That means it can't get assigned a value.
So it also can't hold any value.
|
I read that GCC 4.9 has support for_Thread_local.
Hereis said:
ISO C11 thread-local storage (_Thread_local, similar to GNU C
__thread) is now supported.
However I installed on Fedora 21 GCC 4.9.1-11 but the include filethreads.his not present.
Any idea?
Does anyone know if there is a compiler with this support?... |
_Thread_localshould work fine, but it's not very useful, except as a way of making your code thread-safe for somebody else using it with threads, unless you have a way to make threads. The C11 threads API would be provided by libc, not the compiler, and glibc does not support it yet. You can of course use the POSIX t... |
I have made a Makefile for compiling my C programm but it's not building object when i change one of the headers.
My MakeFile:
```
CC=gcc
CFLAGS=-O3 -Wall
LDFLAGS=-I/usr/include/mysql -L/usr/lib/x86_64-linux-gnu -lmysqlclient
SOURCES=$(wildcard *.c)
OBJECTS=$(SOURCES:.c=.o)
EXECUTABLE=bin/beta_parser
all: $(EXECUTA... |
Although there are other more elegant tricks, in your case, I think something like
```
$(OBJECTS): types.h cstes.h headers.h mysql.h
%.o: %.c
$(CC) -o $@ -c $< $(CFLAGS)
```
should be sufficient.
|
I have the pid of a forked process. Now, from my c code (running on Linux), I have to check periodically whether this process is still running or terminated. I do not want to use blocking calls likewait()orwaitpid(). Need (preferably) a non-blocking system call which would just check whether this pid is still running ... |
Thewaitpid()function can take the option valueWNOHANGto not block. Seethe manual page, as always.
That said, I'm not sure that pids are guaranteed to not be recycled by the system, which would open this up to race conditions.
|
I have the above code but the output is not what I expected.
```
typedef struct
{
int a;
}node, *nodePtr;
nodePtr* createTest()
{
nodePtr *head = (nodePtr*)malloc(3 * sizeof(nodePtr));
node n1 =
{
3
};
node n2 =
{
4
};
node n3 =
{
5
};
head... |
```
head[0] = &n1;
head[1] = &n2;
head[2] = &n3;
```
n1,n2,n3are local variables. Using their address after the functioncreateTestexits is undefined behavior.
|
How can I get the title of web page with curl? I wish to pass http or https url and get title of that page. I figured out thatcurl_easy_perform(curl)prints the html to terminal but I can't figure out how I can parse the html.
|
libcurl is not a HTML parsing library, it's focus is on the transport, i.e. getting you the bits. You need to either interpret them yourself, or turn to other libraries.
In your case you need to look for the<title>element and extract that element's text.
It's a bit too large to paste here, butthis example from libcu... |
I have astructwhich contains an array ofints. I do not want to fix the size of the array as I don't know how many elements will go into it and do not want to waste memory.
An array of int pointers would be the same essentially.
I tried a pointer to an array of integers and a double pointer to no avail.
How could I ... |
An array of int pointers would be the same essentially.
No, you mean a pointer (int *):
```
int *arr = malloc(sizeof(*arr) * n);
```
If you don't knownbeforehand:
```
int n = 0, *arr = NULL;
while (condition) {
arr = realloc(arr, sizeof(*arr) * (n + 1));
n++;
}
```
|
Example
```
//This is my function
void myfunc (how does the definition look like?)
{
int counter = 0;
for (counter = 0; counter < 10; counter++)
{
*arr[counter] += 10;
}
int main(void)
{
char arr[100] = {'\0'};
myfunc (how does this look like?)
return 0;
}
```
I want to pass in something like a pointer so I can mod... |
When an array is passed to a function, a pointer to the first element is passed.
```
void myfunc(char *arr) {
int counter;
for (counter = 0; counter < 10; counter++) {
arr[counter] += 10;
}
}
```
|
I'm trying to take tokens in a format of "%i / %i%s" and split them into three variables.
```
char char1[20];
int int1;
int int2;
sscanf(token, "%[^/]/%d", char1, &int2);
printf("%s - %i ", char1, &int2);
```
It just segfaults. What am I doing wrong?
I've tried changing %d to %i, with no difference.
|
You shouldn't print address of int2 in your printf. This is working for me:
```
const char *token = "qwerasdf/10";
char char1[20];
int int2;
sscanf(token, "%[^/]/%d", char1, &int2);
printf("%s - %i ", char1, int2);
```
Output:
```
qwerasdf - 10
```
|
I allocated memory to an array (usingmalloc) but what if it needs more space, is it possible to expand the array later in the program? Or maybe create a new array and have the last element in the first array point to the new array?I know thatreallocwould be much easier to use but I am trying to do this only usingmallo... |
The general algorithm is
```
allocate array of 100
while more input
if no-room-in-array
allocate another array 100 bigger than the current array
copy values from current array into newly created array
free(current array)
current array = newly created array (the one you copied into)... |
I have the above code but the output is not what I expected.
```
typedef struct
{
int a;
}node, *nodePtr;
nodePtr* createTest()
{
nodePtr *head = (nodePtr*)malloc(3 * sizeof(nodePtr));
node n1 =
{
3
};
node n2 =
{
4
};
node n3 =
{
5
};
head... |
```
head[0] = &n1;
head[1] = &n2;
head[2] = &n3;
```
n1,n2,n3are local variables. Using their address after the functioncreateTestexits is undefined behavior.
|
How can I get the title of web page with curl? I wish to pass http or https url and get title of that page. I figured out thatcurl_easy_perform(curl)prints the html to terminal but I can't figure out how I can parse the html.
|
libcurl is not a HTML parsing library, it's focus is on the transport, i.e. getting you the bits. You need to either interpret them yourself, or turn to other libraries.
In your case you need to look for the<title>element and extract that element's text.
It's a bit too large to paste here, butthis example from libcu... |
I have astructwhich contains an array ofints. I do not want to fix the size of the array as I don't know how many elements will go into it and do not want to waste memory.
An array of int pointers would be the same essentially.
I tried a pointer to an array of integers and a double pointer to no avail.
How could I ... |
An array of int pointers would be the same essentially.
No, you mean a pointer (int *):
```
int *arr = malloc(sizeof(*arr) * n);
```
If you don't knownbeforehand:
```
int n = 0, *arr = NULL;
while (condition) {
arr = realloc(arr, sizeof(*arr) * (n + 1));
n++;
}
```
|
Example
```
//This is my function
void myfunc (how does the definition look like?)
{
int counter = 0;
for (counter = 0; counter < 10; counter++)
{
*arr[counter] += 10;
}
int main(void)
{
char arr[100] = {'\0'};
myfunc (how does this look like?)
return 0;
}
```
I want to pass in something like a pointer so I can mod... |
When an array is passed to a function, a pointer to the first element is passed.
```
void myfunc(char *arr) {
int counter;
for (counter = 0; counter < 10; counter++) {
arr[counter] += 10;
}
}
```
|
I'm trying to take tokens in a format of "%i / %i%s" and split them into three variables.
```
char char1[20];
int int1;
int int2;
sscanf(token, "%[^/]/%d", char1, &int2);
printf("%s - %i ", char1, &int2);
```
It just segfaults. What am I doing wrong?
I've tried changing %d to %i, with no difference.
|
You shouldn't print address of int2 in your printf. This is working for me:
```
const char *token = "qwerasdf/10";
char char1[20];
int int2;
sscanf(token, "%[^/]/%d", char1, &int2);
printf("%s - %i ", char1, int2);
```
Output:
```
qwerasdf - 10
```
|
I allocated memory to an array (usingmalloc) but what if it needs more space, is it possible to expand the array later in the program? Or maybe create a new array and have the last element in the first array point to the new array?I know thatreallocwould be much easier to use but I am trying to do this only usingmallo... |
The general algorithm is
```
allocate array of 100
while more input
if no-room-in-array
allocate another array 100 bigger than the current array
copy values from current array into newly created array
free(current array)
current array = newly created array (the one you copied into)... |
How can I get the title of web page with curl? I wish to pass http or https url and get title of that page. I figured out thatcurl_easy_perform(curl)prints the html to terminal but I can't figure out how I can parse the html.
|
libcurl is not a HTML parsing library, it's focus is on the transport, i.e. getting you the bits. You need to either interpret them yourself, or turn to other libraries.
In your case you need to look for the<title>element and extract that element's text.
It's a bit too large to paste here, butthis example from libcu... |
I have astructwhich contains an array ofints. I do not want to fix the size of the array as I don't know how many elements will go into it and do not want to waste memory.
An array of int pointers would be the same essentially.
I tried a pointer to an array of integers and a double pointer to no avail.
How could I ... |
An array of int pointers would be the same essentially.
No, you mean a pointer (int *):
```
int *arr = malloc(sizeof(*arr) * n);
```
If you don't knownbeforehand:
```
int n = 0, *arr = NULL;
while (condition) {
arr = realloc(arr, sizeof(*arr) * (n + 1));
n++;
}
```
|
Example
```
//This is my function
void myfunc (how does the definition look like?)
{
int counter = 0;
for (counter = 0; counter < 10; counter++)
{
*arr[counter] += 10;
}
int main(void)
{
char arr[100] = {'\0'};
myfunc (how does this look like?)
return 0;
}
```
I want to pass in something like a pointer so I can mod... |
When an array is passed to a function, a pointer to the first element is passed.
```
void myfunc(char *arr) {
int counter;
for (counter = 0; counter < 10; counter++) {
arr[counter] += 10;
}
}
```
|
I'm trying to take tokens in a format of "%i / %i%s" and split them into three variables.
```
char char1[20];
int int1;
int int2;
sscanf(token, "%[^/]/%d", char1, &int2);
printf("%s - %i ", char1, &int2);
```
It just segfaults. What am I doing wrong?
I've tried changing %d to %i, with no difference.
|
You shouldn't print address of int2 in your printf. This is working for me:
```
const char *token = "qwerasdf/10";
char char1[20];
int int2;
sscanf(token, "%[^/]/%d", char1, &int2);
printf("%s - %i ", char1, int2);
```
Output:
```
qwerasdf - 10
```
|
I allocated memory to an array (usingmalloc) but what if it needs more space, is it possible to expand the array later in the program? Or maybe create a new array and have the last element in the first array point to the new array?I know thatreallocwould be much easier to use but I am trying to do this only usingmallo... |
The general algorithm is
```
allocate array of 100
while more input
if no-room-in-array
allocate another array 100 bigger than the current array
copy values from current array into newly created array
free(current array)
current array = newly created array (the one you copied into)... |
I have a question aboutreturn0 in C:
```
void main()
{
int i = 0;
while(1)
{
switch(i)
{
case 1:
case 2:
case 3:
case 4:
i ++;
break;
case 5:
return 0;
}
}
}
```
will... |
It will return from the main method, which in this case, will exit the whole program.
|
This question already has an answer here:What default promotions of types are there in the variadic arguments list?(1 answer)Closed8 years ago.
I only found pretty unrelated questions due to the tons of results searching forprintf().
Why doesuint8_tnot specify its own format string but any other type does?
As far a... |
Because %u stands for "unsigned", it well may be uint64_t and is architecture dependent. According toman 3 printf, you may want to use length modifier to get sought behaviour, i.e. %hu (uint16_t) and %hhu (uint8_t).
|
Why doesn't this compile? I don't want to put2in the last pair of brackets. Is there another way to do it?
```
int ary[][] = {{2, 3}, {5, 7}, {11, 13}};
```
|
There is a way to do it without specifying the dimensions, using compound literals:
```
int* ary[] = {( int[] ){2, 3}, ( int[] ){5, 7}, ( int[] ){11, 13} };
```
And the usage stays the same!:
```
ary[2][1] = 55 ;
printf("%d %d\n" , ary[2][0] , ary[2][1] ) ;
```
Compound literals have the same scope and lifetime as... |
I have defined an integer in C as
```
#define FOO_VERSION 04042012
```
when I go to pass this to a function like so:
```
unsigned int version = FOO_VERSION;
bar(version);
```
the actual value passed is 1065994.
I verified this using GBD, printf-ing the variable version and by printf-ing the define:
'FOO_VERSION'
... |
04042012is an octal (base 8) integer constant because of the initial 0. Remove it to define a decimal (base 10) integer:
```
#define FOO_VERSION 4042012
```
|
I have been enjoying using Qt Creator for bare C development, however the IDE still seems to think that 'class' is a keyword. This creates some issues with autocompletion/intellisense, as struct members named 'class' are not listed.
I thought the answer would be in the 'c.xml' generic highlighter file in my home dire... |
Bugs already reported:https://bugreports.qt-project.org/browse/QTCREATORBUG-12817,https://bugreports.qt-project.org/browse/QTCREATORBUG-9125. Just comment there and get some developer attention and ask about workarounds(seems needs recompiling).
|
can anyone tell me what it the exact purpose of mtCOVERAGE_TEST_MARKER() macro in FreeRTOS sources? By default it expands to nothing.
It is obviously used forsomecoverage test, but I can't really think of a code that can be universally useful in all places where this macro is used.
|
They provide thorough code coverage analysis - so each time there is an if() without an else we can see in a more automated way if the code has taken the path where the if() evaluates to true and where the if() evaluates to false - rather than just one path. The coverage tests are not published, but the general codin... |
I have a question aboutreturn0 in C:
```
void main()
{
int i = 0;
while(1)
{
switch(i)
{
case 1:
case 2:
case 3:
case 4:
i ++;
break;
case 5:
return 0;
}
}
}
```
will... |
It will return from the main method, which in this case, will exit the whole program.
|
This question already has an answer here:What default promotions of types are there in the variadic arguments list?(1 answer)Closed8 years ago.
I only found pretty unrelated questions due to the tons of results searching forprintf().
Why doesuint8_tnot specify its own format string but any other type does?
As far a... |
Because %u stands for "unsigned", it well may be uint64_t and is architecture dependent. According toman 3 printf, you may want to use length modifier to get sought behaviour, i.e. %hu (uint16_t) and %hhu (uint8_t).
|
Why doesn't this compile? I don't want to put2in the last pair of brackets. Is there another way to do it?
```
int ary[][] = {{2, 3}, {5, 7}, {11, 13}};
```
|
There is a way to do it without specifying the dimensions, using compound literals:
```
int* ary[] = {( int[] ){2, 3}, ( int[] ){5, 7}, ( int[] ){11, 13} };
```
And the usage stays the same!:
```
ary[2][1] = 55 ;
printf("%d %d\n" , ary[2][0] , ary[2][1] ) ;
```
Compound literals have the same scope and lifetime as... |
I have defined an integer in C as
```
#define FOO_VERSION 04042012
```
when I go to pass this to a function like so:
```
unsigned int version = FOO_VERSION;
bar(version);
```
the actual value passed is 1065994.
I verified this using GBD, printf-ing the variable version and by printf-ing the define:
'FOO_VERSION'
... |
04042012is an octal (base 8) integer constant because of the initial 0. Remove it to define a decimal (base 10) integer:
```
#define FOO_VERSION 4042012
```
|
I have been enjoying using Qt Creator for bare C development, however the IDE still seems to think that 'class' is a keyword. This creates some issues with autocompletion/intellisense, as struct members named 'class' are not listed.
I thought the answer would be in the 'c.xml' generic highlighter file in my home dire... |
Bugs already reported:https://bugreports.qt-project.org/browse/QTCREATORBUG-12817,https://bugreports.qt-project.org/browse/QTCREATORBUG-9125. Just comment there and get some developer attention and ask about workarounds(seems needs recompiling).
|
can anyone tell me what it the exact purpose of mtCOVERAGE_TEST_MARKER() macro in FreeRTOS sources? By default it expands to nothing.
It is obviously used forsomecoverage test, but I can't really think of a code that can be universally useful in all places where this macro is used.
|
They provide thorough code coverage analysis - so each time there is an if() without an else we can see in a more automated way if the code has taken the path where the if() evaluates to true and where the if() evaluates to false - rather than just one path. The coverage tests are not published, but the general codin... |
I have defined an integer in C as
```
#define FOO_VERSION 04042012
```
when I go to pass this to a function like so:
```
unsigned int version = FOO_VERSION;
bar(version);
```
the actual value passed is 1065994.
I verified this using GBD, printf-ing the variable version and by printf-ing the define:
'FOO_VERSION'
... |
04042012is an octal (base 8) integer constant because of the initial 0. Remove it to define a decimal (base 10) integer:
```
#define FOO_VERSION 4042012
```
|
I have been enjoying using Qt Creator for bare C development, however the IDE still seems to think that 'class' is a keyword. This creates some issues with autocompletion/intellisense, as struct members named 'class' are not listed.
I thought the answer would be in the 'c.xml' generic highlighter file in my home dire... |
Bugs already reported:https://bugreports.qt-project.org/browse/QTCREATORBUG-12817,https://bugreports.qt-project.org/browse/QTCREATORBUG-9125. Just comment there and get some developer attention and ask about workarounds(seems needs recompiling).
|
can anyone tell me what it the exact purpose of mtCOVERAGE_TEST_MARKER() macro in FreeRTOS sources? By default it expands to nothing.
It is obviously used forsomecoverage test, but I can't really think of a code that can be universally useful in all places where this macro is used.
|
They provide thorough code coverage analysis - so each time there is an if() without an else we can see in a more automated way if the code has taken the path where the if() evaluates to true and where the if() evaluates to false - rather than just one path. The coverage tests are not published, but the general codin... |
We constantly run into issues where we are running different C images on different machines. Since our code is still in production, we keep generating binaries that folks use. Often lot of time is spent in debugging only to learn later that the binaries were incorrect.
I was wondering if there is some mechanism with ... |
The__DATE__and__TIME__macros are predefined by the compiler with the date and time that a C program is built. These are just string literals of the format"Mmm dd yyyy"and"hh:mm:ss"respectively, so should be easy to use with any logging or printing system. (These macros are defined in the C11 standard section 6.10.8.1)... |
If
```
char d[3];
d[0] ='p';
d[1] ='o';
d[2] ='\0';
```
how come
```
printf("%s\n",d[0]);
```
won't work properly.
But if I have
```
char n[2][4];
n[0][0]=’T’; n[0][1]=’o’; n[0][2]=’m’; n[0][3]=0;
n[1][0]=’S’; n[1][1]=’u’; n[1][2]=’e’; n[1][3]=0;
```
printf("%s %s\n", n[0],n[1]);
it will print t... |
Because
```
d[0] - is a character
```
And
```
n - is and array of and array of characters. I.e. an array of strings
```
|
This is my program :
```
#include<stdio.h>
int main()
{
int *n;
int var;
scanf("%d",n);
printf("%d",*n);
}
```
asscanfstores the value at specified address I am giving the address .Then I am trying to print value at address but its giving segfault.
|
You should allocate memory for pointers like this:
```
int* n = (int*)malloc(sizeof(int))
```
|
I have written the following code. It should swap the values of two variables ... but, as soon as I compile the code it shows swap.exe has stopped working...Why doesn't it work?
```
#include<cstdio>
#include<iostream>
using namespace std;
void swap(int *x, int *y)
{
int *temp;
*temp=*x;
*x=*y;
*y=*tem... |
Change to
```
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
```
If you want to swap twoints why do you use a pointer tointas temporary variable? Use the same type.
|
According to page 135 K&R (as well asthiswikipedia page), the sizeof operator can be used to compute the size of an object and returns the size in bytes as an unsigned integer of type size_t. Since the max value of an unsigned integer is 2^32, what would happen if I was to call sizeof on an object that had a larger si... |
I think you're reading it wrong.
"An unsigned integer" does not mean "the typeunsigned int". It can also, for instance, beunsigned long longwhich can be (much) larger. Also, of course, there's no requirement or specification that says thatunsigned intis limited to 32 bits.
|
I've some doubts about fgets. From what I know, it adds "\n" at the end of the string, and not "\0". So if I write this code:
```
fgets(buff,2,stdin);
printf("%s",buff);
```
So fgets reads two characters, I give as input "y", so buff should be "y\n". I'd expect printf to print y and add a line, while it prints "y" w... |
```
char * fgets ( char * str, int num, FILE * stream );
```
Reads characters from input stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.
A newline character makes fgets stop reading, but it is considered... |
A bit of a noob question.. I'm using Linux and apt-get installed libusb-1.0 as my API uses this to talk to my USB device. If I have created an object file of my .c file, does that mean that if I use it on another machine do they need to first apt-get installed libusb-1.o, or is it in the object file?
Thanks
|
If you statically link your library to make the executable, then the executable file will contain the requisite definition of the API, bundled with the executable.
|
I am working on a project in which If I could include a header file at runtime, it would save some programming effort. I google'd about it, but all in vain. My question is :Can we include header files in a C program at runtime ?If yes, how?If not, why?
|
In C the source files are only read compile-time, so the answer to your question isnot. Runtime there is only the executable binary, which has nothing to do with your source code headers.
|
Would a Tun/tap device avoid a netmap/pf_ring/dpdk installation ? If tun/tap allow to bypass kernel, isn't it the same thing ?
Or those codes bring so many optimizations that they overclass tun os bypass strategy ?
The final goal is to port tcp/ip from kernel to user space, FOR TESTING PURPOSES.
I don't quite under... |
no.
for userspace tcpip implementation see lwip or rumpkernel.
dpdk/pfring/netmap as you probably know are about getting packets to userspace as fast as possible.
tun/tap are virtual interface things. probably not what you're after.
|
I would like to read msr 0x19a (IA32_CLOCK_MODULATIOn) directly from C codeWITHroot privilege. However, I get the following segfault error.
```
a.out[27843] general protection ip:40053b sp:7fffefc38020 error:0 in a.out[400000+1000]
```
Does anyone know whether this way of calling rdmsr is a viable option?
Thanks in... |
This instruction must be executed at privilege level 0. In other words, you must be inside the kernel.
|
I have an integer variable x that I need to use to make two 2D arrays but I get an error of "cannot allocate an array of constant size 0". After doing some research I apparently need to use malloc but I have no idea how to apply it to my currently situation.
My two arrays I need:
```
int firMat[x][5];
int secMat[5][... |
```
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int x = 2;
int **firMat;//int firMat[x][5];
int **secMat;//secMat[5][x];
int i;
firMat = malloc(x * sizeof(int*));
for(i = 0; i< x; ++i)
firMat[i] = malloc(5 * sizeof(int));
secMat = malloc(5 * sizeof(int*));
for(i =... |
For example, I have a function:
```
void build()
{
struct Node *node;
node = (struct Node*)malloc(sizeof(struct Node));
}
```
Is it possible to access the pointer "node" from the outside?
|
C is a pretty straightforward and simple language. The only choice you have is to explicitlly put the node value somewhere, eiter:
global variableparameters on the functionreturn value
Options 2 and 3 are the most common ones. As an argument to the function:
```
void build(struct Node **node_param)
{
struct Node... |
I would like to read msr 0x19a (IA32_CLOCK_MODULATIOn) directly from C codeWITHroot privilege. However, I get the following segfault error.
```
a.out[27843] general protection ip:40053b sp:7fffefc38020 error:0 in a.out[400000+1000]
```
Does anyone know whether this way of calling rdmsr is a viable option?
Thanks in... |
This instruction must be executed at privilege level 0. In other words, you must be inside the kernel.
|
I have an integer variable x that I need to use to make two 2D arrays but I get an error of "cannot allocate an array of constant size 0". After doing some research I apparently need to use malloc but I have no idea how to apply it to my currently situation.
My two arrays I need:
```
int firMat[x][5];
int secMat[5][... |
```
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int x = 2;
int **firMat;//int firMat[x][5];
int **secMat;//secMat[5][x];
int i;
firMat = malloc(x * sizeof(int*));
for(i = 0; i< x; ++i)
firMat[i] = malloc(5 * sizeof(int));
secMat = malloc(5 * sizeof(int*));
for(i =... |
For example, I have a function:
```
void build()
{
struct Node *node;
node = (struct Node*)malloc(sizeof(struct Node));
}
```
Is it possible to access the pointer "node" from the outside?
|
C is a pretty straightforward and simple language. The only choice you have is to explicitlly put the node value somewhere, eiter:
global variableparameters on the functionreturn value
Options 2 and 3 are the most common ones. As an argument to the function:
```
void build(struct Node **node_param)
{
struct Node... |
```
char *word = malloc(sizeof(char) * (pos + 1));
```
is producing an SIGTRAP error.posis anint.
How do I know this is the line? Process of elimination with break points.
I searched and did not find any information on this function producing this error. What should I do?
|
There are many memory debuggers available on Windows (though I haven't tried them by myself):
Is there a good Valgrind substitute for Windows?
I'd recommend you to try Application Verifier from MS:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd371695(v=vs.85).aspx
It should be able to catch heap corrup... |
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.Closed8 years ago.Improve this question
i m trying to make s... |
```
first = ((char*) base) + i;
second = ((char*)base) + j;
```
|
If I change the condition (i < n -1) to (i < n) it glitches, and as it is now, all but the first position [0] gets sorted.
```
int sortIndexByDate(Match match[], int n)
{
int i, j, sum[n], swapped;
for (i = 0; i < n; i++)
sum[i] = match[i].d.year*10000 + match[i].d.month*100 + match[i].d.day;
do {... |
You are starting ati = 1in inner loop. Hence sum[0] is being ignored.
Change it to
```
for (i = 0; i < n-1; i++) {
```
|
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.Closed8 years ago.Improve this question
I'm having the issues of trying to separate 1s or 2d into int 1 and char 's' and then storing them as sepa... |
Usestrtol. For example,
```
char *endptr;
val = strtol(input_str, &endptr, 10;
next_char = *endptr;
```
As discussed in the manpage,http://man7.org/linux/man-pages/man3/strtol.3.html, the second parameter is a pointer to a char pointer and after the conversion, the char pointer points to the following character.
|
I have a console application with two threads. Both threads make output to the console.
This is confusing when one thread wait for an input, while the other thread is writing to the output.
Is there a possibility to split the console; so that thread 1 writes to the left area and thread 2 to the right area of the cons... |
Working on a console you can't do both simultaneously.
What you can do is redirect the output to a string or a stream while the first thread is waiting for input, and then output it on the console while processing the input.
|
I make a function, this make an operation and after this write on the variable, my question is:
this code is safe ?
There is a sample:
```
#include <stdlib.h>
void test(char **out){
char *f = (char *) malloc(10);
f = "123456";
*out = f;
return;
}
int main(void){
char *A = NULL;
test(&A);
... |
Look more closely intotest()definition:
```
void test(char **out){
char *f = (char *) malloc(10);
f = "123456";
*out = f;
return;
}
```
especially those two lines:
```
char *f = (char *) malloc(10);
f = "123456";
```
What this code is doing is simply replacing malloc-ed pointer with pointer to stri... |
i have created macro as following
```
#define log printf("(%s):(%d) ",__FUNCTION__, __LINE__);printf
```
And i am using it in main function for logging
```
log("Hello world\n");
```
it is resulting in run time error as "lldb".
Error in IDE is displaying "called object type 'int' is not a function or function poin... |
Try:
```
#define LOG( s ) printf( "(%s):(%d)%s\n", __FUNCTION__, __LINE__, s );
```
|
I see many programmers that include "utils.h" to their program.
Tried to search for what it is exactly and what is the proper use of utils.h, but all I found was different versions of the file.
So what is it exactly?
|
Many programmers define common functionalities inutils.cand declare them inutils.h. You could implement for example command line parsing methods in utils.h / utils.c.
But utils.h is no standard file to be included.
|
I'm trying to re-construct a 32-bit floating point value from an eeprom.
The 4 bytes in eeprom memory (0-4) are : B4 A2 91 4D
and the PC (VS Studio) reconstructs it correctly as 3.054199 * 10^8 (the floating point value I know should be there)
Now I'm moving this eeprom to be read from an 8-bit Arduino, so not s... |
The safest way, and due to compiler optimization also as fast as any other, is to usememcpy:
```
uint32_t dword = 0x4D91A2B4;
float f;
memcpy(&f, &dw, 4);
```
Demo:http://ideone.com/riDfFw
|
I see many programmers that include "utils.h" to their program.
Tried to search for what it is exactly and what is the proper use of utils.h, but all I found was different versions of the file.
So what is it exactly?
|
Many programmers define common functionalities inutils.cand declare them inutils.h. You could implement for example command line parsing methods in utils.h / utils.c.
But utils.h is no standard file to be included.
|
I'm trying to re-construct a 32-bit floating point value from an eeprom.
The 4 bytes in eeprom memory (0-4) are : B4 A2 91 4D
and the PC (VS Studio) reconstructs it correctly as 3.054199 * 10^8 (the floating point value I know should be there)
Now I'm moving this eeprom to be read from an 8-bit Arduino, so not s... |
The safest way, and due to compiler optimization also as fast as any other, is to usememcpy:
```
uint32_t dword = 0x4D91A2B4;
float f;
memcpy(&f, &dw, 4);
```
Demo:http://ideone.com/riDfFw
|
Let's say I have the following string:
```
char *my_string = "Stack";
```
As far as I knowchar *holds the memory address of the first character of the string"Stack". In the computer memory it might be represented as the following:
```
------------------------
| S | t | a | c | k | \0|
------------------------
^
... |
Thechar*indeed points only to the first character of your string, however functions likeprintf("%s")will simply start reading and continue until they find a 0-byte. String literals like your"Stack"example are zero-terminated by default, thusprintfwill know to print your string and stop after that.
|
I have creates a file in directory and want to read it in. I am using the following code to open and read a file in C-Language. But it creates a new file instead of reading the old file.
```
int main()
{
FILE * file;
file = fopen ("file", "r+");
//file reading code
fclose(file);
return(0);
}
```
|
you are using'r+'mode to open the file. It creates a new file if not already exist in the directory. see the following code for your help.
```
int main()
{
FILE * file;
file = fopen ("file", "r");
if(file !== NULL)
// to do file reading code
else
printf("error in reading file");
fclose(f... |
When I do
```
int k = 9;
printf("sizeof k: %zu \n", sizeof (&k));
```
I get the size as8. But when I do
```
printf("pointer to k: %p \n", &k);
```
I get0x7fff57e3ba24. I can see that this is 12 hex numbers which means (since 1 hex is 4 bits) that the pointer occupies 48 bits which is 6 bytes.
The question: Why do... |
Your logic is that if I write
```
printf("%d", 4);
```
and it prints 1 decimal digit, which can potentially be stored in 1 byte, thensizeof(int)must be 1 byte.
The number0x7fff57e3ba24is the same as0x00007fff57e3ba24. Just because the number happens to have fewer digits than the type can store doesn't mean it occup... |
What's the result of a function being called with a negative sign in the front? Is it to turn the return value into negative?
```
int someFunction(int newBoard[9], int aValue) {
for(i = 0; i < 9; ++i) {
if(newBoard[i] == 0) {
newBoard[i] = player;
int thisScore = -someFunction(ne... |
Yes that is correct, since someFunction returns an integer putting a '-' in front negates the result
```
e.g. int n = 1;
printf( "%d", -n );
...
-1
```
how this is used in your context is more difficult to guess since you do not provide much context in your question.
|
I am using linux to try and exec to run a different child process to parent process.
I can exec a child process to run the ps command fine.
```
int x = fork();
if (x == 0)
{
execl("/bin/ps","ps", NULL);
}
```
However as soon as I try to exec to a .exe file that I have created from my own c file like thisgcc... |
The problem is, that your desktop folder is at~/Desktop/. The tilde means yourhomefolder.
|
I've got ac programI"m using off github that intermittently crashes every few days and I think it might be down to "open_lockfile" - maybe the file cannot be opened etc.
How would I go about adding some error level checking on this open_lockfile statement?
```
#define LOCKFILE "/var/run/dht.lock"
int lockfd;
lockfd ... |
After looking at the code a bit more the open_filelock is a function within the c code.
|
Let's say I have the following string:
```
char *my_string = "Stack";
```
As far as I knowchar *holds the memory address of the first character of the string"Stack". In the computer memory it might be represented as the following:
```
------------------------
| S | t | a | c | k | \0|
------------------------
^
... |
Thechar*indeed points only to the first character of your string, however functions likeprintf("%s")will simply start reading and continue until they find a 0-byte. String literals like your"Stack"example are zero-terminated by default, thusprintfwill know to print your string and stop after that.
|
I have creates a file in directory and want to read it in. I am using the following code to open and read a file in C-Language. But it creates a new file instead of reading the old file.
```
int main()
{
FILE * file;
file = fopen ("file", "r+");
//file reading code
fclose(file);
return(0);
}
```
|
you are using'r+'mode to open the file. It creates a new file if not already exist in the directory. see the following code for your help.
```
int main()
{
FILE * file;
file = fopen ("file", "r");
if(file !== NULL)
// to do file reading code
else
printf("error in reading file");
fclose(f... |
When I do
```
int k = 9;
printf("sizeof k: %zu \n", sizeof (&k));
```
I get the size as8. But when I do
```
printf("pointer to k: %p \n", &k);
```
I get0x7fff57e3ba24. I can see that this is 12 hex numbers which means (since 1 hex is 4 bits) that the pointer occupies 48 bits which is 6 bytes.
The question: Why do... |
Your logic is that if I write
```
printf("%d", 4);
```
and it prints 1 decimal digit, which can potentially be stored in 1 byte, thensizeof(int)must be 1 byte.
The number0x7fff57e3ba24is the same as0x00007fff57e3ba24. Just because the number happens to have fewer digits than the type can store doesn't mean it occup... |
I recently bought a STM32 Value line discovery kit to work with STM32 devices. I'm working on a project now which requires a watchdog. It's called IWDG in STM32. But my problem is that I need an ISR when the watchdog is triggered.
Does anyone know how to implement this (or even have an example)?
|
Youdon'twant a watchdog, since the whole purpose of the watchdog is to force a reset if the software has hung.
What you're after sounds more like simply a high-priority regular timer interrupt to me.
Set it up so that you restart the timer (pushing the interrupt event generation forwards in time) at regular interval... |
I can't understand why my program only prints the first number in the array.
it seems it loops only once and then something breaks the loop. The output is 232.
```
#include <stdio.h>
int main( int argc, char* argv[]){
int sum_arr(int arr[]);
int arr[5]={232,44,3,4,5};
printf("%d\n",sum_arr(arr));
return 0;
}
s... |
```
sizeofarr = sizeof(arr) / sizeof(arr[0]);
```
This trick to calculate the size of an array doesn't work. Because in the function,arrdecays to a pointer, not an array.
To fix the problem, pass the size explicitly.
|
```
union {
__int64 bigint;
struct {
unsigned long low;
long high;
};
} offbytes;
```
I am not sure what the meaning of above code?
__int64, unsigned long, long all is 8 bytes.
|
unsigned longandlongare not always 8 bytes. Many compilers offer 4-byteslongintegers. I bet that this is the case with your example.
In this context, you can use the union like this:
```
offbytes a;
a.bigint = 0x0123456789abcdef;
printf("%x %x\n", a.high, a.low);
```
The result is:
```
1234567 89abcdef
```
Warni... |
I recently bought a STM32 Value line discovery kit to work with STM32 devices. I'm working on a project now which requires a watchdog. It's called IWDG in STM32. But my problem is that I need an ISR when the watchdog is triggered.
Does anyone know how to implement this (or even have an example)?
|
Youdon'twant a watchdog, since the whole purpose of the watchdog is to force a reset if the software has hung.
What you're after sounds more like simply a high-priority regular timer interrupt to me.
Set it up so that you restart the timer (pushing the interrupt event generation forwards in time) at regular interval... |
I can't understand why my program only prints the first number in the array.
it seems it loops only once and then something breaks the loop. The output is 232.
```
#include <stdio.h>
int main( int argc, char* argv[]){
int sum_arr(int arr[]);
int arr[5]={232,44,3,4,5};
printf("%d\n",sum_arr(arr));
return 0;
}
s... |
```
sizeofarr = sizeof(arr) / sizeof(arr[0]);
```
This trick to calculate the size of an array doesn't work. Because in the function,arrdecays to a pointer, not an array.
To fix the problem, pass the size explicitly.
|
```
union {
__int64 bigint;
struct {
unsigned long low;
long high;
};
} offbytes;
```
I am not sure what the meaning of above code?
__int64, unsigned long, long all is 8 bytes.
|
unsigned longandlongare not always 8 bytes. Many compilers offer 4-byteslongintegers. I bet that this is the case with your example.
In this context, you can use the union like this:
```
offbytes a;
a.bigint = 0x0123456789abcdef;
printf("%x %x\n", a.high, a.low);
```
The result is:
```
1234567 89abcdef
```
Warni... |
I want to reshape an array of length L to one of MxN, however rather than create new memory by copying the elements over in for loops I'd like to do some pointer casting to allow me to access the array with double subscripting (array[X][Y]) .
I've googled around for ages and couldn't find anything helpful.
Any help ... |
Pointer casting doesn't seem like a good idea here. But if the number of columns is known before run-time, one option I often encounter is to simply define a macro e.g.
```
#define arrayName(i,j) arrayName[((i)*N) + (j)]
```
Or
```
#define ELEMENT(arrayName, i,j) (arrayName)[((i)*N) + (j)]
```
if you want it to be... |
I recently bought a STM32 Value line discovery kit to work with STM32 devices. I'm working on a project now which requires a watchdog. It's called IWDG in STM32. But my problem is that I need an ISR when the watchdog is triggered.
Does anyone know how to implement this (or even have an example)?
|
Youdon'twant a watchdog, since the whole purpose of the watchdog is to force a reset if the software has hung.
What you're after sounds more like simply a high-priority regular timer interrupt to me.
Set it up so that you restart the timer (pushing the interrupt event generation forwards in time) at regular interval... |
I can't understand why my program only prints the first number in the array.
it seems it loops only once and then something breaks the loop. The output is 232.
```
#include <stdio.h>
int main( int argc, char* argv[]){
int sum_arr(int arr[]);
int arr[5]={232,44,3,4,5};
printf("%d\n",sum_arr(arr));
return 0;
}
s... |
```
sizeofarr = sizeof(arr) / sizeof(arr[0]);
```
This trick to calculate the size of an array doesn't work. Because in the function,arrdecays to a pointer, not an array.
To fix the problem, pass the size explicitly.
|
```
union {
__int64 bigint;
struct {
unsigned long low;
long high;
};
} offbytes;
```
I am not sure what the meaning of above code?
__int64, unsigned long, long all is 8 bytes.
|
unsigned longandlongare not always 8 bytes. Many compilers offer 4-byteslongintegers. I bet that this is the case with your example.
In this context, you can use the union like this:
```
offbytes a;
a.bigint = 0x0123456789abcdef;
printf("%x %x\n", a.high, a.low);
```
The result is:
```
1234567 89abcdef
```
Warni... |
I want to reshape an array of length L to one of MxN, however rather than create new memory by copying the elements over in for loops I'd like to do some pointer casting to allow me to access the array with double subscripting (array[X][Y]) .
I've googled around for ages and couldn't find anything helpful.
Any help ... |
Pointer casting doesn't seem like a good idea here. But if the number of columns is known before run-time, one option I often encounter is to simply define a macro e.g.
```
#define arrayName(i,j) arrayName[((i)*N) + (j)]
```
Or
```
#define ELEMENT(arrayName, i,j) (arrayName)[((i)*N) + (j)]
```
if you want it to be... |
I used a online compiler to compile the following code, and it throws an error that says: " â null undeclared (first use in this function)" I don't quite understand where the problem lies, as I thought we don't need to declare null.
```
int main(int argc, char *argv[]){
FILE *f;
f=fopen(argv[1],"r");
char ... |
The check should be againstNULLnot null.
```
while (fgets(string,17,f)!=NULL )
```
|
I have a C project that uses a Makefile to compile so, basically I tell Xcode to rely on an external build tool (make).
Since I updated from Xcode 5 to Xcode 6, I am not able to Run that project (build still works). Each time I try to run the execute I get the following error message :
My Mac runs OS X 10.9.5, which... |
Finally I just deleted and recreated the target and that solved the issue...
|
How do I write nothing inifpart if the condition is true?
For example:
```
if(true)
// I want to keep this space blank or want compiler to do nothing here
else
break;
```
How do I do this?
|
Typically, this is written by negating the condition:
```
if (not true)
break;
```
|
By now, I found only this way: get a pointer to the global variable via a function.
LLVM:
```
@a = global i8 0
define i8* @ggvp_a () {
ret i8* @a
}
```
C:
```
char* ggvp_a (void);
```
usage:
```
char* gvp_a = ggvp_a ();
*gvp_a = 8;
return *gvp_a;
```
(“ggvp” — “get global variable pointer”)
Is there a more... |
It's an external declaration like any other - just add
```
extern signed char a;
```
to your.cfile.
|
I'm having a hard time understanding my issue:
```
uint8_t nal_type=6;
for(i=7;i!=0;i--){
printf("%d",(nal_type>>i)&0x01U);}
printf("\n");
```
I would expect the following code to display the binary value from MSB to LSB. But it displays the following:
```
0000011
```
Can someone enlighten me ?
|
It's just a simple mistake in your loop, so you're not seeing the LS bit (bit 0) - make it:
```
for (i = 7; i >= 0; i--)
{ ^^^^^^
printf("%d", (nal_type >> i) & 0x01U);
}
```
This will then give the output as:
```
00000110
```
which I think is what you are looking for (MSB to LSB).
|
I have a socket where I set a timeout forrecv().
I have two steps forrecv(), first I check content of received data if complete usingMSG_PEEK | MSG_DONTWAIT.
```
recvTimeout.tv_sec = mRecvTimeoutSecs;
recvTimeout.tv_usec = mRecvTimeoutUSecs;
sendTimeout.tv_sec = mSendTimeoutSecs;
sendTimeout.tv_usec = mSendTimeoutUS... |
No, the socket will not timeout, asMSG_DONTWAITwill causerecv()to return immediately. Note that if you set like 1 msec timeout, then it might timeout - that would depend on the implementation (on which OS your code runs on).
|
How can I write three different matrices of different sizes say A, B and C using C?
The doubt being that once a particular row is printed the cursor is in the bottom most position, now how do we bring it back up?
|
You don't. you plan in advanced the rows and then print each row (one you go down - you can't go up....)
If you can't handle the logic - use a 2d array to store everything and then print it.
|
This question already has answers here:Removing trailing newline character from fgets() input(15 answers)Closed8 years ago.
```
while (fgets(line, LINELEN, inputFile)){
printf("%s$", line)
}
```
I am trying to read a file and print it out to the console as a CAT command. In this case I wanted to put a dollar s... |
fgetsincludes the'\n'at the end of the line.
Use something like:
```
char line[hopefullybigenough];
while (fgets(line, sizeof(line), inputFile)) {
size_t len = strlen(line);
if (line[len - 1] == '\n') line[len - 1] = '\0';
printf("%s$\n", line);
}
```
|
Closed.This question does not meetStack Overflow guidelines. It is not currently accepting answers.This question does not appear to be about programming within the scope defined in thehelp center.Closed8 years ago.Improve this question
How to find coefficient of
```
x^m (m<=n)
```
in the polynomial of type
```
(a1... |
```
(a1+b1x)(a2+b2x)...(an+bnx)=b1*b2*...*bn*(a1/b1+x)*(a2/b2+x)...(a/bn+x)
```
Right part is polynomial with roots (-a1/b1,-a2/b2...-an/bn)
There is O(N^2) algorithm to find coefficients of this polynomial, implementedhere
(Don't forget to multiply coefficients by product of b[i])
|
So, i have the following code:
```
#include <stdio.h>
int main() {
FILE* f = fopen("test.txt", "r");
FILE* p = fopen("test2.txt", "w+");
double i;
char j;
while (!feof(f)){
fscanf(f, " %c", &j);
if ((j == '(')||(j == ')'))
fprintf(p, "%c ", j);
else {
ungetc(j,f);
fscanf(f, "%lf ", &i);
... |
You shouldn't check forfeof()like that. Instead, simply check the result offscanf():
```
while (fscanf(f, " %c", &j) == 1) {
```
|
I am having trouble storing the strings correctly in this bit of code. I am excluding any special characters using isalnum(). The issue I am trying to overcome is that this method is also storing empty strings as well. I'm trying to find a way to iterate over special characters without storing them into a string.
```... |
```
if(i!=0)return stringStore(str,i);
```
also
```
if(i!=0)return stringStore(str,i); else return NULL;
```
– BLUEPIXY
|
Recently, I've been studying buffer overflows as an undergraduate student in Computer Engineering. Simply out of interest, I began researching and studying buffer overflows, but have gotten stuck when attempting to implement them in my own C programs on my computer, compiled with GCC 4.9.1 (in Debian Jessie).
I've he... |
Use-zexecstack -fno-stack-protectorto disable stack frame protection and non-executable stack withgcc.
On your Linux system, you also have to disable address randomization (ASLR) using:
```
echo 0 > /proc/sys/kernel/randomize_va_space
```
|
I'm trying to create a function that will print
```
1
2 1
3 2 1
4 3 2 1
```
etc, in C, up to 20. I can get it to print
```
1
1 2
1 2 3
1 2 3 4
```
just fine.
Help?
This is what I have so far.
```
int i, j;
for(i = 1; i<=20; i++) {
for(j=1; j<=i; j++) {
printf("%3d", j);
}
printf("\n");
}
```
|
You can simply reverse your second loop to go from the higher number to the lower number like such:
```
int i, j;
for(i = 1; i<=20; i++) {
for(j=i; j>0; j--) {
printf("%3d", j);
}
printf("\n");
}
```
This will start with printing the largest number and end with a one.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.