The C programming language distinguishes character constants from string constants by using single quotation marks for characters and double quotation marks for strings. Thus,'c' is the character c, while "c" is a string of length 1 consisting of the single character c.Why is this distinction is made? How is it useful?
jeudi 2 juillet 2015
What exactly is in a .o / .a / .so file?
I was wondering what exactly is stored in a .o or a .so file that results from compiling a C++ program. This post gives a quite good overview of the compilation process and the function of a .o file in it, and as far as I understand from this post, .a and .so files are just multiple .o files merged into a single file that is linked in a static (.a) or dynamic (.so) way.
But I wanted to check if I understand correctly what is stored in such a file. After compiling the following code
void f();
void f2(int);
const int X = 25;
void g() {
f();
f2(X);
}
void h() {
g();
}
I would expect to find the following items in the .o file:
- Machine code for
g(), containing some placeholder addresses wheref()andf2(int)are called. - Machine code for
h(), with no placeholders - Machine code for
X, which would be just the number25 - Some kind of table that specifies at which addresses in the file the symbols
g(),h()andXcan be found - Another table that specifies which placeholders were used to refer to the undefined symbols
f()andf2(int), which have to be resolved during linking.
Then a program like nm would list all the symbol names from both tables.
I suppose that the compiler could optimize the call f2(X) by calling f2(25) instead, but it would still need to keep the symbol X in the .o file since there is no way to know if it will be used from a different .o file.
Would that be about correct? Is it the same for .a and .so files?
Thanks for your help!
printf() without '\n' doesn't work in libev
Post the code first:
#define EV_STANDALONE 1
#include <stdio.h>
#include "ev.c"
ev_timer timeout_watcher;
struct ev_loop* loop;
static void timeout_cb (EV_P_ ev_timer *w, int revents)
{
// puts("timeout");
printf("timeout");
ev_timer_again(loop, w);
}
int main (void)
{
printf("hello, world.");
loop = EV_DEFAULT;
ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.);
timeout_watcher.repeat = 2.0;
ev_timer_start (loop, &timeout_watcher);
ev_run (loop, 0);
return 0;
}
Strange thing happened while running: although the printf("hello, world."); was in the first place in main function, but it didn't work. But if I use printf("hello, world\n"); instead, things worked fine. Further more, I changed printf("hello, world"); instead of puts("hello, world");, it also worked. So what on earth did libev do to the io? Why "\n" matters?
Is there a way to find matching #if, #else, #elif & #endif in Eclipse?
I have some long C & C++ header files with a lot of nested #if statements in them.
#if FOO
...
#elif BLAR
#ifndef WIDGET
#endif
#else
...
#end
Is there a way to jump between matching statements in Eclipse? I have found a similar question that says it is possible in Visual Studio which suggests that the CTRL + ] key combination should do it, but that seems to only work for matching braces.
Assigning a string to a pointer in a struct
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Person {
char *forename;
char *surname;
int age;
};
void change_struct(struct Person *person, char *forename, char *surname,
int age);
void print_struct(struct Person *person);
int main(void)
{
struct Person person1;
person1.forename = malloc((strlen("Max") + 1) * sizeof(char));
if (!person1.forename) {
exit(EXIT_FAILURE);
}
strcpy(person1.forename, "Max");
person1.surname = malloc((strlen("Mustermann") + 1) * sizeof(char));
if (!person1.surname) {
exit(EXIT_FAILURE);
}
strcpy(person1.surname, "Mustermann");
person1.age = 35;
print_struct(&person1);
change_struct(&person1, "Hans", "Bauer", 45);
print_struct(&person1);
free(person1.forename);
free(person1.surname);
exit(EXIT_SUCCESS);
}
void change_struct(struct Person *person, char *forename, char *surname,
int age)
{
person->forename = realloc(person->forename,
(strlen(forename) + 1) * sizeof(char));
if (!person->forename) {
exit(EXIT_FAILURE);
}
strcpy(person->forename, forename);
person->surname = realloc(person->surname,
(strlen(surname) + 1) * sizeof(char));
if (!person->surname) {
exit(EXIT_FAILURE);
}
strcpy(person->surname, surname);
person->age = age;
}
void print_struct(struct Person *person)
{
printf("%s\n", person->forename);
printf("%s\n", person->surname);
printf("%d\n", person->age);
}
When assigning a string to a pointer in a struct is it well-defined behavior if I would do
person1.forename = "Max";
person1.surname = "Mustermann";
in main() initially instead of using malloc() and strcpy()? (Of course in this specific case I would need to also change the realloc() calls in change_struct() since it is undefined behavior when realloc() receives a non- malloc(), calloc(), or realloc() created pointer.) If dynamic memory allocation should be required could you give an explanation why?
Why can't I compile this C API (NeMo Spiking Neural Network Simulator)
Hi I am trying to utilize this library http://ift.tt/1Nyk9EY to play around with Spiking Neural Networks.
I am new to C and C++.
What I've done is, downloaded the installer from here: http://ift.tt/1Nyk9F0
Installed.
I then wrote this program in main.c file:
#include<nemo.h>
#include<stdio.h>
#include<stdlib.h>
main()
{
printf("Hello World!");
getchar();
}
and compiled it using MinGW on Windows:
gcc -I"C:\Program Files (x86)\NeMo\include" main.c -o main.exe
I get the following error:
In file included from main.c:1:0:
C:\Program Files (x86)\NeMo\include/nemo.h:48:1: error: unknown type name 'nemo_
network_class'
typedef nemo_network_class* nemo_network_t;
^
C:\Program Files (x86)\NeMo\include/nemo.h:49:1: error: unknown type name 'nemo_
simulation_class'
typedef nemo_simulation_class* nemo_simulation_t;
^
C:\Program Files (x86)\NeMo\include/nemo.h:50:1: error: unknown type name 'nemo_
configuration_class'
typedef nemo_configuration_class* nemo_configuration_t;
^
Please help me.
It looks like nemo.h has problems, but I suspect I am missing something because I am a newbie...
What is EOF and what is its significance? How can it be noticed?
While studying getchar() function in C ,I came across this EOF being returned , I want to know how can its existence be noticed, where is it stored?
Can we type EOF character explicitly?
How can I execute .bin file with assembly or C?
I am currently working on my OS. I've started building it since a-day before yesterday.I want to know that how can I open .bin files with C language or assembly.I want it open when my OS is running and I click a button.
I can use only assembly or C.
Please help.
returning a buffer in c
I have a couple of questions.
I need to write a program(winapi) that will create a buffer of a fixed size, then append strings to it and returns it.
1. Is it even possible for "main" to return a buffer? 2. How should I create, append string and return it?
I am not new to C, but I have very little experience with buffers and strings handling.
Thank you!
Why does 'typeof enum constant' generate a warning when compared to a variable of enum type?
I have the following code.
typedef enum {FOO, BAR} Baz;
int main()
{
Baz f1 = FOO;
typeof(FOO) f2 = FOO;
return (f1 == f2);
}
My compilation using gcc -Wextra foo.c generates a warning saying
foo.c: In function ‘main’:
foo.c:7:13: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
return (f1 == f2);
^
My gcc version
gcc --version
gcc (Ubuntu 4.9.2-10ubuntu13) 4.9.2
How can I fix this problem?
How can I use the kernel function in my C code?
First, i want to apologize for my English, it's not my mother language but i will do my best.
I'm a new developer in Debian, before that I only do cross-plateform code. Since cross-plateform isn't in my constraint anymore, I want to be as close as possible from the kernel or the binary (like ls, mount and other binary in C).
What bug me is I can't find the source code for the binary in my debian 7.1.0 and 8.0.1. I know this is a common question, but it's seem that all I do finish by a failure (and be new in Debian doesn't really help me :/ )
For example : i want to see the code of ifup / ifdown command. I search and i see that ifupdown isn't a binary but a script so I can directly view inside, but in my Debian it's a ELF binary.
Does a documentation to get a source code for a binary Debian exist ? I'm really frustrated because I have the feeling that the answer is just under my nose ! It drive me crazy :/
The second thing is, for example, i want to use AES for crypt file. AES exist in the kernel and I prefer to use the AES kernel rather than another AES (I simply trust more the kernel source code). Is there a way to use Kernel function in user space ?
I hope I doesn't make a mistake with my question. Thank you for your reading, stack overflow help me a dozen and dozen time in the past, so thank you.
ARM bare metal (no OS), Eclipse, GDB and Segger J-Link
This is my first question on stackoverflow, so I'll give some background info. I have some experience with Cortex-M development and I'm now discovering Cortex-A8. I'm interessed in bare-metal programming without any OS running on the device. I'm comfortable with C and especially C++.
In contrast to the Cortex-M devices I used (Atmel SAM4s), which have flash memory to store exectuable code, the Cortex-A8 (TI AM3358) uses its own ROM code to boot. This rom code is responsible for loading code for a second boot step into on-chip RAM and executing this code. This second step usualy sets up peripherals etc, initializes external devices (external DDR3 memory), loads final code into this DDR3 memory and jumps to the entry point of this final code.
I'm using Eclipse with GNU bare metal ARM toolchain on Windows 8.1 machine, and have a SEGGER J-Link to debug on the real hardware (Beaglebone Black).
When I run/debug the second bootloader step (in the embedded RAM) everything works fine, I'm able to initialize the external DDR3 memory.
When I try to load executable code into the DDR3 memory things goes wrong : I'm unable to make this work.
After rethinking, I Think I need some kind of script to: 1) load the second bootloader's executable code into embedded RAM and execute it (initialize peripherals and DDR3 memory) 2) at the end of step 1), break into the debugger to load the executable code into DDR3 memory 3) set the programm counter to the entry point of the executable in DDR3 and start executing these code.
On the SAM4s I have worked with Atmels EDBG debugging tool, so I don't have experience with configuring and setting up the SEGGER J-Link to control this booting process. What I need is more info on how I can accomplish this tasks : Load the second boot step into embedded RAM (file MLO.elf) Execute this code At the end of this code, break into the debugger to load the target code into DDR3 memory (Kernel.elf) Jump to the entry point of the target code without resetting the SoC.
Any help on this is very welcome.
Thanks, Paul
Why is a multithreaded C program forced to a single CPU on Mac OS X when system() is used in a thread?
I encountered a strange difference in the behavior of a program using pthreads between Linux and Mac OS X.
Consider the following program that can be compiled with "gcc -pthread -o threadtest threadtest.c":
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
static
void *worker(void *t)
{
int i = *(int *)t;
printf("Thread %d started\n", i);
system("sleep 1");
printf("Thread %d ends\n", i);
return (void *) 0;
}
int main()
{
#define N_WORKERS 4
pthread_t workers[N_WORKERS];
int args[N_WORKERS];
int i;
for (i = 0; i < N_WORKERS; ++i)
{
args[i] = i;
pthread_create(&workers[i], NULL, worker, args + i);
}
for (i = 0; i < N_WORKERS; ++i)
{
pthread_join(workers[i], NULL);
}
return 0;
}
Running the resulting executable on a 4-core Mac OS X machine results in the following behavior:
$ time ./threadtest
Thread 0 started
Thread 2 started
Thread 1 started
Thread 3 started
Thread 0 ends
Thread 1 ends
Thread 2 ends
Thread 3 ends
real 0m4.030s
user 0m0.006s
sys 0m0.008s
Note that the number of actual cores is probably not even relevant, as the time is simply spent in the "sleep 1" shell command without any computation. It is also apparent that the threads are started in parallel as the "Thread ... started" messages appear instantly after the program is started.
Running the same test program on a Linux machine gives the result that I expect:
$ time ./threadtest
Thread 0 started
Thread 3 started
Thread 1 started
Thread 2 started
Thread 1 ends
Thread 2 ends
Thread 0 ends
Thread 3 ends
real 0m1.010s
user 0m0.008s
sys 0m0.013s
Four processes are started in parallel that each sleep for a second, and that takes roughly a second.
If I put actual computations into the worker() function and remove the system() call, I see the expected speedup also in Mac OS X.
So the question is, why does using the system() call in a thread effectively serialize the execution of the threads on Mac OS X, and how can that be prevented?
How to find memory leaks with Clang
I have installed Clang in my machine (ubuntu) in order to find memory leaks in my C code. I wrote a sample code in order to check the working of it which is as follows:
/* File: hello.c for leak detection */
#include <stdio.h>
#include <stdlib.h>
void *x;
int main() {
x = malloc(2);
x = 0; // Memory leak
return 0;
}
I found some options in internet to compile like
$ scan-build clang --analyze hello.c
and
$ scan-build clang -fsanitize=address hello.c
But none of them are showing any signs of memory leak.
scan-build: Using '/usr/bin/clang' for static analysis
scan-build: Removing directory '/tmp/scan-build-2015-07-02-122717-16928-1' because it contains no reports.
scan-build: No bugs found.
Can anyone kindly tell how to correctly use Clang for Memory leak detection.
Recursive Insertion in a Binary Tree C#
Why reason the member variables LEFT and RIGHT never change when i make the recursive call? Here's the Source Code:
public class C_Nodo
{
int dato;
C_Nodo left;
C_Nodo right;
public int DATO
{
get { return dato; }
set { dato = value; }
}
public C_Nodo LEFT
{
get { return this.left; }
set { this.left= value; }
}
public C_Nodo RIGHT
{
get { return this.right; }
set { this.right = value; }
}
public C_Nodo(int inf)
{
this.dato = inf;
this.left = null;
this.right = null;
}
}
public class C_Arbol_Bin
{
C_Nodo root;
public C_Arbol_Bin()
{
root = null;
}
Simple insertion in the root or make the recursive call
public void inserta(int dat)
{
if (root == null)
{
root = new C_Nodo(dat);
}
else
{
insert_Order(this.root, dat);
}
}
Here i make the recursive insertion in ordered way depending of the value that contains the father node but RIGH and LEFT never change.
public void insert_Order(C_Nodo tree, int inf)
{
if (tree == null)
{
tree = new C_Nodo(inf);
}
else
{
if (tree.DATO > inf)
{
insert_Order(tree.LEFT, inf);
}
else
{
insert_Order(tree.RIGHT, inf);
}
}
}
}
Thanks for any help.
Setting arguments in a kernel in OpenCL causes error
I am a beginner in OpenCL and thus writing a simple program to double the elements of an array. The kernel code is:-
__kernel void dataParallel(__global int* A, __global int* B)
{
int base = get_local_id(0);
B[base]=A[base]+A[base];
}
The local_work_size=32 as I am squaring 32 elements.
In my program I have declared an integer array which holds the elements to be squared.
int *A;
A=(int*)malloc(sizeof(int)*64);
for (i=0; i < 32; i++) { A[i] = i; }
platforms[i] stores the platform id, devices[j] stores the corresponding device id. Their types:
cl_platform_id* platforms;
cl_device_id* devices;
Creating context
cl_context context=clCreateContext(NULL,1,&devices[j],NULL,NULL,NULL);
Next comes the command queue
cl_command_queue cmdqueue=cmdqueue=clCreateCommandQueue(context,devices[j],NULL,&err);
Next I created 2 memory buffers, one to hold the input data and the other to hold the result.
cl_mem Abuffer,Bbuffer;
Abuffer=clCreateBuffer(context, CL_MEM_READ_WRITE ,32*sizeof(int),NULL,&err);
Bbuffer=clCreateBuffer(context, CL_MEM_READ_WRITE ,32*sizeof(int),NULL,&err);
Then I copied the data of array A to Abuffer
ret=clEnqueueWriteBuffer(cmdqueue, Abuffer, CL_TRUE, 0, 32*sizeof(int), A, 0, NULL, NULL);
printf("%d",ret);//output is 0 thus data written successfully into the buffer
The kernel code was then read into a character string source_str and the program was created.
kernelprgrm=clCreateProgramWithSource(context,1,(const char **)&source_str,(const size_t *)&source_size,&err);
if(!err)
{
printf("\nKernel program created successfully\n");
}//Outputs -Kernel program created successfully
I then built the program using:
ret=clBuildProgram(kernelprgrm,1,&devices[i],NULL,NULL,NULL);//returns CL_SUCCESS
Getting buildinfo next
ret=clGetProgramBuildInfo(kernelprgrm,devices[j], CL_PROGRAM_BUILD_STATUS ,0,NULL,&size);//Returns success
Creating kernel
kernel = clCreateKernel(kernelprgrm, "dataParallel", &ret);
printf("\nReturn kernel program=%d",ret);
if(!ret)
{
printf("\nProgram created successfully!\n");
}
//Outputs -Program created successfully!
Now comes the devil:-
ret=clSetKernelArg(kernel,0,sizeof(cl_mem),(void *) Abuffer);
printf("\nKernel argument 1 ret=%d",ret);
ret=clSetKernelArg(kernel,1,sizeof(cl_mem),(void *) Bbuffer);
printf("\nKernel argument 2 ret=%d",ret);
Both return -38 meaning CL_INVALID_MEM_OBJECT.
P.S.:As per the errors pointed out i.e. use &Abuffer instead of Abuffer in the argument, both return 0
Also ret=clEnqueueTask(cmdqueue,kernel,NULL,NULL,NULL); returns 0.
Trying to get the result
ret = clEnqueueReadBuffer(cmdqueue, Bbuffer, CL_TRUE, 0, 32*sizeof(int), B, 0, NULL, NULL);`
printf("\nB:-\n");
for (t=0; t < 32; t++) {
printf("%d\t ", B[t]);
}
This prints garbage values! While ret = clEnqueueReadBuffer(cmdqueue, Abuffer, CL_TRUE, 0, 32*sizeof(int), A, 0, NULL, NULL); returns the Array A successfully.
Console input in 32-bit Protected mode
I am currently working on my OS. I've started building it since a-day before yesterday. My OS is command-based.
This is my Kernel.c(The main file):
#include "include/screen.h"
#include "include/kb.h"
#include "include/string.h"
#include "data/userdata.c"
kmain()
{
clearScreen();
print("Halcyon OS 1.05 Beta ");
while (1)
{
print("\nhalcyon@halcyon ~\n$ ");
string ch = readStr();
if(strEql(ch,"cmd")!=0)
{
print("\nYou are already in cmd\n");
}
else if(strEql(ch,"clear")!=0)
{
clearScreen();
}
else if(strEql(ch,"help")!=0)
{
print("Halcyon help.");
}
else if(strEql(ch,"")!=0)
{
continue;
}
else
{
print("\nNo command found:");print(ch);
break;
}
}// end while loop!
}
And here is kb.h (I've made it for keyboard support.):
#ifndef KB_H
#define KB_H
#include "screen.h"
#include "system.h"
#include "types.h"
string readStr()
{
char buff;
string buffstr;
uint8 i = 0;
uint8 reading = 1;
while(reading)
{
if(inportb(0x64) & 0x1)
{
switch(inportb(0x60))
{
/*case 1:
printch('(char)27); Escape button
buffstr[i] = (char)27;
i++;
break;*/
case 2:
printch('1');
buffstr[i] = '1';
i++;
break;
case 3:
printch('2');
buffstr[i] = '2';
i++;
break;
case 4:
printch('3');
buffstr[i] = '3';
i++;
break;
case 5:
printch('4');
buffstr[i] = '4';
i++;
break;
case 6:
printch('5');
buffstr[i] = '5';
i++;
break;
case 7:
printch('6');
buffstr[i] = '6';
i++;
break;
case 8:
printch('7');
buffstr[i] = '7';
i++;
break;
case 9:
printch('8');
buffstr[i] = '8';
i++;
break;
case 10:
printch('9');
buffstr[i] = '9';
i++;
break;
case 11:
printch('0');
buffstr[i] = '0';
i++;
break;
case 12:
printch('-');
buffstr[i] = '-';
i++;
break;
case 13:
printch('=');
buffstr[i] = '=';
i++;
break;
case 14:
printch('\b');
i--;
buffstr[i] = 0;
break;
/* case 15:
printch('\t'); Tab button
buffstr[i] = '\t';
i++;
break;*/
case 16:
printch('q');
buffstr[i] = 'q';
i++;
break;
case 17:
printch('w');
buffstr[i] = 'w';
i++;
break;
case 18:
printch('e');
buffstr[i] = 'e';
i++;
break;
case 19:
printch('r');
buffstr[i] = 'r';
i++;
break;
case 20:
printch('t');
buffstr[i] = 't';
i++;
break;
case 21:
printch('y');
buffstr[i] = 'y';
i++;
break;
case 22:
printch('u');
buffstr[i] = 'u';
i++;
break;
case 23:
printch('i');
buffstr[i] = 'i';
i++;
break;
case 24:
printch('o');
buffstr[i] = 'o';
i++;
break;
case 25:
printch('p');
buffstr[i] = 'p';
i++;
break;
case 26:
printch('[');
buffstr[i] = '[';
i++;
break;
case 27:
printch(']');
buffstr[i] = ']';
i++;
break;
case 28:
// printch('\n');
// buffstr[i] = '\n';
i++;
reading = 0;
break;
/* case 29:
printch('q'); Left Control
buffstr[i] = 'q';
i++;
break;*/
case 30:
printch('a');
buffstr[i] = 'a';
i++;
break;
case 31:
printch('s');
buffstr[i] = 's';
i++;
break;
case 32:
printch('d');
buffstr[i] = 'd';
i++;
break;
case 33:
printch('f');
buffstr[i] = 'f';
i++;
break;
case 34:
printch('g');
buffstr[i] = 'g';
i++;
break;
case 35:
printch('h');
buffstr[i] = 'h';
i++;
break;
case 36:
printch('j');
buffstr[i] = 'j';
i++;
break;
case 37:
printch('k');
buffstr[i] = 'k';
i++;
break;
case 38:
printch('l');
buffstr[i] = 'l';
i++;
break;
case 39:
printch(';');
buffstr[i] = ';';
i++;
break;
case 40:
printch((char)44); // Single quote (')
buffstr[i] = (char)44;
i++;
break;
case 41:
printch((char)44); // Back tick (`)
buffstr[i] = (char)44;
i++;
break;
/* case 42: Left shift
printch('q');
buffstr[i] = 'q';
i++;
break;
case 43: \ (< for somekeyboards)
printch((char)92);
buffstr[i] = 'q';
i++;
break;*/
case 44:
printch('z');
buffstr[i] = 'z';
i++;
break;
case 45:
printch('x');
buffstr[i] = 'x';
i++;
break;
case 46:
printch('c');
buffstr[i] = 'c';
i++;
break;
case 47:
printch('v');
buffstr[i] = 'v';
i++;
break;
case 48:
printch('b');
buffstr[i] = 'b';
i++;
break;
case 49:
printch('n');
buffstr[i] = 'n';
i++;
break;
case 50:
printch('m');
buffstr[i] = 'm';
i++;
break;
case 51:
printch(',');
buffstr[i] = ',';
i++;
break;
case 52:
printch('.');
buffstr[i] = '.';
i++;
break;
case 53:
printch('/');
buffstr[i] = '/';
i++;
break;
case 54:
printch('.');
buffstr[i] = '.';
i++;
break;
case 55:
printch('/');
buffstr[i] = '/';
i++;
break;
/*case 56:
printch(' '); Right shift
buffstr[i] = ' ';
i++;
break;*/
case 57:
printch(' ');
buffstr[i] = ' ';
i++;
break;
}
}
}
buffstr[i] = 0;
return buffstr;
}
#endif
And at last the string.h(This has function to compare two strings.):
#ifndef STRING_H
#define STRING_H
#include "types.h"
uint16 strlength(string ch)
{
uint16 i = 1;
while(ch[i++]);
return --i;
}
uint8 strEql(string ch1,string ch2)
{
uint8 result = 1;
uint8 size = strlength(ch1);
if(size != strlength(ch2)) result =0;
else
{
uint8 i = 0;
for(i;i<=size;i++)
{
if(ch1[i] != ch2[i]) result = 0;
}
}
return result;
}
#endif
But the problem is that even if enter the correct command like 'cmd', it says 'No command found: cm'. It should say: 'You're already in cmd!'
Also, it is recognizing it as 'cm' not 'cmd'.
And if I write in kernel.c: "print("Hello");" then it will print: 'Hell' not 'Hello'! It misses the last character.
I don't know what's wrong with my program. I use gcc to compile it, platform is Linux Ubuntu.
Please help! Any help will be greatly appreciated.
mercredi 1 juillet 2015
Why is the value of "C" changing in the following code?
the output I'm getting for the given code is "0" even though I initialized the value of c as "1"...can somebody explain it... Why is the value of "C" changing in the following code??
#include <iostream>
using namespace std;
int c=1; // global initialized 'c' as 1..
long long f(long long n){
if(n==6){
return 2;
}
else{
c=c+1;
f(n-2);
}
}
int main()
{
long long n,ans,p;
cin>>n;
ans=f((2*n)-2);
cout<<c; //printing out the value of 'c'
return 0;
}
Split array into fixed size
I would like to know how can I split my array into a fixed size ( a block) and each block contains an ID
Example: I have an array of data 1, 2, 3, 4, 5, 6, 7, 8
I would like to output it as
- Counter 0 = 1, 2, 3
- Counter 1 = 4, 5, 6
- Counter 2 = 7, 8
Each block of has an incremented counter
const uint8_t MAX_SIZE = 3;
uint8_t data[] = { 1, 2, 3, 4, 5, 6, 7, 8};
uint8_t counter = 0;
int data_length = sizeof(data);
int current_length = data_length;
int index = 0;
while (current_length > MAX_SIZE) {
printf("Counter: %d = ", counter++);
for (int i = 0; i < MAX_SIZE; i++) {
printf("%d ", data[index++]);
}
printf("\n");
current_length -= MAX_SIZE;
}
printf("Counter: %d = ", counter++);
for (int i = 0; i < current_length; i++) {
printf("%d ", data[index++]);
}
printf("\n");
Output Error When include file included twice
I would like to trap sloppy programming by outputting an error when some include files are included twice.
I use #pragma once for include files that intend to include within other include files. That works great.
I know I can do a variation of "guard macros" to accomplish this. But is there a better way? Another #pragma or a gcc compile option?
This is a sample of a guard macro:
#ifndef FILE_FOO_SEEN
#define FILE_FOO_SEEN
the entire file
#endif /* !FILE_FOO_SEEN */
This would work for me:
#ifdef FILE_FOO_SEEN
#error "FILE_FOO inappropriately included twice.
#endif /* FILE_FOO_SEEN */
#define FILE_FOO_SEEN
/* Active Code */
[edit] Note: I am not asking for why it is necessary to support including header files multiple times. That is a common case and supported with the a gcc pragma. I am asking for the case when I have specific include files that I do not want included more than once. If someone were to include them more than once, then it would be one of two actions: 1) Change the trap to a #pragma once, or 2) change the code to eliminate the dependency.
Because there is a special pragma to support multiple include, I thought someone might have good techniques to avoid this as well.
the code is working but is it c99 compatible?
the while loop is not working here.there is no compilation error and the print statement is also getting executed in the beggining.the code works fine without the while loop.the code is to print the most repeating letter in a string and the number of times it is repeated
#include <stdio.h>
#include <string.h>
int main(void)
{
int t;
scanf("%d",&t);
int tempC;
while ( (tempC = getchar()) != '\n' && tempC != EOF );
while(t--)
{
char c[100];
char r='z';
int i,j=0,count,a,k,amx;
gets(c);
k=strlen(c);
for(i=0,amx=1;i<k;i++)
{
if(c[i]!=0)
{
for(j=0,count=1;j<k;j++)
{
if(c[i]==c[j])
{
if(i!=j)
{
count++;
c[j]=0;
}
a=count;
if(a>amx||(a==amx&&(c[i]<r)))
{
amx=a;
r=c[i];
}
}
}
}
}
printf("%d %c\n",amx,r);
}
}
Branch "anticipation" in modern CPUs
I was recently thinking about branch prediction in modern CPUs. As far as I understand, branch prediction is necessary, because when executing instructions in a pipeline, we don't know the result of the conditional operation right before taking the branch.
Since I know that modern out-of-order CPUs can execute instructions in any order, as long as the data dependencies between them are met, my question is, can CPUs reorder instructions in such a way that the branch target is already known by the time the CPU needs to take the branch, thus can "anticipate" the branch direction, so it doesn't need to guess at all?
So can the CPU turn this:
do_some_work();
if(condition()) //evaluating here requires the cpu to guess the direction or stall
do_this();
else
do_that();
To this:
bool result = condition();
do_some_work(); //bunch of instructions that take longer than the pipeline length
if(result) //value of result is known, thus decision is always 100% correct
do_this();
else
do_that();
A particular and very common use case would be iterating over collections, where the exit condition is often loop-invariant(since we usually don't modify the collection while iterating over it).
My question is can modern generally CPUs do this, and if so, which particular CPU cores are known to have this feature?
Fopen file with dir name in Mint with C
I am using
FILE *fp = fopen("pasta/test.txt",w);
but this line doesn´t create a file in folder "pasta", i am creating a file with name "pasta/test.txt", can you help me?
How to use a library with headers and .so files?
I'm new to C and wanted to use a library (mlt framework)
I've built it and it produced the following directories: include lib share
Inside lib there are .so .a .la files
Inside include there are .h files
Now, I'm instructed to do this:
#include <framework/mlt.h> which is inside include/mlt/framework/
Questions:
- Why I do I need to place the header file that contains only function prototypes? are they linked someway to the ones included in
libdirectory? - Where to place my own files and how to compile it?
- How to learn more about the topics:
- Dynamic/Static libraries
- Building / making / installing
- How to use any C library
fixed amount of renders per second with a fixed logic update per second
I read the gaffer article on fix your tilmestep and also dewitters about fixed frame render rate.
I agree with both parts, I think choosing a desired frame rate and locking it locking the frame rate at 24, 30, 60 or even 120 at the beginning of the project and then working within those limitations would be ideal.
I also think that making those same decisions at the beginning for the logic loop as well.
So let's say you want to target having an update loop that runs 1/24 and a rendering loop that runs at a constant 1/30.
I was trying to combine both articles to create a game loop that would work and I hope that I can get some feedback. Here's my code below:
double logicTime = 0.0;
const logicDt = 1/120.0;
double currLogicTime = 0.0; //get time in seconds
double LogicAccum = 0.0;
int ftps = 30;
int fpsSkipTicks = 1000/ftps;
int maxFrameSkips = 5;
double nextFtps = 0.0 //get time in seconds
int loops;
float interpolation;
while(game_running)
{
double newLogicTime = 0.0; //get time in seconds
double frameLogicTime = newLogicTime - currTime;
currLogicTime = newLogicTime;
LocgicAccum += frameLogicTime;
while(LocgicAccum >= logicDt)
{
//update core game logic here with fixed steps
LogicAccum -= logicDt;
logicTime += logicDt;
}
//can also update none essential things here such as background animations, particles, etc.
loops = 0;
while( /* get time in milliseconds */ > nextFtps && loops < maxFrameSkips) {
nextFtps += fpsSkipTicks;
loops++;
}
interpolation = float( /* get time in milliseconds */ + fpsSkipTicks - nextFtps ) / float( SKIP_TICKS );
//render here with interpolation so that I can multiply the objects position based on the interpolation value
render( interpolation );
}
As you can see there are two distinct loops inside the main loop. One updates logic at a fixed rate and another updates the renderer also at a fixed time.
Develop a File chooser UI in Turbo C [on hold]
Please help me develop a File chooser application in Turbo C. It is something similar to the 'open...' option available in Turbo C itself.
Compare two files in C, one file format is fixed and input files must have same format but different contents
<School>
</SchoolName>latha2 //skip, but keep
</School>
<Student>
<Team>power //skip,but keep
<StudentNo>1 //skip
<Sport>
<StartDate>16122016</StartDate> //*skip(May or maynot contained)
<SportType>All
<ExpiryDate>16122020</EndDate> //*skip (May or maynot contained)
</Sport>
<Personal>
<phone>50855466 //skip,but keep
<rollno>6 //skip,but keep
</Personal>
<hobby> //skip
</Student>
Note: There are 4 <Student> tags.
- Assume that File1 is fixed and File2 is input-file. In File 1,one school with 4 students. In File 2,there are many schools but have to check with File-1 format repeatedly according to the number of schools it has. Above is an example of File1.
"Scenario" - There are 4 package of "Student" tags in one school. In each tags, the value of "Team" are repeated.
"Questions with restrictions"
- From File 1,"Sport" Tag, "StartDate" and "ExpiryDate" are defined but they may not be contained in every "School" from File2.
- If they are defined, how to verify that they should be at the correct line?.
- How to verify that format is right even they are not defined in some schools of File2?
- Some lines are skipped when 2 files are compared but some lines need to be collected form File2 to write a new txt even they are skipped. From File2, "SchoolName", "Team","phone" and "roll no" are retrieved and write txt altogether line by line. ****Important, retrieve "Team" once from one "School". Because it is repeated 4 times in four "Student" from same "School".
- How to retrieve only SchoolName,Team,Phone,RollNo among the skipped lines?
- How to retrieve only Team in writing new textfile even it is duplicated in students under one school?
Two things to be done. 1. Match File Format 2.New Text with specific values
"Example of new text"
latha2 // SchoolName
power // Team
5035546 // phone - student1
6 // rollno - student1
5089973 // phone - student2
5 // rollno - student2
5402734 // phone - student3
1 // rollno - student3
8540345 // phone - student4
2 // rollno - student4
how to define repeated field as required in google protocol buffer?
how to define repeated field as required in Google protocol buffer?I have a field that modifier is repeated(repeated int32 A ).How i add required modifier to this field? in fact i want to have both modifier(required and repeated).
white and the shadow forces in galaxy [on hold]
A war has been started between the White and the Shadow forces in the galaxy. The galaxy is considered to be a single dimensional infinite stretch on both sides. Only one force can attack the other at a time. The first one to attack are the White forces and the alternating turns continue. White have mobility of mw and shadow have mobility of ms. In each turn both the forces can move upto their mobility. (Ex. If a force is located at location 0 and have mobility of 10, then in its next turn it can move from -10 to 10 location.) Both the forces have their own attacking range described as aw and as respectively. In each turn after making the move, the force can attack the other force if it is in the attacking range of the force. (Ex. If the force with mobility of 5 is located at location 0 and has range of 10 while its enemy is at 15, it can attack its enemy in its turn by first moving to location 5 and then attacking). Given the initial distance between the two forces D, find if White forces will win or Shadow forces will win or the battle would not be concluded if both play optimally. Note that the force can attack in the same turn after making its move.
When using IBO/EBO, program only works when I call glBindBuffer to bind the IBO/EBO AFTER creation of the VAO
For some reason, this program only works when I bind the IBO/EBO again, after I create the VAO. I read online, and multiple SO posts, that glBindBuffer only binds the current buffer, and that it does not attach it the the VAO. I thought the glVertexAttribPointer is the function that attached the data to the VAO.
float points[] = {
-0.5f, 0.5f, 0.0f, // top left = 0
0.5f, 0.5f, 0.0f, // top right = 1
0.5f, -0.5f, 0.0f, // bottom right = 2
-0.5f, -0.5f, 0.0f, // bottom left = 3
};
GLuint elements[] = {
0, 1, 2,
2, 3, 0,
};
// generate vbo (point buffer)
GLuint pb = 0;
glGenBuffers(1, &pb);
glBindBuffer(GL_ARRAY_BUFFER, pb);
glBufferData(GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW);
// generate element buffer object (ibo/ebo)
GLuint ebo = 0;
glGenBuffers(1, &ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);
// generate vao
GLuint vao = 0;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, pb);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); // when I bind buffer again, it works
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
If I did not have the second glBindBuffer, the program crashes. All I want to know is why I have to call glBindBuffer again, after I create the VAO, when calling glBindBuffer only makes the buffer the active buffer for other functions.
Trouble using Functions for Hangman game in C
I am trying to make a hangman gave using C Functions. I was able to make the game without using functions but now when i try to use functions i am running into a few problems.
The main problem i am having is in my displayWord() function. I need this function to print out the word to screen with all letters that have not been correctly guessed blanked out with an underscore.
~Header FiIles
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Constants. */
#define NUM_WORDS 50
#define ALPHABET_SIZE 26
#define GOOD_GUESS 0
#define BAD_GUESS 1
#define GAME_OVER 1
#define GAME_CONTINUE 0
#define MAX_GUESS 10
#define MAX_WORD_LEN 10
/* Function prototypes. */
int init(char* word);
void displayWord(char* word, int* guessedLetters, int* length);
int guessLetter(char* word, int* guessedLetters);
void displayHangman(unsigned wrongGuesses);
int isGameOver(char* word, int* guessedLetters, unsigned wrongGuesses);
void readRestOfLine();
~Main Code
#include "hangman.h"
/****************************************************************************
* Function main() is the entry point for the program.
****************************************************************************/
int main(void)
{
char word[MAX_WORD_LEN + 1];
unsigned wrongGuesses = 0;
int guessedLetters[ALPHABET_SIZE] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
};
int length = 0;
int numLives = 10;
int numCorrect = 0;
int oldCorrect = 0;
int lengthOfWord = 0;
length = init(word);
printf("length: %d\n", length);
displayWord(word, guessedLetters, length);
return EXIT_SUCCESS;
}
int init(char* word)
{
srand(time(NULL));
int randomIndex = rand() % 50;
const char* words[NUM_WORDS] = {
"array", "auto", "break", "case", "cast",
"character", "comment", "compiler", "constant", "continue",
"default", "double", "dynamic", "else", "enum",
"expression", "extern", "file", "float", "function",
"goto", "heap", "identifier", "library", "linker",
"long", "macro", "operand", "operator", "pointer",
"prototype", "recursion", "register", "return", "short",
"signed", "sizeof", "stack", "statement", "static",
"string", "struct", "switch", "typedef", "union",
"unsigned", "variable", "void", "volatile", "while"
};
word = words[randomIndex];
int lengthOfWord = strlen(words[randomIndex]);
printf("Word: %s\n", words[randomIndex]);
return lengthOfWord;
}
void displayWord(char* word, int* guessedLetters, int* length)
{
int loopIndex;
char gameWord[][1] = word;
for ( loopIndex = 0; loopIndex < length; loopIndex++ ) {
if(letterGuessed[loopIndex] == 1) {
printf("%c",gameWord[0][loopIndex]);
} else {
printf("-");
}
}
}
I have no idea how to scan through my random word to print out the letters that have been guessed. I have tried a few different way from reading around the web and watching videos but i am really not sure. Please help.
Problem Code
void displayWord(char* word, int* guessedLetters, int* length)
{
int loopIndex;
char gameWord[][1] = word;
for ( loopIndex = 0; loopIndex < length; loopIndex++ ) {
if(letterGuessed[loopIndex] == 1) {
printf("%c",gameWord[0][loopIndex]);
} else {
printf("-");
}
}
}
How to read csv file 2D array using C
Below mentioned is my file
usertype userid name 1 0001 conductor 2 0001 driver
please give me a solution for this.Thank you in advance
Can you explain why I get 2 different results passing the same structure in Objective-C?
Have been struggling with this so hope people can help me. Suppose I have defined following structure
struct _SParticleEffect
{
enumParticleTypes type;
int count;
GLKVector3 initialPos;
GLKVector3 direction;
float triggerRadius;
CGSize prtSize;
float prtclSpeedMax;
float prtclSpeedInitial;
float prtclLifeMax;
GLKVector4 color;
};
typedef struct _SParticleEffect SParticleEffect;
Then I make an instance of this structure and pass it to single function in two ways - pointer and by value:
- (void) InitGeometry
{
SParticleEffect splashEffect;
splashEffect.count = 15;
[splashPrt TestFunc: &splashEffect : splashEffect];
}
//test function with 2 parameters - by pointer and by value
//method of splashPrt
- (void) TestFunc: (SParticleEffect*) attrPointer: (SParticleEffect) attr
{
NSLog(@"1: %d", attrPointer->count);
NSLog(@"2: %d", attr.count);
}
And this is the result I get
2015-07-01 16:58:28.766 [1738:707] 1: 15
2015-07-01 16:58:28.770 [1738:707] 2: 804245704
As you can see it seems like in second case 'count' is lost. The worst part is that this result is not consistent, because if I put this count parameter as first parameter of structure then in both cases result is 15. Can you explain to me why this is or tell some way to try to debug it?
How can I pass a single pointer to a structure, inside a function and modify that structure variable?
In the below piece of code, I am able to modify the a variable used in main from the function.
#include<stdio.h>
int main()
{
int *a,b=10;
a = &b;
printf("%d\n",*a);
ref(a);
printf("%d\n",*a);
return 1;
}
int ref(int *a)
{
int b = 98;
*a = b;
return 1;
}
whereas, in the below piece of code, I couldnot able to do the same.
I know that we can modify a value which is in the main, from a function by using double pointer. I also know that we can use single pointer to modify, by returning the required address to the main and getting it in the main with the same data type. I just wanted to know whether I can modify a value in the main by passing it as a parameter to the function, only as a single pointer to the (structure) variable.
Note: I have denoted the working code with the comment '//WC'. Will be very thankful if someone can explain me the same.
//int insert(int data, Node **head) //WC
int insert(int data, Node *head)
{
Node *temp, *run;
temp = (Node *) malloc(sizeof(Node));
temp->data = data;
temp->next = NULL;
//if(*head == NULL) //WC
if(head == NULL)
{
printf("1st node\n");
//*head = temp; //WC
*head = *temp;
}
else
{
printf("node after first\n");
//run = *head //WC
*run = *head;
while(run->next != NULL)
{
run = run->next;
}
run->next = temp;
}
return 1;
}
int main()
{
Node *head;
insert(10, head);
insert(20, head);
insert(30, head);
insert(40, head);
insert(50, head);
return 1;
}
How does `if(!found)` in this function work?
This function finds the first and last occurrence of an integer in an array. I don't understand what the second if statement does if(!found) is it the same as saying if(found==0)? How does the second statement 'find' the first occurrence? Lets say if there are 3 4's in an array the loop finds the last occurrence and sets it to plast and than it goes into the 2nd if statement how does it know to find the first occurrence and not the 2nd occurrence?
find_occurences(const int a[], size_t n, int x, size_t *pfirst, size_t *plast) {
size_t i;
int found = 0;
for (i=0; i<n; i++)
{
if (a[i] == x)
*plast = i;
foundlast = 0;
if (!found)
{
*pfirst = i;
found = 1;
}
}
}
Passing C++ character array to Fortran
I have been trying to pass a character array from C++ to a Fortran subroutine but it seems like Fortran does not receive characters properly. I have been searching the web to find a solution but proposed ideas seem to be too complicated. An interesting (and concise) solution was proposed by Steve at Intel Fortran Forum but I cannot get it work in my code. So, I appreciate any suggestion to help me out to resolve this issue.
The following function is my C++ routine that makes call to fortran subroutines:
extern "C" void __stdcall F_VALIDATE_XML(const char* buffer, int len);
void CUDMEditorDoc::OnValidateXML()
{
CString fileName = "test.udm";
const char* buffer = fileName.GetBuffer();
int len = fileName.GetLength();
F_VALIDATE_XML(buffer, len);
}
And here is the Fortran subroutine that is supposed to receive character array:
subroutine validate_xml(file_name, len)
!DEC$ ATTRIBUTES DECORATE, STDCALL, ALIAS:"F_VALIDATE_XML" :: validate_xml
use xml_reader_structure
use, intrinsic :: ISO_C_Binding
integer(C_INT), value, intent(in) :: len
character(len, kind=C_CHAR), intent(in) :: file_name
integer :: i
i = 1
end subroutine validate_xml
In debug mode and when the program has stopped at line (i = 1), I hover mouse over file_name to see its contents but the Watch window says that it cannot find file_name symbol (although len is correctly passed). Also, if I watch file_name(1:8) in watch window, still I don't get the original character arrays. I believe there is something wrong with the way I pass parameters to Fortran but chances are Watch Window is not correct.
I appreciate any help that could shed some lights here. Thanks
io_submit() blocks until a previous operation will be completed
I'm using the Linux kernel AIO through libaio, and I have to submit the next reading operation before the previous one was completed. The problem is that io_submit() blocks for some time and, as I can deduce from the interval, it waits the previous operation to be completed.
I know that I can enqueue a several operations with a single io_submit(), but it is not an option for me, because I don't know how exactly the next read operation would like when it's already a time to submit the first one.
Is it working like that only for me, or for everyone? In the second case, may I ask if I'm looking for something feasible, or I have to fallback to a threaded model?
Generic Linked List in C with run time data types [on hold]
I want to create a linked list which can accept any data type at run time and display the list. The problem is display function and memory management changes for different data types. So I don't know how to do that. Code examples will be appreciated. Edit: to narrow down the problem. this is queue structure(using linked list)
struct node
{
void *data;
struct node *link;
};
struct queue
{
struct node *front;
struct node *rear;
};
unsatisfied link error in java native programming
I am trying to build my first native program in java.The .c and .h file compiled well but when running java code I get this error. Here are my java and c source file
Main.java
public class Main{
public native void sayHello();
static{
System.loadLibrary("hello");
}
public static void main(String[] args) {
Main main = new Main();
main.sayHello();
}
}
Hello.c
#include <jni.h>
#include "stdio.h"
#include "Main.h"
JNIEXPORT void JNICALL Java_Main_sayHello
(JNIEnv *env, jobject obj)
{
printf("Hello World \n");
return;
}
.C file compilation
C:.../gcc -I"C:\Program Files\Java\jdk1.7.0_79\include"
-I "C:\Program Files\Java\jdk1.7.0_79\include\win32" -o hello.dll -shared Hello.c
Running Java File
C:.../javac Main.java
C:.../java Main
Exception in thread "main" java.lang.UnsatisfiedLinkError: Main.sayHello()V
at Main.sayHello(Native Method)
at Main.main(Main.java:8)
Sending qsub command through system
I have the below code where I want to send qsub command using system("qsub"). The problem is I can't send this command to the dynamically created directories. However, I can send it to the manually created directory.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <zlib.h>
main(){
const char *a[5];
int i, j ,k, ii, jj, kk;
char str[256];
FILE *fp, *source, *target, *fp1;
char ch[300];
char str1[256];
char sbuff[300];
printf("Start Here ...\n");
a[0] = "submit.sh";
a[1] = "run.prm";
a[2] = "name.txt";
a[3] = "prot.pdb";
a[4] = "step2_out.pdb";
for (i=1;i<6;i++){
sprintf(str,"_%d", i);
mkdir(str, 0755); // Create temporary directories
for (j=0;j<5;j++){
sprintf(str,"%s", a[j]);
source = fopen(str, "r");
if( source == NULL )
{
printf("Error in doStepOneAndTwo, can't open file source \n");
return -1;
}
sprintf(str,"_%d/%s", i, a[j]);
target = fopen(str, "w+");
if( target == NULL )
{
fclose(source);
printf("Error in doStepOneAndTwo, can't open file target %s \n",str);
return -1;
}
while( (fgets(ch, sizeof(ch), source))) {
if (j == 1){
if (strstr(ch, "(DO_PREMCCE)")){
ch[0] = 'f';
}
else if (strstr(ch, "(DO_ROTAMERS)")){
ch[0] = 'f';
}
else if (strstr(ch, "(DO_MONTE)")){
ch[0] = 'f';
}
else if (strstr(ch, "(DELPHI_STEP)")){
ch[0] = 'f';
}
fputs(ch, target);
}else {
fputs(ch, target);
}
}
}
sprintf(str1,"chmod +x _%d/submit.sh", i);
system(str1);
// Submiting the jobs
if (getcwd(sbuff, sizeof(sbuff)) != NULL)
printf("Current working dir 1: %s\n", sbuff);
else
printf("getcwd() error");
sprintf(str,"_%d/", i);
chdir(str);
system("qsub submit.sh"); // This line doesn't works, the above directories are dynamically created (str)
chdir(sbuff);
}
// Submit the job
chdir("1l2y");
system("qsub submit.sh"); // This line works, the above directory is manually created (1l2y)
chdir(sbuff);
return 0;
}
The error I get "Unable to run job: job rejected: no script in your request." However, if I change my command from system("qsub submit.sh") to system("rm *") everything works just fine. I don't know why I can't send this command to the dynamically created directories.
Search One array elements in another array in java [duplicate]
This question already has an answer here:
I have two Arrays for example
int a[]={1,2,3,4,5,6} int b[]={9,8,7,8,1,15,2,25,6}
I want search elements of a[] in b[] and return all common elements in another array temp[]
what is wrong with this code?i am unable to find what is wrong with this code?
i am trying to convert infix notation to postfix notation using stack.i have written the following code but it is giving me error(/Users/apple/Desktop/infix.c|49|error: expected expression ).and i am unable to find the error.please help me to correct this code....
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
#define MAX 100
char st[MAX];
int top=-1;
void push(char st[],char);
char pop(char st[]);
void InfixtoPostfix(char source[],char target[]);
int getPriority(char);
int main() {
char infix[100],postfix[100];
printf("enter any infix expression");
fflush(stdin);
gets(infix);
strcpy(postfix,"");
InfixtoPostfix(infix,postfix);
printf("\n the corrsponding postfix expression is:");
puts(postfix);
return 0;
}
void InfixtoPostfix(char source[],char target[])
{
int i=0,j=0;
char temp;
strcpy(target,"");
while(source[i]!='\0')
{
if(source[i]=='(')
{
push(st,source[i]);
i++;
}
else if(source[i]==')')
{
while((top!=-1)&&(st[top]!='('))
{
target[j]=pop(st);
j++;
}
if(top==-1)
{
printf("\n incorrect syntex");
exit(1);
}
temp=pop(st);
i++;
else if((isdigit(source[i]))||(isalpha(source[i]))
{
target[j]=source[i];
j++;
i++;
}
else if(source[i]=='+'||source[i]=='- '||source[i]=='*'||source[i]='/'||source[i]=='%d')
{
while((top!=-1)&&(st[top]!='(')&&(getPriority(st[top])>getPriority(source[i])))
{
target[j]=target[i];
i++;
}
push(st,source[i]);
i++;
}
else{
printf("\n incorrect expression");
exit(1);
}
}
while((top!=-1)&&(st[top]!='('))
{
target[j]=pop(st);
j++;
}
target[j]='\0';
}
}
int getPriority(char op)
{
if(op=='/'||op=='*'||op=='%'||op=='%')
return 1;
else if(op=='+'||op=='-')
return 0;
}
void push(char st[],char val)
{
if(top==MAX-1)
printf("overflow");
else{
top++;
st[top]=val;
}
}
char pop(char st[])
{
char val=' ';
if(top==-1)
printf("underflow");
else{
val=st[top];
top--;
}
return val;
}
changing variable value from within a function
I'm writing a program in c in which I need to change the value of a variable from within a function. I've tried setting the variable globally but it was not recognized withinn the function so I tried the following: the variable is nobuttons:
readconfig(config2,&nobuttons);
void readconfig(FILE *config, int *buttons)
{
buttons=5;
}
when I print the value of buttons, it's shown as 0(the value it was initialized to)
what am I doing wrong? thanks
Implementing a c function callback in Swift 2.0?
CFReadStreamSetClient has a C-function callback (CFReadStreamClientCallBack) in it's initializer,
CFReadStreamClientCallback looks like this:
typealias CFReadStreamClientCallBack = (CFReadStream!,
CFStreamEventType, UnsafeMutablePointer<Void>) -> Void
I have a method that attempts to handle the CFReadStreamClientCallBack C-function callback:
func callback(stream: CFReadStreamRef,
eventType: CFStreamEventType,
inClientInfo: UnsafeMutablePointer<Void>) {
}
but when i attempt to set the callback in CFReadStreamCallback as follows, it doesn't compile.
CFReadStreamSetClient(stream, registeredEvents, callback, clientContextPtr)
I know with Swift 2.0 there's a way to use Swift closures with C-Function callbacks but I cant seem to get it to work. Does anyone know how it can be done in this situation?
Why do function names that are not part of the implementation still use the double underscore naming convention?
Aren't double underscores reserved for the implementation? I'm referring to something like this. People seem to ignore this convention all the time.
Here's the code:
signed int __cdecl upload_exploit() {
int device_type;
signed int payload_address;
int free_address;
int deviceerror;
char *chunk_headers_ptr;
...
Here is where the convention is defined:
In addition to the names documented in this manual, reserved names include all external identifiers (global functions and variables) that begin with an underscore (‘_’) and all identifiers regardless of use that begin with either two underscores or an underscore followed by a capital letter are reserved names. This is so that the library and header files can define functions, variables, and macros for internal purposes without risk of conflict with names in user programs.
Infinite loop when simplifying fractions in binary in C
I'm trying to simplify fractions in binary with this code that checks if the value is even:
int is_even(floatlet value){
if(value & 1) return 0;
return 1;
}
And this while loop keeps bit shifting until the value is odd.
while(is_even(numerator) && is_even(denomExp)){
numerator >>= 1;
denomExp <<= 1;
}
The while loop goes on an infinite loop. I'm wondering why? We've done test and the is_even function works fine. Thanks!
PN532 Target Emulation
I'm attempting to use a PN532 chip to emulate an NFC target (eg. Mifare Classic) without the use of libnfc. The implementation occurs on an Arduino system, so I want to be as succinct as possible. The desired target type is NMT_ISO14443A.
An initiator seems to be able to recognize a target without exchanging C/APDU. Can anyone explain how is this achieved?
What is EOF and what is its significance? How can it be noticed?
While studying getchar() function in C ,I came across this EOF being returned , I want to know how can its existence be noticed, where is it stored?
Can we type EOF character explicitly?
int produces near correct answer, but float just gives -18.000
I wrote a simple program to convert degrees Fahrenheit to degrees Celsius using functions (been working w/ Python for 2 weeks, wanted to refresh myself):
#include <stdio.h>
#include <math.h>
int temp_change(fahrenheit);
int main()
{
while(1)
{
int fahrenheit;
printf("Please input a temperature in Fahrenheit.\n");
scanf("%d", &fahrenheit); //Obtains degrees F value
printf("%d\n", temp_change(fahrenheit));
}
}
//Function to change temperature
int temp_change(fahrenheit)
{
int centigrade;
centigrade = 5*(fahrenheit - 32)/9; //Changing the temperature
return centigrade;
}
and it gave me correct answers (to the nearest degree). However, I wanted exact answers, so I changed all the ints to floats (except for int main(). Now the only thing the program will give me is -18.000000, no matter what input I give it. The best way to summarize what I tried: I tried different combinations of the ints and the floats but with no luck. I would suspect that it had something to do with printf("%d\n", temp_change(fahrenheit)); but it gave me correct answers when everything was int, so I don't know. XD Thanks in advance for any help!
What is an intuitive way to interpret the bitwise operators and masking? Also, what is masking used for?
I'm learning about bitwise operators and masking right now in my computer systems class. However I'm having some trouble internalizing them.
I understand what the operators, &, |, ^, >> (both arithmetic and logical shift), and << DO, but I don't quite get what they're really used for aside from optimizing multiplication and division operations (for >> and <<), and to check if certain bits are on or off (the & operator).
Also, I don't understand what masking is used for. I know that doing x & 0xFF is used to extract the least significant bit in an integer x, but I can't really extrapolate from that to how other kinds of masks (e.g. those that extract the leftmost 1 in a number, that obtain the number of 1s in a number, etc.) are used?
Could anyone please shed some light on this, preferably with some examples? Thank you.