question stringlengths 25 894 | answer stringlengths 4 863 |
|---|---|
As the title said I was interested in the best way to convert a binary string to a hexadecimal string in C. The binary string is 4 bits at most so converting into a single hexadecimal char would be best.
Thanks for any help, I'm not sure if there's something built in to make this easier so don't have my own attempt t... |
You can usestrtolto convert the binary string to an integer, and thensprintfto convert the integer to a hex string:
```
char* binaryString = "1101";
// convert binary string to integer
int value = (int)strtol(binaryString, NULL, 2);
// convert integer to hex string
char hexString[12]; // long enough for any 32-bit ... |
I've to check one byte in 200 tables.
I don't want to write 200 line to check it.
Do you have any tips to do it with a for loop?
My example of code :
```
#include <stdio.h>
#include "CUnit/Basic.h"
#include "CUnit/Console.h"
#include "CUnit/Automated.h"
#include "CUnit/CUCurses.h"
#include "CUnit/TestDB.h"
void _... |
If you have n independant arrays, you could try to build an array of pointers:
```
char *my_tab[] = { my_tab_0, my_tab_1, m__tab_2, ... my_tab_n };
```
you can they simply do:
```
void _testu(){
int i;
for(i=0; i<=n; i++) {
CU_ASSERT_EQUAL(55, my_tab[i][5]);
}
}
```
It mainly make sense if you ... |
I want to know how a node* variable NODE can be assigned to the data inside the structure?
```
struct node
{
int info;
struct node *link;
};
typedef struct node* NODE;
//IN SOME OTHER FUNCTION
NODE temp,first;
temp = first;
first = first->link; // I WANT HELP WITH THIS LINE.
```
|
In a linked list you have a node with some information. In every node you have the address of the next node.
```
struct node
{
int info; //Information or data which is stored at every node
struct node *link; // Address of next node
};
```
first = first->link; // I WANT HELP WITH THIS LINE.
If you'... |
Is it possible to display progress on one line instead of having the for-loop printing out a bunch of lines for every action?
Like, for example. Instead of this:
```
Progress: 0%
Progress: 15%
Progress: 50%
Progress: 100%
```
It does all that in one line (while showing progress, of course):
```
Progress: 100%
```
... |
Use
```
printf ("\r progress =%d", progress)
```
|
I encountered this in a C program:
```
char str[100];
scanf(" %[^\n]", str);
```
Please explain how it works and why?
|
Thisscanfformat string consists of two parts:
a space character, which skips space characters (' ','\t','\n', etcetera) in the input, andthe%[^\n]conversion specification, which matches a string of all characters not equal to thenew linecharacter ('\n') and stores it (plus a terminating'\0'character) instr.
Note how... |
I want to know how a node* variable NODE can be assigned to the data inside the structure?
```
struct node
{
int info;
struct node *link;
};
typedef struct node* NODE;
//IN SOME OTHER FUNCTION
NODE temp,first;
temp = first;
first = first->link; // I WANT HELP WITH THIS LINE.
```
|
In a linked list you have a node with some information. In every node you have the address of the next node.
```
struct node
{
int info; //Information or data which is stored at every node
struct node *link; // Address of next node
};
```
first = first->link; // I WANT HELP WITH THIS LINE.
If you'... |
Is it possible to display progress on one line instead of having the for-loop printing out a bunch of lines for every action?
Like, for example. Instead of this:
```
Progress: 0%
Progress: 15%
Progress: 50%
Progress: 100%
```
It does all that in one line (while showing progress, of course):
```
Progress: 100%
```
... |
Use
```
printf ("\r progress =%d", progress)
```
|
I encountered this in a C program:
```
char str[100];
scanf(" %[^\n]", str);
```
Please explain how it works and why?
|
Thisscanfformat string consists of two parts:
a space character, which skips space characters (' ','\t','\n', etcetera) in the input, andthe%[^\n]conversion specification, which matches a string of all characters not equal to thenew linecharacter ('\n') and stores it (plus a terminating'\0'character) instr.
Note how... |
My program asks the user to input an integer and adds the sum of the digits.
```
#include <stdio.h>
int main (void)
{
int inputNum, sum;
// Gets the inputNum
printf("Type in a positive integer, and this program\nwill calculate the sums of the digits: ");
scanf("%i", &inputNum);
do
{
sum += (inputNu... |
You never initializedsum; it may well be starting with value 1,000,000
Just do:
```
int inputNum, sum = 0;
```
|
I've got a program to catch any terminating signals. Currently all it does is catchCtrl + C. I want to be able to catchCtrl + ZandCtrl + \in addition toCtrl + C. Here's part of my code.
```
if (signal(SIGINT, SIG_IGN) == SIG_ERR)
fprintf(stderr,"Error: Can't catch SIGINT\n");
if (signal(SIGTERM, SIG_IGN) == SIG_... |
Ctrl+Zraises SIGTSTP.Ctrl+\raises SIGQUIT.
I don't know of any key combination that raises SIGTERM, but of course you can send it usingkill -TERM <pid>replacing<pid>with the process ID. (Or justkill <pid>; SIGTERM is the default signal forkill)
Note that you can't catch SIGSTOP nor SIGKILL.
|
I want to use interrupt handlers
```
void EXTI3_IRQHandler(void)
{
//body
}
```
but when I build the project, I get the following error:
SymbolEXTI3_IRQHandlermultiply defined (by stm32f10x_it.o and
main.o)
I have included library stm32f10x_exti.h
|
Handlervoid EXTI3_IRQHandler(void)already defined in filestm32f10x_it.c.
You can replace code of your handler frommain.cto this special file or comment blank handler instm32f10x_it.c.
|
```
#include<stdio.h>
#include<conio.h>
void main()
{
int *p=NULL;
*p=30;
printf("%d %p", *p,p); //output:- 30 0000
}
```
p should be pointing to address 0 and I think there should be null assignment error. But how *p is giving output as 30? Is 30 stored in location 0000? According to me 0th address sh... |
[..] I think there should be null assignment error.
C staandard doesn't provide any such guarantees.
Dereferencing a null pointer isundefined behaviour. So, there's no point in reasoning about why it prints 30.
Btw, you should cast the pointer argument tovoid*to print it:
```
printf("%d %p", *p, (void*)p);
```
|
I have a C program and a bash script that need exclusive access to a file. I've seen thatyou can use mkdir with bash, but does this mix well with C? Is it safe to just test the presence of a directory, create and then delete it?
What I'm actually doing: a C program keeps rewriting a file with new data that is then re... |
The whole point of semaphores is atomicity, and if you check for directory presence using your own code, you will lose that property. What you should do it usemkdirfunction and check forEEXISTerror code once it returns:
```
char * lockdir="/tmp/myscript.lock";
int retval=mkdir(lockdir, S_IRWXU);
if(retval == 0) print... |
I have this piece of C code
```
#include <stdio.h>
int main(){
int i , j , m , A[5]={0,1,15,25,20};
i = ++A[1];
printf("%d:\n",i);
j = A[1]++;
printf("%d:\n",j);
m = A[i++];
printf("%d:\n",m);
printf("%d %d %d",i,j,m);
return 0;
}
```
and It... |
The line
```
m = A[i++];
```
will increment the variable i in-place after it gets the cooresponding value from the array A.
|
I have the following code:
```
#include <stdio.h>
float a; //Initialize variables
char b;
int c;
char d;
int main(void)
{
printf("Enter float: ");
scanf("%4.2f", &a);
printf("%4.2f", a);
//printf("Enter character:\n");
//printf("Enter 4-digit integer: \n");
//printf("Enter cha... |
scanf("%f",&a)does not take format specifier.
As mentioned in comments Visual Studio treat this warning as error.
So either use
```
scanf_s("%f",&a);
```
or go into settings and disable this warning as mentioned in this postWhy does Visual Studio 2013 error on C4996?
|
What would this translate to (in a more verbose way)?
```
local.sin_addr.s_addr = (!ip_address) ? INADDR_ANY:inet_addr(ip_address);
```
Trying to understand Ternary operators and I can't quite get it.
|
A ternary is similar to anifstatement, but it can be used where an expression is required. So it's equivalent to:
```
if (!ip_address) {
local.sin_addr.s_addr = INADDR_ANY;
} else {
local.sin_addr.s_addr = inet_addr(ip_address);
}
```
|
I want to get char array size but I cant do that
let see
```
#define MAX 64
char value[MAX]
value = "hi" //or something initialization
sizeof("hi") //result = 3
sizeof(value) // result = 64
```
I want to getsizeof("hi") == sizeof(value)How cant I do?
|
In the snippet that you've included, you're actually setting the size ofvalueto 64. As a resultsizeof(value)will return 64 *sizeof(char).
This is correct, regardless of what you're putting into the arrayvalue.
Perhaps what you're trying to do is to get the array to be automatically sized at compile time? e.g.
```
ch... |
I looked at thisSO postwith no help.
```
int main()
{
int a[][] = {{1,2},{3,4}};
}
```
Error
```
$ gcc a.c
a.c:6:8: error: array has incomplete element type 'int []'
int a[][] = {{1,2},{3,4}};
^
1 error generated.
```
Why isa[][]inco... |
Only one index can autosize. Otherwise you could have any pair of factors in the size. Soa[][2]works, buta[][]does not, because it can't guess the size of the array of arrays.
|
I have 2 structs of the same size, layout and alignment, but of different types. I would like to copy one onto the other.
```
struct one s1;
struct two s2;
...
s1 = (struct one)s2; // error: conversion to non-scalar type requested
s1 = *((struct one*)&s2); // fine?
```
Is the 2nd method safe & portable?
Bonus: ... |
The second method is undefined behaviour due to violating the strict aliasing rule. Even thoughstruct oneandstruct twohave the same layout, it is not permitted to use an lvalue of typestruct oneto access an object of typestruct twoor vice versa.
In general, accessing an object via an expression of a different type is... |
I am working with multi processes and signals and I just found out yesterday that printf is not a re-entrant function so there is a risk by using it with signal handlers. Is there anything I can do about it? Is there any re-entrant variation of printf or any re-entrant syscall that could replace printf?
Thanks!
|
Signal handlers are highly tricky in general. So highly tricky, that usually the only safe operation to do within them is to set a flag "signal was received" and then let the main loop (or in a multi threaded application a special signal handling thread) of the program do the actual signal handling.
|
I want to assign a value to mychar *like that:
```
char *text;
struct node *ptr = head;
//start from the beginning
while(ptr != NULL)
{
text = ptr->key + ";" + ptr->data + ";\n";
ptr = ptr->next;
fprinft(f, text);
}
```
The key value is achar[]and the data value anint.
I get the following error:
... |
As the concatenation ofptr->key,";",ptr->data,";\n"does not need to exist after the loop, just print it to the file.@user3386109
```
// Not needed
// char *text;
struct node *ptr = head;
while(ptr != NULL) {
// v--v----- printf specifiers for a pointer to a string and int
fprinft(f, "%s;%d;\n", ptr... |
I'm trying to count the syscalls in my Go program on OS X Yosemite. I've tried usingdtrussanddtrace, but both cause my program to crash with the following error, followed by a stack trace:
```
fatal error: runtime: bsdthread_register error
```
The two commands I've used are:
sudo dtruss "./my_program my_arg"sudo dt... |
If you want to use dtrace on macOS, you will need to use the external linker to build your program
```
-ldflags -linkmode=external
```
|
I want to do an evented read on Serial port which will run only when the data is available.
I have triedsigactionbut it causes problem when making a highly threaded application, alsosleepfunction seem to work incorrectly according to many forums.
So I am looking for a similar way as in windowsWaitCommEventthat is us... |
The canonical equivalents for linux systems is to usepoll()orselect().
Workings are different of course.
|
What does the 'Rebuild all' button or the 'Build' in IDE's like DEV C++ do actually?I never needed it but I've seen people using it.This is different from 'compile'(compiling is building in code blocks but not in DEV c++).
|
The first time you compile, you need to compile every C file. On subsequent compiles, you only need to compile the C files that have changed.
The project can keep track of what had been modified and what needs to be recompiled and what doesn't.
So Build can be faster, as it won't recompile everything, only the sourc... |
Is it possible to define a macroINPUT_ARR, so thatint a[4]; void (INPUT_ARR(int, a, 4)){}equals tovoid (int a0, int a1, int a2, int a3){}
|
Here's one way:
```
#define INPUT_ARR(type, name, count) IARR ## count (type, name)
#define IARR0(type, name)
#define IARR1(type, name) type name##0
#define IARR2(type, name) IARR1(type, name), type name##1
#define IARR3(type, name) IARR2(type, name), type name##2
#define IARR4(type, name) IARR3(type, name), type na... |
I have 2 structs of the same size, layout and alignment, but of different types. I would like to copy one onto the other.
```
struct one s1;
struct two s2;
...
s1 = (struct one)s2; // error: conversion to non-scalar type requested
s1 = *((struct one*)&s2); // fine?
```
Is the 2nd method safe & portable?
Bonus: ... |
The second method is undefined behaviour due to violating the strict aliasing rule. Even thoughstruct oneandstruct twohave the same layout, it is not permitted to use an lvalue of typestruct oneto access an object of typestruct twoor vice versa.
In general, accessing an object via an expression of a different type is... |
I am working with multi processes and signals and I just found out yesterday that printf is not a re-entrant function so there is a risk by using it with signal handlers. Is there anything I can do about it? Is there any re-entrant variation of printf or any re-entrant syscall that could replace printf?
Thanks!
|
Signal handlers are highly tricky in general. So highly tricky, that usually the only safe operation to do within them is to set a flag "signal was received" and then let the main loop (or in a multi threaded application a special signal handling thread) of the program do the actual signal handling.
|
I want to assign a value to mychar *like that:
```
char *text;
struct node *ptr = head;
//start from the beginning
while(ptr != NULL)
{
text = ptr->key + ";" + ptr->data + ";\n";
ptr = ptr->next;
fprinft(f, text);
}
```
The key value is achar[]and the data value anint.
I get the following error:
... |
As the concatenation ofptr->key,";",ptr->data,";\n"does not need to exist after the loop, just print it to the file.@user3386109
```
// Not needed
// char *text;
struct node *ptr = head;
while(ptr != NULL) {
// v--v----- printf specifiers for a pointer to a string and int
fprinft(f, "%s;%d;\n", ptr... |
I'm trying to count the syscalls in my Go program on OS X Yosemite. I've tried usingdtrussanddtrace, but both cause my program to crash with the following error, followed by a stack trace:
```
fatal error: runtime: bsdthread_register error
```
The two commands I've used are:
sudo dtruss "./my_program my_arg"sudo dt... |
If you want to use dtrace on macOS, you will need to use the external linker to build your program
```
-ldflags -linkmode=external
```
|
I want to do an evented read on Serial port which will run only when the data is available.
I have triedsigactionbut it causes problem when making a highly threaded application, alsosleepfunction seem to work incorrectly according to many forums.
So I am looking for a similar way as in windowsWaitCommEventthat is us... |
The canonical equivalents for linux systems is to usepoll()orselect().
Workings are different of course.
|
There are a ton of posts explaining why explicitly doingfoo(void)is better thanfoo()because it specifies that there are no function arguments instead of an unknown amount.
However, I cannot seem to find if it's best practice to put void in both the header file declarationandthe source file definition such as:
foo.h
... |
Old-style function declarations and definitions with empty parentheses are an obsolescent feature (N15706.11.6, 6.11.7). There are hardly any good reasons to use them.
Use(void)consistently, not().
|
Strings(character arrays) can be modified in C but string literals can't be modified. But why do string functions like strlen(const char *str) have a pointer to a constant characters?
|
Because they do not modify (and do not need to modify) their argument strings. That's what thatconstmeans.
Ifstrlen's argument were declared aschar *(noconst), you wouldn't be able to usestrlento determine the length of a constant string. For example
```
size_t my_own_strlen(char *str) { /* whatever */ }
const char... |
```
hashset *newset= new_hashset;
char *info="1234";
put_hashset (newset,info);
```
I took the help fromhere. I have inserted values in the hashset but I am not being able to print the values.
|
it's a standard hashtable structure. A size, plus an array of linked lists. So you ned to iterate over the array, then over the lists (mosts of the lists will be short and some will be empty). The data is in no particular order.
```
void getdata(hashset *hash)
{
int i;
hashnode *ptr;
for(i=0;i<hash->size;i+... |
That's my code -
```
main()
{
double x;
double y = pow(((1/3 + sin(x/2))(pow(x, 3) + 3)), 1/3);
printf("%f", y);
return 0;
}
```
I get an error indouble y = pow((1/3 + sin(x/2))(pow(x, 3) + 3), 1/3);, it says that called object is not a function or function pointer. I don't get it though -(1/3 + s... |
If you want to multiply, you need to use the*operator. You can't put parenthesized expressions adjacent to each other to denote multiplication.
```
(1/3 + sin(x/2))*(pow(x, 3) + 3)
```
|
In the below code,
```
#include<stdio.h>
int main(){
char string[] = {1, 2, 3};
char* my_pointer = string;
printf("%c", *my_pointer);
}
```
Am expecting the ASCII character'1'to be displayed on screen.
ASCII character'1'is49with binary representation as00110001
|
You need to give it characters when initializing:
```
char string[] = {'1', '2', '3', '\0'};
```
or you can initialize using a string
```
char string[] = "123";
```
When you use numbers like
```
char string[] = {1, 2, 3};
```
it will print the ASCII character corresponding to the number 1 (which is most likely n... |
I wrote the following c program:
```
int main()
{
char a[1];
char b[6]="hello\0";
int c, i;
for(i = 0; (c = getchar()) != EOF; i++)
a[i] = c;
for(i = 0; i < 5; i++)
printf("%c", b[i]);
}
```
Why when I give "bye" in input the program print "helby"?
I thought 'b' s... |
You assume thatais immediately followed bybin memory. That is not necessarily the case.
Reading/writing past the end of an array isundefined behavior, so compilers are free to arrange local variables in any order they choose.
On my particular machine, ifbis declared beforea, thenaappears just beforebin memory and I... |
i try this code to get duration of a media file:
```
AVFormatContext* pFormatCtx = NULL;
avformat_open_input(&pFormatCtx, filename.c_str(), NULL, NULL);
if (pFormatCtx != 0) {
avformat_find_stream_info(pFormatCtx, NULL);
int64_t media_duration = pFormatCtx->duration;
duration = media_duration/AV_TIME_BA... |
Becauseavformat_close_inputwill free theAVFormatContextafter it close it. That is why you should sendpFormatCtxby pointer.
So you don't need to callavformat_free_contextas it is already called byavformat_close_inputand no need to worry about memory leaks.
See the documentation foravformat_close_inputfor reference.
|
If "Allow windows manager to decorate window" is on.
What is the function name in the wine source that knows a user click this X button and send the WM_CLOSE to the app?
Thank you
|
The window manager sends ClientMessage with type WM_PROTOCOLS and the protocol value WM_DELETE_WINDOW. This is handled in dlls/winex11.drv/event.c: X11DRV_ClientMessage() -> handle_wm_protocols().
|
What's the difference between the following two character arrays: one with a null character and one without a null character?
```
char name1[] = {'j','o','h','n'};
char name2[] = {'j','o','h','n','\0'};
```
If there is a difference betweenname1andname2how doesstrlenwork onname1since it has no null character?
What w... |
how does strlen work on name1 since it has no null character.
It doesn't. This would invoke undefined behaviour.
I expected it to be 0 but got 1
Your code snippet tries to accessname1[5]. Given thatnameis achararray of size 4, you are accessing memory that has nothing to do with that array. Possibly at the time of ... |
What's the difference between the following two character arrays: one with a null character and one without a null character?
```
char name1[] = {'j','o','h','n'};
char name2[] = {'j','o','h','n','\0'};
```
If there is a difference betweenname1andname2how doesstrlenwork onname1since it has no null character?
What w... |
how does strlen work on name1 since it has no null character.
It doesn't. This would invoke undefined behaviour.
I expected it to be 0 but got 1
Your code snippet tries to accessname1[5]. Given thatnameis achararray of size 4, you are accessing memory that has nothing to do with that array. Possibly at the time of ... |
While running a sample code from the internet, I am stuck at 'glutTimerfunc'. I cannot figure out what is this error.
|
glutTimerFunctakes a pointer to a function that must have a signature of
```
void (*func)(int value)
```
YourframeTimerCallbackfunction doesn't take an integer parameter. Hence the error.
Refer tohttps://www.opengl.org/resources/libraries/glut/spec3/node64.html
|
I have:
```
char M[20] = "abcdabcdabcdabcd";
```
I can either print it as a string or as characters:
```
printf("%s\n", M); //print as string
for(i = 0;str[i] != '\0';i++) //print as characters
{
printf("%c",str[i]);
}
```
I want to read a string of 7 characters and store it in M such that afterwa... |
You should add a statement:M[7] = '\0'. The last character for the string should be '\0'.
|
need to make a c program that will get the current time of pc and display if its traffic or not.
Traffic every : 7:00am - 10:00am && 17pm - 19pm
need help in time comparisons. im using if else.
if ((mytime > 7 && mytime < 10) && (mytime > 17 && mytime < 19))
|
Use||(OR) instead of&&(AND). Or it will never work.
And to get the hour, do something like that:
```
#include <stdio.h>
#include <time.h>
int main() {
time_t now = time(NULL);
struct tm *now_tm = localtime(&now);
int hour = now_tm->tm_hour;
if ((hour > 7 && hour < 10) || (hour > 17 && hour < 19))
... |
I have the following lines:
```
char *name = malloc(strsize + 1);
```
and
```
uint8_t *data;
data = (uint8_t *)name;
```
It is correct? It doesn't exist a chance that the pointer *name will be interpreted bad when that conversion is done?
|
That shouldn't be much of a problem, except that thesignednessof the memory would be interpreted differently between access alongdataandname. In most of the practical platforms, the size ofcharanduint8_tin bits is the same.
|
I can't seem to find any good documentation for the DWARF DI format to answer my question. I'm writing a language that compiles to C, is there any way that I can produce DWARF Debug Information into the C code or is it assembly only?
Is itimpossibleto add debug information to some (generated) C code other than using ... |
It can be done for some things, if you assume your compiler can emit assembly. For an example of this, seemy favorite gdb test case.
Normally this isn't done, though. It can be quite hard to get right. Nowadays it's better to either write your compiler to be a direct front-end to GCC or LLVM; or to write gdb or ll... |
I want to write a C program that takes as input an integer, and outputs its square. Here is what I have tried.
However,
./a.out < 3outputs 32768, and./a.out < 4also outputs 32768.
Where am I wrong? Thanks.
```
#include <stdio.h>
int main(){
int myInt;
scanf("%d", &myInt);
printf("%d\n",myInt*myInt);
}
```
|
It looks like what you're trying to do is
```
echo 4 | ./a.out
```
the syntax for < is
```
program < input_file
```
whereas | is
```
command_with_output | program
```
|
I am working on my first C program for school. For some reason I am getting the following error when I try to compile it
```
#include <stdio.h>
int multiplication()
{
int i, j, k;
for ( i = 0; i < 10; i++) {
for (j = 0; j < 10; j++) {
for (k = 0; k < 10; k++) {
if (x[k] == 0... |
you have to declarea,bandxor receive them as arguments to your function before you can use them
|
I want to receive a file through a TCP socket on Linux. But I just get a empty file. However when I delete line 1 (while), anything will go okay. My code on server looks like this:
```
while(1)
{
FILE *fp = fopen(file_name, "w");
if(NULL == fp)
{
printf("File:\t%s Can Not Open To Write\n", file_name... |
fclosethe file before you return.
|
I have the following lines:
```
char *name = malloc(strsize + 1);
```
and
```
uint8_t *data;
data = (uint8_t *)name;
```
It is correct? It doesn't exist a chance that the pointer *name will be interpreted bad when that conversion is done?
|
That shouldn't be much of a problem, except that thesignednessof the memory would be interpreted differently between access alongdataandname. In most of the practical platforms, the size ofcharanduint8_tin bits is the same.
|
I can't seem to find any good documentation for the DWARF DI format to answer my question. I'm writing a language that compiles to C, is there any way that I can produce DWARF Debug Information into the C code or is it assembly only?
Is itimpossibleto add debug information to some (generated) C code other than using ... |
It can be done for some things, if you assume your compiler can emit assembly. For an example of this, seemy favorite gdb test case.
Normally this isn't done, though. It can be quite hard to get right. Nowadays it's better to either write your compiler to be a direct front-end to GCC or LLVM; or to write gdb or ll... |
I have a function like
```
int myfun(int *a, int *b)
{
while(some condition)
{
if(condition) return *a + *b;
else
{
some manipulation;
}
}
return -1;
}
```
When first return statement in while->if part is encountered,does the control go to the function call... |
After thereturn *a+*bthe function returns that and ends. You need thereturn -1because if that condition is never met, what will it return? It is aintfunction so it has to return something.
|
I'm trying to print the following pattern:
```
@@@@@@@@
@@@@@@@
@@@@@@
@@@@@
```
However, I am getting this instead:
```
@ABCDEFG
ABCDEFG
BCDEFG
CDEFG
```
I'm not sure what I am doing wrong. I would appreciate any feedback or direction.
```
#include <stdio.h>
#define ROWS 4
#define CHARS 8
int main(void)
{
f... |
The+operator doesn't work the way you think it does.@is converted to it's ASCII value (64) then you addrow. Whenrowis2, you are saying: print the character that coresponds the number (64 + 2) which isA.
Here's an ASCII Table
I would change the inside loop to something like this:
```
for(int ch = row; ch < CHARS; ch... |
I'm looking at string manipulation in C and I don't understand why the statements1[i] = s1[++i];won't replace the firstHby the next charactere. Take a look at the code :
```
#include <stdio.h>
main()
{
char s1[] = "Hello world !";
for(int i = 0; s1[i] != '\0'; ++i)
s1[i] = s1[++i];
printf("%s", s1);
}
```
... |
Your program hasundefined behaviourbecause in this statement
```
s1[i] = s1[++i];
```
iis modified twice between sequence points (The assignment operator=doesn't introduce a sequence point).
gcc (gcc -Wall -Wextra) warns with:
```
warning: operation on ‘i’ may be undefined [-Wsequence-point]
```
similarly clang w... |
I would like to assign hex values into char type. Due to null (\x00) character, I cannot assign all hex values. Just 4 character can be assigned. How to assign all hex values in(char*)data??
```
unsigned char data[100];
sprintf((char*)data,"\x30\x29\x02\x01\x00\x04\x06\x70\x75\x62\x6c\x69\x63\xa0");
```
|
Since you have all your hex numbers available at compile time, you can assign them using curly brace initializer instead of a string literal:
```
unsigned char data[] = {
0x30, 0x29 ,0x02, 0x01, 0x00, 0x04, 0x06,
0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0xa0
};
```
|
So I wish to make it so you cannot enter a number such as 0 or 11. I am usingnetbeans 8.1 (GNU cygwin). I have found that the while loop is not being used, and that the terminal runs a successful build regardless of the loop made to ensure out of bound numbers are not existent.
```
int main(int argc, char** argv) {
i... |
Simply needs a & (ampersand) in the scan f statement.
```
scanf("%d", &guess);
```
|
This question already has answers here:Segmentation fault when trying to modify a string [duplicate](4 answers)Closed6 years ago.
Why this code won't work, on online compiler return segment fault, on my linux VPS memory leak...
```
#include <ctype.h>
#include <stdio.h>
#include <string.h>
char *a_foo(char *str) {
... |
The string literal"TestTest"is probably stored in read-only memory in your environment, so the code ina_foothat attempts to write to it would fail.
The type of a string literal has theconstqualifier and the compiler should warn you if you try to assign it to a non-const pointer variable.
|
Just a curiosity,
Consider that I have
./first./second
that they are executable c program
first.c:
```
char main(void){
return '5';
}
```
second.c:
```
#include<stdio.h>
int main(int argc, char** argv){
printf("%s", argv[2]);
return 0;
}
```
(I want to print 5 here)
Is it possible to compile seco... |
The return value ofmain()becomes the program's exit status, which is put in the shell's$?variable. So it should be:
```
./first
./second $?
```
You should changefirst.cto return anint, notchar; otherwise it will print the ASCII code for the'5'character, not5.
```
int main(void){
return 5;
}
```
And insecond.c,... |
I would like to assign hex values into char type. Due to null (\x00) character, I cannot assign all hex values. Just 4 character can be assigned. How to assign all hex values in(char*)data??
```
unsigned char data[100];
sprintf((char*)data,"\x30\x29\x02\x01\x00\x04\x06\x70\x75\x62\x6c\x69\x63\xa0");
```
|
Since you have all your hex numbers available at compile time, you can assign them using curly brace initializer instead of a string literal:
```
unsigned char data[] = {
0x30, 0x29 ,0x02, 0x01, 0x00, 0x04, 0x06,
0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0xa0
};
```
|
So I wish to make it so you cannot enter a number such as 0 or 11. I am usingnetbeans 8.1 (GNU cygwin). I have found that the while loop is not being used, and that the terminal runs a successful build regardless of the loop made to ensure out of bound numbers are not existent.
```
int main(int argc, char** argv) {
i... |
Simply needs a & (ampersand) in the scan f statement.
```
scanf("%d", &guess);
```
|
(There was a similar question but the answer given doesn't work)
There is no warning. But after entering values, segmentation fault appears.
```
#include <stdio.h>
typedef struct
{
int a;
char b;
}PO;
PO *P[1000];
int main()
{
scanf("%d%c",&(P[0]->a),&(P[0]->b));
}
```
|
PO *P[1000];
defines an array of 1000pointerstoPOstructures.
Written like that it would probably be clearer:
```
PO* P[1000]; // <-- P is an array of 1,000 pointers to PO
```
What you probably want is a preallocated array of structures, not pointers to those, e.g.:
```
PO Data[1000];
```
In this case, you can r... |
I have a stringrangethat represents a range, for example:
```
"7-35"
```
I am looking for a simple way to split it into two integersint beginandint end.I already sawthisandthis, but I am actually searching for some kind of a "one line" command if there exist any.It is actually the opposite of doing:
```
sprintf(ran... |
The opposite of printing is scanning, and you'd usesscanf():
```
unsigned int start, end;
if(sscanf(range, "%u-%u", &start, &end) == 2)
printf("start=%u, end=%u\n", start, end);
```
Some notes:
We useunsigned intand%uto make the embedded dash non-ambigousAlways check the return value to make sure the scanning suc... |
I want to change a value in the stack inside another function.
```
int Function(int *var){
int i=125;
var = i;
}
int Function2(){
int apple;
Function(&apple);
printf("%d", apple);
}
```
This shows meerror: assignment makes pointer from integer without a castat this linevar = 125;.
I want to copy... |
You need to dereference the pointer.
```
*var = 125;
```
As written you are trying to change the address stored in the pointer (i.e., the thing the pointer is pointing to).
|
According to thecplusplus.com,tm_secfield from thetmstructure accept values from 0 to 61 in C90 and values from 0 to 60 in C99 and later.
I know that 60 can be used to express leap second but what about the other one (I mean 61)? And why did they choose to remove it?
Yeah, I tagged it both C and C++ because it is re... |
A range of0to61allows for up to 2 consecutive leap seconds on December 31st of a given year, probably mistakenly because in years that require 2 leap seconds, these are not added on the same day.
Newer versions of the C Standard correctly assume that at most one leap second will be inserted at a time on any given day... |
This question already has answers here:Yosemite and Valgrind(12 answers)Closed6 years ago.
I am not sure if I can installvalgrinddebugger in my Macbook Pro. I searched online but most posts are related to Ubuntu. Can someone tell if this is possible? If so, can it be by brew for example?
|
you can use "brew install valgrind" to install valgrind.
|
I'm trying to explain this satisfactorily, but when I call a function I want it to virtually insert itself into the main function's code in the place where I call it, so I can save typing it out multiple times, however it directly affects variables defined in the scope of the main function. What's the best way to achi... |
Sounds like you need a preprocessor macro. These aren't real functions, but blocks of code the the preprocessor replaces before compiling the code. E.g., consider a simple macro to increment a number:
```
#include <stdio.h>
#define INC(x) (x)++
int main() {
int a = 1;
INC(a);
INC(a);
printf("%d\n", ... |
I am trying to invoke python script from C application usingsystem()call
The python script has#!/usr/bin/python3on the first line.
If I dosystem(python_script), the script does not seem to run.
It seems I need to dosystem(/usr/bin/python3 python_script).
I thought I do not need to specify the interpreter externall... |
Make sure you have executable permission forpython_script.
You can makepython_scriptexecutable by
chmod +x python_script
Also check if you are giving correct path forpython_script
|
I am trying to invoke python script from C application usingsystem()call
The python script has#!/usr/bin/python3on the first line.
If I dosystem(python_script), the script does not seem to run.
It seems I need to dosystem(/usr/bin/python3 python_script).
I thought I do not need to specify the interpreter externall... |
Make sure you have executable permission forpython_script.
You can makepython_scriptexecutable by
chmod +x python_script
Also check if you are giving correct path forpython_script
|
I want to add a string to a string array but it doesn't work.Currently, I have that code:
```
void splitArray(char *strings, char *delimiter) {
int i = 0;
char newArray[MAXCHARS];
char* pch = NULL;
pch = strtok(strings, delimiter);
while (pch != NULL)
{
// doesn't work; Exception: warning: assignment makes inte... |
Use strcpy to copy string to char array.
|
I am trying to invoke python script from C application usingsystem()call
The python script has#!/usr/bin/python3on the first line.
If I dosystem(python_script), the script does not seem to run.
It seems I need to dosystem(/usr/bin/python3 python_script).
I thought I do not need to specify the interpreter externall... |
Make sure you have executable permission forpython_script.
You can makepython_scriptexecutable by
chmod +x python_script
Also check if you are giving correct path forpython_script
|
I want to add a string to a string array but it doesn't work.Currently, I have that code:
```
void splitArray(char *strings, char *delimiter) {
int i = 0;
char newArray[MAXCHARS];
char* pch = NULL;
pch = strtok(strings, delimiter);
while (pch != NULL)
{
// doesn't work; Exception: warning: assignment makes inte... |
Use strcpy to copy string to char array.
|
I don't understand why the last two lines cause warning using strlen(). Shouldn't the compiler ignore these?
```
size_t len;
char cstr[] = "char string";
signed char scstr[] = "signed char string";
unsigned char ucstr[] = "unsigned char string";
len = strlen(cstr);
len = strlen(scstr); /* warns when char is unsigne... |
Because the prototype is:
size_t strlen ( const char * str );
as stated on theref.
An implicit conversion is happening in these lines, thus the warnings. Read more here:How can I avoid gcc warning for plain "char" to : "unsigned char" OR "signed char" conversion?
As Pete Becker stated:
"chartounsigned charinvol... |
Is there any way to roundsystemGuessup. In this case the outcome ofsystemGuessis 5.5 I want it to be 6 how do I do this?
See code below:
```
int main(void){
int systemGuess = 0;
stystemGuess = (10 - 1)/2 + 1;
printf(" %d ", stystemmGuess);
}
```
|
Use floating point division andceil:
```
stystemGuess = ceil((10 - 1)/2.0) + 1;
```
If you want to round 0.4 down, useroundinstead.
|
This is part of my code:
```
float score_from_judge(number_judges, n)
{
float judge_score;
printf("Score from judge %d? ", n);
scanf("%f", &judge_score);
return(judge_score);
}
int main(void)
{
int n;
float judge_score;
n=1;
for(n; n<=number_judges; n++ ) {
judge_score = score_f... |
declare a float array and set its value inside the 'for' loop, as shown:
```
int main(){
float judge_score[10];
for(int n=1; n<=number_judges; n++ ) {
judge_score[n] = score_from_judge(number_judges, n);
}
}
```
|
My code:
```
#include <stdio.h>
int main() {
int M, N, O, P;
printf("Enter the value of M\n");
scanf("%d", &M);
N = 3*M^2;
O = M + N;
P = M + M;
printf("The value of %d \n", M + %d \n", M equals %d \n", P %d \n", N %d \n", O);
return 0;
}
```
The error:
test.c: In function 'main':te... |
You seem to have mixed up your formatting string, with some %d and \n outside of your quotes.
Try writing your entire formatting string first, then each of the arguments; like so:
```
printf("The value of %d \nM equals %d \nN %d \n", M, P, 0);
```
Each %d should correspond to the number you want to print from the a... |
I wanted to know the meaning of space after the format specifier in scanf. There are many posts related to space in scanf and most of them talk of the space before %c. In the below code, I have to enter second character for first scanf to return. Just entering enter key will not break the scanf. Because of this second... |
If you use trailing space after"%c"thenscanfwill need to find the next non-white-space to be able to return. If there is none thenscanfwill block for ever.
|
I am using this :
```
if(strstr(inData, respond) != NULL)
```
to search for the stringCMDinsideinData.
problem is that when new data looks like this :
```
Reboot
CMD
```
strstrwill not find it, because it stops searching where is a new line.
Is there an elegant way (notusing fancy functions since I can't) to get ... |
As pointed out in the comments, strstr does not stop at newline boundaries, but only at string terminators (\0)
Here is the relevant section from the man page:
DESCRIPTION
The strstr() function finds the first occurrence of the substring needle in the string haystack. The terminating null
bytes
... |
I have been working on a college project. I want user to enter Y/N if he wants to continue or not, so I wrote following code
```
repeat:
pr=0;
q=0;
res=0;
printf("\nEnter the serial number of product you wish to purchase: ");
scanf("%d",&pr);
printf("Quantity: ");
scanf("%d",&q);
bill... |
There is a bug in this line
```
scanf("%d",&res);
```
It should be
```
scanf(" %c",&res);
```
The formatting placeholders for char is%cnot%d
|
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
```
#include <stdio.... |
The program converts any input into lower case output.
You would have recognized this yourself, if youran it,debugged it, or justmade a paper testfor this.
|
Is there a possibility to load a system font usingsdl2-ttf. I read the documentation but there seems only the way of loading a font with the full file path. On windows this would be a bit easier than in linux, as you can find the font folder relativly easy, but on Linux this is more of an issue as fonts can be stored ... |
To display text on Linux you need to go through harfbuzz-ng (for correct text shaping) and fontconfig (for font discovery and substitution), either directly or via a third-party lib such as pango or cairo.
Direct use of ttf files bypasses the font location stack, font substitution stack, correct opentype metadata par... |
In TensorFlow, you can create custom allocators for various reasons (I am doing it for new hardware). Due to the structure of the device, I need to use a struct of a few elements as my data pointer which the allocator returns as avoid*.
In the kernels that I am writing, I am given access to Tensors but I need t get t... |
You may also be able to useTensor::tensor_data().data() to get access to the raw pointer, without using the weird indirection through DMAHelper.
|
I have a file pointercurrent_fileof typeFILE *current_file;. When I run this code
```
current_file = fopen ("file.text", "r");
struct buffer *buf;
buf->file = current_file;
```
I keep ending with aSegmentation fault (core dumped). Herebufferis a struct like so:
```
struct buffer {
FILE *file;
int size;
};
`... |
You only declare buf to be a pointer of the type buffer, but there is no memory allocated for the struct.
Therefore you have an uninitialized pointer.
|
I came across this syntax today and couldn't work out what it meant:
```
// Uses the GNU C statement expression extension
#define envSet(name) ({ \
static int initialised; \
static bool set; \
(void) "" name; \
if (!initialised || !g_cacheEnv) { \
const char *value = getenv(name); \
set = value != NULL; \
... |
It looks like a way to statically ensure thatnameis a string literal and not some other type.
If you do(void)"" "hello";then it is a valid C expression.
But if you do something like(void)"" 1;then you get a syntax error.
|
When you define a structure like below
```
typedef struct num {
int a;
int b;
} A;
```
Thensizeof(A)is valid, butsizeof(num)isn't. Could anyone please explain the reason why the sizeof operator doesn't acceptnum?
|
Becausenumon its own doesn't constitute atypein C (onlystruct numor its typedefAconstitutes thetype). So,sizeoffails as its operand is not in either form of that it's defined for:
```
sizeof unary-expression
sizeof ( type-name )
```
i.e.numis neither atypenor aunary-expression.
So,sizeof(struct num)orsizeof(A)is fi... |
I am trying to compile sqlite from sources (amalgamation) to use it from C#. The reason to compile it myself rather than use precompiled version is that I need JSON support which is not included by default. This is how I compiled it:
```
cl sqlite3.c -DSQLITE_ENABLE_JSON1 -link -dll -out:sqlite3.dll
```
Then I tried... |
The solution is to export the API functions:
```
cl sqlite3.c -DSQLITE_API=__declspec(dllexport) -link -dll -out:sqlite3.dll
```
|
I am trying to memcpy from one ptr to another. I know the size that I want to copy. Both the destination and source pointers are void pointers. Is this valid? Does it actually copy the ELEMENT_SIZE (integer like 128) from source to the destination? I know this is not the most ideal thing to do. But I want to know if t... |
Does it actually copy the ELEMENT_SIZE (integer like 128) from source
to the destination?
Yes, If you know the size information,then its working fine.
See the reference link :http://www.cplusplus.com/reference/cstring/memcpy/
|
I want to evaluate the following boolean expression in C:
```
f = (b+c')(a'+c')(a+b'+c)
```
This is my current program:
```
#include <stdio.h>
int main()
{
int a,b,c,f;
a=0;b=1;c=1;
f=((b|(~c))&((~a)|(~c))&(a|(~b)|c));
printf("%d\n",f);
}
```
The function should return 1 since a=0,b=1 and c=1 but it... |
In C you use!for negation:
```
#include <stdio.h>
int main()
{
int a,b,c,f;
a=0;b=1;c=1;
f=((b||(!c))&&((!a)||(!c))&&(a||(!b)||c));
printf("%d\n",f);
}
```
The~operator flips all the bits in a number, which is not what you wanted, and why you were getting -1.
Also you need||instead of|and&&instead of... |
I want to have a regex that contains one and only one "-", followed by "s" or "h".
So, "-shshshshs" would match, "-ssssss" would too, but "-so" would not match, neither would "sh".
So far, I only succeeded to match "if strings contains "-" and "s" or "h", but typing "-sho" is accepted.
```
/* Compile regular express... |
If your regex engine supports it:
```
"-[sh]+$"
```
Otherwise:
```
"-[sh][sh]*$"
```
|
Give the c code for a loop that computes and displays a sum of numbers that the user enters. The loop should prompt the user for input until the user enters -335 and then exit and display the final sum.
This is what I have. Why does it not print (exit the loop) when I enter -335? It just keeps asking me to input a n... |
userNum changes after you have input it, in the statementuserNum += userNum;. -335 plus -335 is -670, not 335.
|
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
How show 00156,00
```
float number = 156;
printf("%5.2f",number);
```
The output of the example above:
O... |
You need to pass the0flag for leading zeros, and the field width must be wide enough to have any leading characters printed. So you might try this:
```
printf("%08.2f", number);
```
The.verses,(aka, the "radix character") is determined from the LC_NUMERIC portion of the locale. Seeman setlocalefor information on s... |
Functions likememchrseem quite simple but Rust projects usebindings to the C codewith only a Rust fallback, rather than implementing them in Rust. Can'tmemchrbe efficiently implemented in Rust?
|
They can. If you look at glibc's implementation, it will look somewhat likefallback:memchr. However, that's only part of the story. Thegeneric implementationis used only when there isn't a more appropriate one available.
For example,x68-64 has a variant written in assembly. And so domanyotherarchitectures, that provi... |
I have a huge project consisting of:
main.cwhich contains main function and calls function fromabc.S- nothing more!abc.Swhich does some initialization steps and then calls other assembly routinesa1.S,a2.S, ... which contain functions called byabc.S
abc.Shas all the files included like this:
```
.include "a1.S"
.inc... |
Figured it out for myself - makefile could look like this:
```
all:
gcc -o abc a1.S a2.S a3.S abc.S main.c
clean:
rm -rf abc
```
Includedefinitions.hina1.Sand includea1.Sinabc.S.
|
I am new to kernel module programming and got some problem while compiling some old kernel code. I am getting following error messages,
```
error: ‘struct tty_driver’ has no member named ‘write’
((my_tty->driver)->write) (my_tty,0,str,strlen(str));
```
I checked thetty_driver.hfile, therewriteis defined.... |
writeis indeed defined, but not as members oftty_driver. It is defined as members oftty_operations, andtty_driverhas a memberops, a pointer to aconst tty_operations.
So, I usedmy_driver->ops->writeinstead ofmy_driver->driver->write.
|
I want to get a number of days from a certain date to current date.
Here is my current code that gets the days from 1/1/1970.
```
int days_since_my_birth(int day, int month, int year) {
time_t sec;
sec = time(NULL);
printf("Number of days since birth is %ld \n", sec / 86400);
return d;
}
```
Can I... |
Subtract the julian day integer of the earlier date from the julian integer of the later date. The following tells you exactly how to do that.
http://www.cs.utsa.edu/~cs1063/projects/Spring2011/Project1/jdn-explanation.html
Otherwise,http://pdc.ro.nu/jd-code.htmlalready has a C version
```
long gregorian_calendar_... |
This question already has answers here:What is the difference between macro constants and constant variables in C? [duplicate](4 answers)Closed6 years ago.
I am rewriting a function and I noticed one particular variable is never reassigned after initialization. Is there any reason NOT to simply convert this variable... |
A macro is basically never preferable compared to a variable, since a variable which doesn't change its value can be declared asconstand it will likely be optimized away in any case.
```
const int CONST_VALUE = 1234;
```
is safer and clearly expresses the meaning more than a macro.
|
I've found an interesting way to allocate matrices in C which allows the use of[i][j]without initializing asdouble matrix_a[nrows][ncols]. The allocation is
```
double (*matrix_a)[ncols] = (double (*)[ncols])malloc(sizeof(double) * (nrows) * (ncols));
```
But I can't find how to properly free this type of allocation... |
That is correct. You may only pass tofreewhat was returned frommallocand family. So since you did onemalloc, you do onefree.
Also,there is no need to cast the return value of malloc:
```
double (*matrix_a)[ncols] = malloc(sizeof(double) * (nrows) * (ncols));
```
|
```
void main()
{
char a;
float f = 10;
for(a=1; a<=5; a++)
{
f-=.2;
printf("\nf = %g", f);
}
}
```
Here the for loop is executive five times and each time the value of f is decremented by .2.But according to me the final value of f should be 9.0 but output is 9.
Why the value of f is not coming in decimal po... |
The decimal point is not shown for%gconversions if there is no non-zero digit following the decimal point. You can use%finstead, or explicitly specify the number of digits you want to see behind the decimal point, for example%.1gto always show 1 digit.
|
Why we don't use extern when using function from one .c file in another .c file , but we must do extern for variables case? Is it related to linker?
|
Functions are extern qualified by default (unless you change it to internal withstatic). For example,
```
int func(void) {
}
extern int func2(void) {
}
```
Bothfuncandfunc2are external. Theexternkeyword is optional for external functions.
|
Functions likememchrseem quite simple but Rust projects usebindings to the C codewith only a Rust fallback, rather than implementing them in Rust. Can'tmemchrbe efficiently implemented in Rust?
|
They can. If you look at glibc's implementation, it will look somewhat likefallback:memchr. However, that's only part of the story. Thegeneric implementationis used only when there isn't a more appropriate one available.
For example,x68-64 has a variant written in assembly. And so domanyotherarchitectures, that provi... |
I have a huge project consisting of:
main.cwhich contains main function and calls function fromabc.S- nothing more!abc.Swhich does some initialization steps and then calls other assembly routinesa1.S,a2.S, ... which contain functions called byabc.S
abc.Shas all the files included like this:
```
.include "a1.S"
.inc... |
Figured it out for myself - makefile could look like this:
```
all:
gcc -o abc a1.S a2.S a3.S abc.S main.c
clean:
rm -rf abc
```
Includedefinitions.hina1.Sand includea1.Sinabc.S.
|
I am new to kernel module programming and got some problem while compiling some old kernel code. I am getting following error messages,
```
error: ‘struct tty_driver’ has no member named ‘write’
((my_tty->driver)->write) (my_tty,0,str,strlen(str));
```
I checked thetty_driver.hfile, therewriteis defined.... |
writeis indeed defined, but not as members oftty_driver. It is defined as members oftty_operations, andtty_driverhas a memberops, a pointer to aconst tty_operations.
So, I usedmy_driver->ops->writeinstead ofmy_driver->driver->write.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.