language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#ifndef _SETUIDGID_H_ #define _SETUIDGID_H_ /* How should we treat supplementary groups? */ enum { SETUIDGID_SGROUP_IGNORE = 0, SETUIDGID_SGROUP_LEAVE_WARN, SETUIDGID_SGROUP_LEAVE_ERROR }; /** * setuidgid(user_group_string, leave_suppgrp): * Set the UID and/or GID to the names given in ${user_group_string}. If no * UID or GID can be found matching those strings, treat the values as numeric * IDs. Depending on the existence and position of a colon ":", the behaviour * is * - no ":" means that the string is a username. * - ":" in the first position means that the string is a groupname. * - otherwise, the string is parsed into "username:groupname". * * The behaviour with supplementary groups depends on ${leave_suppgrp}: * - SETUIDGID_SGROUP_IGNORE: do not attempt to leave supplementary groups. * - SETUIDGID_SGROUP_LEAVE_WARN: attempt to leave; if it fails, give a * warning but continue. * - SETUIDGID_SGROUP_LEAVE_ERROR: attempt to leave; if it fails, return * an error. */ int setuidgid(const char *, int); #endif /* !_SETUIDGID_H_ */
C
#include <stdio.h> long long callRetInt(long long a); long long callRetPtr(long long a); long long callParaInt(long long a); long long callParaPtr(long long a); int main(__attribute__((unused)) int argc, __attribute__((unused)) char **argv) { long long fail = 0; long long a = 10; //printf("positive:\n"); // return a if(callRetInt(a)!=a){ printf("callRetInt does not pass the test\n"); fail++;} if(callRetPtr(a)!=a){ printf("callRetPtr does not pass the test\n"); fail++;} if(callParaInt(a)!=a){ printf("callParaInt does not pass the test\n"); fail++;} if(callParaPtr(a)!=a){ printf("callParaPtr does not pass the test\n"); fail++;} a = -10; // printf("negative:\n"); // return a if(callRetInt(a)!=a){ printf("callRetInt does not pass the test\n"); fail++;} if(callRetPtr(a)!=a){ printf("callRetPtr does not pass the test\n"); fail++;} if(callParaInt(a)!=a){ printf("callParaInt does not pass the test\n"); fail++;} if(callParaPtr(a)!=a){ printf("callParaPtr does not pass the test\n"); fail++;} if(fail == 0) printf("Success!\n"); return 0; }
C
#include <stdio.h> int main(void) { int a1,a2; scanf("%d %d",&a1,&a2); a1=a1^a2; a2=a1^a2; a1=a1^a2; printf("%d %d",a1,a2); return 0; }
C
/* ** EPITECH PROJECT, 2018 ** PSU_42sh_2017 ** File description: ** Returns a char ** with the segmented path */ #include <stdlib.h> static int get_nb_seg(char *path) { int nb = 0; int i = 0; while (path && path[i]) { if (path[i] == ':') nb++; i++; } if (path && path[i] == '\0') nb++; return (nb); } static unsigned int size_next_path(char *path) { unsigned int i = 0; while (path && path[i] && path[i] != ':') { i++; } return (i + 1); } static char *get_seg_path(char *path, int *a) { char *seg = malloc(sizeof(char) * size_next_path(path + *a)); int i = 0; if (seg == NULL) return (NULL); seg[0] = '\0'; while (path && path[*a] && path[*a] != ':') { seg[i] = path[*a]; i++; (*a)++; seg[i] = '\0'; } if (path && path[*a] && path[*a] == ':') (*a)++; return (seg); } char **my_seg_path(char *path) { char **seg_path = NULL; int nb_seg = get_nb_seg(path); int a = 0; seg_path = malloc(sizeof(char *) * (nb_seg + 1)); if (seg_path == NULL) return (NULL); for (int i = 0; i < nb_seg && path[a]; i++) { seg_path[i] = get_seg_path(path, &a); seg_path[i + 1] = NULL; } return (seg_path); }
C
/* * kernel/driver/rtc.c * * MediOS project * Copyright (c) 2005 by Christophe THOMAS (oxygen77 at free.fr) * * All files in this archive are subject to the GNU General Public License. * See the file COPYING in the source tree root for full license agreement. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express of implied. */ /********************************************** Driver for the STMicroelectronics chip (M41ST84W and similar) it implements standard functions to read/write time/date from the RTC **********************************************/ #include <sys_def/errors.h> #include <kernel/kernel.h> #include <driver/hardware.h> #include <driver/i2c.h> #include <driver/rtc_ST.h> #include <driver/time.h> /* structure representing time for ST chip*/ struct tm_pv { unsigned char tm_ms; unsigned char tm_sec; unsigned char tm_min; unsigned char tm_hour; unsigned char tm_wday; unsigned char tm_mday; unsigned char tm_mon; unsigned char tm_year; }; /* conversion Macro: ST chip uses hex representation of dec: 0x22 from chip is in fact 22 not 34*/ #define pvToUser(val) ((((val>>4)&0xF)*10)+(val&0xF)) #define userToPv(val) ((((val/10)<<4)&0xf0)+((val%10)&0x0F)) /* Macro that put a data in ST chip, print an error if one occurs */ #define sendRTC(addr,val) {int __ret;int __val=val; __ret=i2c_write(RTC_DEVICE, addr, (void*)(&__val), 1); \ if(retVal<0) printk("[I2C - rtc] Error, writting (err:%d)\n",retVal);} MED_RET_T rtc_getTime(struct med_tm * valTime) { struct tm_pv pv_dt; int retVal; retVal=i2c_read(RTC_DEVICE, 0, (void*)(&pv_dt), 8); if(retVal<0) { printk("[I2C - rtc] Error, reading (err:%d)\n",retVal); return retVal; } pv_dt.tm_wday&=0x7; valTime->tm_ms=pvToUser(pv_dt.tm_ms); valTime->tm_sec=pvToUser(pv_dt.tm_sec); valTime->tm_min=pvToUser(pv_dt.tm_min); valTime->tm_hour=pvToUser(pv_dt.tm_hour); valTime->tm_mday=pvToUser(pv_dt.tm_mday); valTime->tm_mon=pvToUser(pv_dt.tm_mon); valTime->tm_year=2000+pvToUser(pv_dt.tm_year); valTime->tm_wday=pvToUser(pv_dt.tm_wday); //valTime->tm_wday=time_getDayOfWeek(valTime->tm_mday,valTime->tm_mon,valTime->tm_year); return MED_OK; } MED_RET_T rtc_setTime(struct med_tm *newTime) { struct tm_pv pv_dt; struct tm_pv pv_dt_ini; int year; int wday; int retVal; retVal=i2c_read(RTC_DEVICE, 0, (void*)(&pv_dt_ini), 8); if(retVal<0) { printk("[I2C - rtc] Error, reading (err:%d) can't save the value\n",retVal); return retVal; } year=newTime->tm_year-2000; pv_dt.tm_ms=userToPv(newTime->tm_ms); pv_dt.tm_sec=userToPv(newTime->tm_sec); pv_dt.tm_min=userToPv(newTime->tm_min); pv_dt.tm_hour=userToPv(newTime->tm_hour); pv_dt.tm_wday=userToPv(newTime->tm_wday); pv_dt.tm_mday=userToPv(newTime->tm_mday); pv_dt.tm_mon=userToPv(newTime->tm_mon); pv_dt.tm_year=userToPv(year); /* only writting h,m,s and d,m,y */ wday=time_getDayOfWeek(newTime->tm_mday,newTime->tm_mon,newTime->tm_year); pv_dt.tm_ms=0; pv_dt.tm_sec=RTC_MK_S(pv_dt_ini.tm_sec,pv_dt.tm_sec); pv_dt.tm_min=RTC_MK_M(pv_dt_ini.tm_min,pv_dt.tm_min); pv_dt.tm_hour=RTC_MK_H(pv_dt_ini.tm_hour,pv_dt.tm_hour); pv_dt.tm_wday=(wday&0x7); pv_dt.tm_mday=RTC_MK_DM(pv_dt_ini.tm_mday,pv_dt.tm_mday); pv_dt.tm_mon=RTC_MK_MO(pv_dt_ini.tm_mon,pv_dt.tm_mon); pv_dt.tm_year=RTC_MK_Y(pv_dt_ini.tm_year,pv_dt.tm_year); retVal=i2c_write(RTC_DEVICE, 0, (void*)(&pv_dt), 8); if(retVal<0) { printk("[I2C - rtc] Error, writting (err:%d)\n",retVal); return retVal; } return MED_OK; } MED_RET_T rtc_init(void) { unsigned char cb; int retVal; int cwd; struct med_tm valTime; if((retVal=i2c_read(RTC_DEVICE, 0x04, (void*)&cb, 1))<0) { printk("[I2C-rtc-ini] Step 0: Error, reading (err:%d)\n",retVal); return -1; } if(cb & 0x80) { cb&= ~0x80; if((retVal=i2c_write(RTC_DEVICE, 0x04, (void*)&cb, 1))<0) { printk("[I2C-rtc-ini] Step 1: Error, writting (err:%d)\n",retVal); return -1; } } /* Clear the Stop bit if it is set */ if((retVal=i2c_read(RTC_DEVICE, 0x01, (void*)&cb, 1))<0) { printk("[I2C-rtc-ini] Step 2: Error, reading (err:%d)\n",retVal); return -1; } if(cb & 0x80) { cb&= ~0x80; if((retVal=i2c_write(RTC_DEVICE, 0x01, (void*)&cb, 1))<0) { printk("[I2C-rtc-ini] Step 3: Error, writting (err:%d)\n",retVal); return -1; } } if((retVal=i2c_read(RTC_DEVICE, 0x0c, (void*)&cb, 1))<0) { printk("[I2C-rtc-ini] Step 4: Error, reading (err:%d)\n",retVal); return -1; } if(cb & 0x40) { cb &= ~0x40; // Make sure HT bit is not set if((retVal=i2c_write(RTC_DEVICE, 0x0c, (void*)&cb, 1))<0) { printk("[I2C-rtc-ini] Step 5: Error, writting (err:%d)\n",retVal); return -1; } } rtc_getTime(&valTime); cwd=time_getDayOfWeek(valTime.tm_mday,valTime.tm_mon,valTime.tm_year); if(cwd!=valTime.tm_wday) { sendRTC(RTC_DW,((cwd&0x7) | 0x80)); } rtc_getTime(&valTime); printk("[init] rtc :current time : %02d/%02d/%04d %02d:%02d:%02d\n",valTime.tm_mday,valTime.tm_mon,valTime.tm_year ,valTime.tm_hour,valTime.tm_min,valTime.tm_sec); return MED_OK; }
C
/********************************************** Title: Toggle switch testing Ver: 1.0 Date: 2012-07-01 By: Aaron Hardware: XT-100 8x51 Develoment Board Connection: P0 -> LEDs (0:On 1:Off) P20 -> Switch S3 (0:On 1:Off) **********************************************/ #include <STC89.H> void delay(unsigned int delayCount) { unsigned int t; for(t=0; t<delayCount; t++); } unsigned char getSwitch(void) { P20 = 1; // Make Pin P20 ready for input if (P20 == 0) // Switch is On { delay(100); if (P20 == 0) { return 1; } } return 0; // Switch is Off } /* getSwitch */ void setLight(unsigned char mode) // 0:Off 1:On { if (mode == 0) // Light Off { P00 = 1; } else { P00 = 0; // Light On } } /* setLight */ void main(void) { unsigned char light=0; unsigned char lastkey=0; // Mark key to be off P0=~0x00; // Light off for (;;) { if (getSwitch() == 1) { if (lastkey == 0) // Switch is from Off to On { lastkey = 1; // Mark switch is on now if (light == 0) // Light is Off { setLight(1); // Turn on the light now light = 1; // Mark light to On } else // Light is on { setLight(0); // Turn off the light now light = 0; // Mark light to Off } } } else { lastkey = 0; // Switch is off } // delay(30000); // for debug use } } /* main */
C
/********************************************************************************* * Copyright: (C) 2020 LuXiaoyang<920916829@qq.com> * All rights reserved. * * Filename: ComportOpen.c * Description: This file Open or close the serial port * * Version: 1.0.0(03/07/20) * Author: LuXiaoyang <920916829@qq.com> * ChangeLog: 1, Release initial version on "03/07/20 17:50:09" * ********************************************************************************/ #include "ComportOpen.h" int comport_open(MyAttr *attr) { int i; int retval = -1; if(NULL == attr) { printf("%s,Invalid parameter\n",__func__); return retval; } /* O_NOCTTY表示打开的是一个终端设备,程序不会成为该 * 端口的控制终端,O_NONBLOCK使得read处于非阻塞模式 */ attr->fd = open(attr->SerialName,O_RDWR | O_NOCTTY | O_NONBLOCK); if(attr->fd < 0) { printf("%s,Open %s failed:%s\n",__func__,attr->SerialName,strerror(errno)); return -1; } /* 检查串口是否处于阻塞态 */ if((retval = fcntl(attr->fd,F_SETFL,0)) < 0) { printf("%s,Fcntl check faile.\n",__func__); return -2; } printf("Starting serial communication process "); for(i = 0;i < 6;i++) { printf(" . "); fflush(stdout); usleep(10000); } printf("\n"); //这部分纯属搞笑 if(0 == isatty(attr->fd)) { printf("%s:[%d] is not a Terminal equipment.\n",attr->SerialName,attr->fd); return -3; } printf("Open %s successfully.\n",attr->SerialName); return 0; } int comport_close(MyAttr *attr) { if(tcflush(attr->fd,TCIOFLUSH)) //清零用于串口通信的缓冲区 { printf("%s,Tcflush faile:%s\n",__func__,strerror(errno)); return -1; } /* 将串口设置为原有属性 */ if(tcsetattr(attr->fd,TCSANOW,&(attr->OldTermios))) { printf("%s,Set old options failed:%s\n",__func__,strerror(errno)); return -2; } close(attr->fd); free(attr); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* feg_print.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hnam <hnam@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/03 18:31:47 by hnam #+# #+# */ /* Updated: 2019/04/04 09:47:34 by hnam ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" long double get_float_number(va_list *ap, t_s fs) { if (fs.length == L_LENGTH) return ((long double)va_arg(*ap, long double)); if (fs.length == l_LENGTH) return ((double)va_arg(*ap, double)); else return ((float)va_arg(*ap, double)); } int f_print(va_list *ap, t_s fs) { long double f; int len; f = get_float_number(ap, fs); if (!fs.prec) fs.prec = fs.dot ? 0 : 6; fs.dot = (fs.prec || fs.hash); len = ft_numlen(ABS((int)f), 10) + fs.dot + fs.prec + is_sign(f < 0, fs); if (!fs.minus && fs.zero) { sign_handler(f < 0, fs); ft_make_width(fs.width - len, '0'); } (!fs.minus && !fs.zero) ? ft_make_width(fs.width - len, ' ') : 0; ft_put_float(f, fs); fs.minus ? ft_make_width(fs.width - len, ' ') : 0; return (get_big(len, fs.width)); } static long double handled_number(long double f, int *e_num) { if (*e_num == -4242) { if (ABS((int)f) == 0) { *e_num = 0; while (ABS(f) > 0.0 && ABS(f) < 1.0) { f *= 10.0; *e_num -= 1; } } else if (ABS((int)f) > 10) { *e_num = ft_numlen(ABS((int)f), 10) - 1; while (ABS(f) > 10.0) f /= 10.0; } else *e_num = 0; } else *e_num = -4242; return (f); } int e_print(va_list *ap, t_s fs) { long double f; int len; int e_num; e_num = -4242; f = handled_number(get_float_number(ap, fs), &e_num); if (!fs.prec) fs.prec = fs.dot ? 0 : 6; fs.dot = (fs.prec || fs.hash); len = ft_numlen(ABS((int)f), 10) + 4 + (e_num < 0 ? 1 : 0) + fs.dot + fs.prec + is_sign(f < 0, fs); if (!fs.minus && fs.zero) { sign_handler(f < 0, fs); ft_make_width(fs.width - len + 1, '0'); } (!fs.minus && !fs.zero) ? ft_make_width(fs.width - len + 1, ' ') : 0; ft_put_float(f, fs); ft_put_expo(e_num, fs); fs.minus ? ft_make_width(fs.width - len, ' ') : 0; return (get_big(len, fs.width)); } int g_print(va_list *ap, t_s fs) { long double f; int len; int e_num; int is_e; f = get_float_number(ap, fs); is_e = (get_enum(f) < -4); e_num = is_e ? -4242 : 0; f = is_e ? handled_number(f, &e_num) : f; if (!fs.prec) fs.prec = fs.dot ? 0 : 6; fs.dot = (fs.prec || fs.hash); len = ft_numlen(ABS((int)f), 10) + (is_e ? 5 : 0) + fs.dot + fs.prec + is_sign(f < 0, fs); if (!fs.minus && fs.zero) { sign_handler(f < 0, fs); ft_make_width(fs.width - len + (is_e ? 1 : 0), '0'); } if (!fs.minus && !fs.zero) ft_make_width(fs.width - len + (is_e ? 1 : 0), ' '); ft_put_float(f, fs); is_e ? ft_put_expo(e_num, fs) : 0; fs.minus ? ft_make_width(fs.width - len, ' ') : 0; return (get_big(len, fs.width)); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "mystring.h" int main() { int i; String *s1 = make_string(); print_string(s1); /* char c = string_charAt(s1, 3); printf("%c\n", c); String *s2 = make_string(); int x = string_compare(s1, s2); printf("%d\n", x); String *name = string_concat(s1, s2); print_string(name); String *sub = make_string("le"); int y = string_indexOf(s1, sub, 0); printf("%d\n", y); String *ss = string_substring(s2, 2, 4); print_string(ss); String *list = make_string("zebra, rhino, hippo, elephant"); String *delim = make_string(", "); String *array[MAX]; int n = string_split(list, delim, array, n); for (i=0; i<n; i++) { print_string(array[i]); } string_sort(array, n); for (i=0; i<n; i++) { print_string(array[i]); } */ return 0; }
C
#include <stdio.h> #include <assert.h> unsigned long add(unsigned long a, unsigned long b) { unsigned long result = 0; unsigned long k = 0x01UL; //the current bit which is under calculation int extra = 0; while(a || b) { if((a & 0x01UL) ^ (b & 0x01UL) ^ extra) result |= k; if(extra && !(a & 0x01UL) && !(b & 0x01UL)) extra = 0; if(!extra && (a & 0x01UL) && (b & 0x01UL)) extra = 1; k <<= 1; a >>= 1; b >>= 1; } if(extra) result |= k; return result; } unsigned long mul(unsigned long a, unsigned long b) { unsigned long result = 0; while(a) { if(a & 0x01UL) result = add(result, b); b <<= 1; a >>= 1; } return result; } void mul_test(unsigned long a, unsigned long b) { printf("%lu * %lu = %lu\n", a, b, mul(a, b)); assert((a*b) == mul(a,b)); } int main(void) { unsigned long a, b; a = 38; b = 34; mul_test(a, b); a = 38888; b = 334355; mul_test(a, b); return 0; } // gcc -g3 -std=c99 -pedantic -Wall 5_5.c
C
// Copyright 2009, Andrew Corrigan, acorriga@gmu.edu // This code is from the AIAA-2009-4001 paper #ifndef COMPUTE_STEP_FACTOR_H #define COMPUTE_STEP_FACTOR_H #include <math.h> #include <cmath> #include "const.h" #include "inlined_funcs.h" inline void calculate_dt_kernel( const double* variable, const double* volume, double* dt) { double density = variable[VAR_DENSITY]; double3 momentum; momentum.x = variable[VAR_MOMENTUM+0]; momentum.y = variable[VAR_MOMENTUM+1]; momentum.z = variable[VAR_MOMENTUM+2]; double density_energy = variable[VAR_DENSITY_ENERGY]; double3 velocity; compute_velocity(density, momentum, velocity); double speed_sqd = compute_speed_sqd(velocity); double pressure = compute_pressure(density, density_energy, speed_sqd); double speed_of_sound = compute_speed_of_sound(density, pressure); *dt = double(0.5) * (cbrt(*volume) / (sqrt(speed_sqd) + speed_of_sound)); } inline void get_min_dt_kernel( const double* dt, double* min_dt) { if ((*dt) < (*min_dt)) { *min_dt = (*dt); } } inline void compute_step_factor_kernel( const double* variable, const double* volume, const double* min_dt, double* step_factor) { double density = variable[VAR_DENSITY]; double3 momentum; momentum.x = variable[VAR_MOMENTUM+0]; momentum.y = variable[VAR_MOMENTUM+1]; momentum.z = variable[VAR_MOMENTUM+2]; double density_energy = variable[VAR_DENSITY_ENERGY]; double3 velocity; compute_velocity(density, momentum, velocity); double speed_sqd = compute_speed_sqd(velocity); double pressure = compute_pressure(density, density_energy, speed_sqd); double speed_of_sound = compute_speed_of_sound(density, pressure); // Bring forward a future division-by-volume: *step_factor = (*min_dt) / (*volume); } inline void time_step_kernel( const int* rkCycle, const double* step_factor, double* flux, const double* old_variable, double* variable) { double factor = (*step_factor)/double(RK+1-(*rkCycle)); variable[VAR_DENSITY] = old_variable[VAR_DENSITY] + factor*flux[VAR_DENSITY]; variable[VAR_MOMENTUM+0] = old_variable[VAR_MOMENTUM+0] + factor*flux[VAR_MOMENTUM+0]; variable[VAR_MOMENTUM+1] = old_variable[VAR_MOMENTUM+1] + factor*flux[VAR_MOMENTUM+1]; variable[VAR_MOMENTUM+2] = old_variable[VAR_MOMENTUM+2] + factor*flux[VAR_MOMENTUM+2]; variable[VAR_DENSITY_ENERGY] = old_variable[VAR_DENSITY_ENERGY] + factor*flux[VAR_DENSITY_ENERGY]; flux[VAR_DENSITY] = 0.0; flux[VAR_MOMENTUM+0] = 0.0; flux[VAR_MOMENTUM+1] = 0.0; flux[VAR_MOMENTUM+2] = 0.0; flux[VAR_DENSITY_ENERGY] = 0.0; } #endif
C
#include<stdio.h> #include<math.h> int main() { double a,b,c,d,e,f,g,h; while(scanf("%lf",&a)==1) { b=floor(a*log10(2)+1); c=exp((b-a)*log(2)+b*log(5)); printf("2^-%.0lf = %.3lfe-%.0lf\n",a,c,b); } return 0; }
C
#include <stdio.h> #include "bib.h" #define MAX 100 #include "bib.c" int main(int argc, char **argv){ int vetor[MAX] = {1,2,4,2,6,8,2,8,10,6}, tamanho = 10, indice; do{ indice = procura(vetor, tamanho); if(indice != -1){ removeDoIndice(vetor, &tamanho, indice); } }while(indice != -1); imprimir(vetor, tamanho); return 0; }
C
/********************************************************* * 実習5-6 * 時間を分で入力すると「〇時間〇分」に変換して返すプログラム * * 作成日 : 8/18.2020 * *******************************************************/ #include<stdio.h> int main() { char line[100]; int m_01, m_02, h; /*m_01は入力された分、m_02は剰余、hは時間を代入する変数*/ /*入力を求める*/ printf("Please enter minute : "); fgets(line, sizeof(line), stdin); sscanf(line, "%d", &m_01); /*入力された分の値を時間と分に分ける*/ h = m_01 / 60; m_02 = m_01 % 60; printf("%d分は%d時間%d分\n", m_01, h, m_02); return 0; }
C
#include "modulos.h" int **StHisto2DFF_d(int n, double *x, double *y, int nbinx, double *xmin, double *xmax, double yff) { double deltx; int i,jx,jy,ex,ey,**h; /* Creamos h */ h=matrix_i(nbinx,2); /* Inicializamos los valores de h a cero */ for(jx=0; jx<nbinx; jx++) { for(jy=0; jy<2; jy++) { h[jx][jy]=0; } } /* Si no tenemos definidos los extremos los tomamos de los datos */ if(*xmin == 0 && *xmax == 0) MinMax_d(n,x,xmin,xmax); deltx = (*xmax - *xmin)/(nbinx); /* Calculamos el histograma */ for(i=0; i<n; i++) { if (x[i] >= *xmin && x[i] < *xmax) { ex=(int)((x[i] - *xmin)/deltx); if(ex>=nbinx || ex<=-1) { printf(" ERROR: StHisto2, ex=%d.\n Exiting\n",ex); exit(1); } if (y[i] >= yff) ey = 1; else ey = 0; h[ex][ey]++; } } return(h); }
C
/* * mm.c * In this approach, we used segrated lists and each list has blocks * of size class 2^n to 2^(n+1)-1. Free blocks are managed in this seg_list. * seg_listp is a global pointer to the first element of seg list. * The seg_lists is of size COUNT*WSIZE, each entry stores the address * of first block in a size class,and the entire seg_lists is on the bottom of heap. * inserted or removed from/to seg_lists when freed or malloced. Min-block-size = 4*WSIZE * All blocks have footer and header, packed with size and allocation bit, * free block stores the ptr to prev and next block in the same seg_list in * the payload. A block is allocated by finding the best-fit block in seg_lists, * optimized for binary sizes using first-fit. Blocks are coalesced whenever * they are freed. Realloc is implemented in-place, first searching the next * block, try to minimize the use of memcpy. * */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <unistd.h> #include <string.h> #include "mm.h" #include "memlib.h" /********************************************************* * NOTE TO STUDENTS: Before you do anything else, please * provide your team information in the following struct. ********************************************************/ team_t team = { /* Team name */ "Wildcats", /* First member's full name */ "Wille", /* First member's email address */ "" /* Second member's full name (leave blank if none) */ "Wildcat", /* Second member's email address (leave blank if none) */ "" }; /* EMPTY BLOCK * -----------------------------------------------* * |HEADER: block size | | |alloc bit| * |----------------------------------------------| * | pointer to prev free block in this size list | * |----------------------------------------------| * | pointer to next free block in this size list | * |----------------------------------------------| * |FOOTER: block size | | |alloc bit| * ------------------------------------------------ */ /* Allocated BLOCK * -----------------------------------------------* * |HEADER: block size | | |alloc bit| * |----------------------------------------------| * | Data | * |----------------------------------------------| * | Data | * |----------------------------------------------| * |FOOTER: block size | | |alloc bit| * ------------------------------------------------ */ /*Basic constants and macros */ #define WSIZE 4 /*word and header/footer size (bytes) */ #define DSIZE 8 /*Double word size (bytes) */ #define CHUNKSIZE (1<<6) /*extend heap by this amount (bytes) */ #define MAX(x,y) ((x) > (y) ? (x) : (y)) /*Pack a size and allocated bit into a word */ #define PACK(size, alloc) ((size) | (alloc)) /*read and write a word at address p */ #define GET(p) (*(unsigned int *)(p)) #define PUT(p, val) (*(unsigned int *)(p) = (val)) /*read the size, allocated fields from address p */ #define GET_SIZE(p) (GET(p) & ~0x7) #define GET_ALLOC(p) (GET(p) & 0x1) /*Given bock ptr bp, compute address of its header and footer */ #define HDRP(bp) ((char *)(bp) - WSIZE) #define FTRP(bp) ((char *)(bp) + GET_SIZE(HDRP(bp)) - DSIZE) /*Given block ptr bp, compute address of next and previous blocks */ #define NEXT_BLKP(bp) ((char *)(bp) + GET_SIZE(((char *)(bp) - WSIZE))) #define PREV_BLKP(bp) ((char *)(bp) - GET_SIZE(((char *)(bp) - DSIZE))) /* single word (4) or double word (8) alignment */ #define ALIGNMENT 8 /* rounds up to the nearest multiple of ALIGNMENT */ #define ALIGN(size) (((size) + (ALIGNMENT-1)) & ~0x7) #define SIZE_T_SIZE (ALIGN(sizeof(size_t))) /*global variables */ static char *heap_listp = 0; #define SEG_LIST_COUNT 20 /*number of segregated lists*/ static void * seg_listp; /*pointer pointing to start of seg_list (ptr to head of first list)*/ /*helper macros for seg list */ /*set the prev and next field of bp to address nbp*/ #define PUT_PTR(p, ptr) (*(unsigned int *)(p) = (unsigned int)(ptr)) /*get address of the prev/next field of a free block in a seg_list with pointer bp */ #define GET_PREV(bp) ((char *)bp) #define GET_NEXT(bp) ((char *)(bp) + WSIZE) /*get the address of the pre/next block in a seg_list (actual address) */ #define GET_PREV_BLK(bp) (*(char **)(bp)) #define GET_NEXT_BLK(bp) (*(char **)(GET_NEXT(bp))) /*helper macro for seg-listst*/ #define SEG_LIST(ptr, index) *((char **)ptr+index) /* Function prototypes */ static void *coalesce(void *bp); static void *extend_heap(size_t words); static void *find_fit(size_t asize); static void *place(void * bp, size_t asize); static void insert_free_block(void *bp, size_t block_size); static void remove_free_block(void *bp); static int mm_check(void); /* * mm_init - initialize the malloc package, first put seg_lists on heap, * then create prolouge and epilogue headers/footers. */ int mm_init(void) { int list_number; seg_listp = mem_sbrk(SEG_LIST_COUNT*WSIZE); /* initialize the seg_lists */ for (list_number = 0; list_number < SEG_LIST_COUNT; list_number++) { SEG_LIST(seg_listp, list_number)= NULL; } /* create the initial empty heap */ if ((heap_listp = mem_sbrk(4*WSIZE))==(void *) -1) return -1; PUT(heap_listp, 0); /*Alignment padding */ PUT(heap_listp + (1*WSIZE), PACK(DSIZE, 1)); /*Prologue header */ PUT(heap_listp + (2*WSIZE), PACK(DSIZE, 1)); /*Prologue footer */ PUT(heap_listp + (3*WSIZE), PACK(0,1)); /* Epilogue header*/ heap_listp += (2*WSIZE); /*Extend the empty heap with a free block of CHUNKSIZE bytes */ if (extend_heap(CHUNKSIZE/WSIZE) == NULL) return -1; return 0; } /* * extend_heap: extend the heap by requesting words space from heap */ static void *extend_heap(size_t words) { char *bp; size_t size; /*Allocate an even number of words to maintain alignment */ size = (words % 2) ? (words + 1)*WSIZE : words * WSIZE; if ((long)(bp = mem_sbrk(size)) == -1) return NULL; /*initialize free block header/footer and the epilogue header*/ PUT(HDRP(bp), PACK(size, 0)); /*Free Block header*/ PUT(FTRP(bp), PACK(size, 0)); /*Free Block footer*/ PUT(HDRP(NEXT_BLKP(bp)), PACK(0, 1)); /*New Epilogue header*/ insert_free_block(bp, size); /*coalesce if the previous block was free */ return coalesce(bp); } /* * find_fit -return a ptr to a free block that can accommodate asize * implemented with best-fit strategy, scanning through the list for * the smallest block that can fit asize * */ static void *find_fit(size_t asize) { size_t size = asize; int list_number = 0; void *list_ptr = NULL; while (list_number < SEG_LIST_COUNT) { if ((list_number == SEG_LIST_COUNT - 1) || ((size <= 1) && (SEG_LIST(seg_listp, list_number)!= NULL))) { list_ptr = SEG_LIST(seg_listp, list_number); // locate the smallest block that can fit while ((list_ptr != NULL) && (asize > GET_SIZE(HDRP(list_ptr)))){ list_ptr = GET_PREV_BLK(list_ptr); } if (list_ptr != NULL) { break; } } list_number++; size = size >> 1; } return list_ptr; } /* * place - occupy asize of block pointed by bp, coalesce the remaining free * space if the block size is larger than allocated size. */ static void *place(void *bp, size_t asize) { size_t csize = GET_SIZE(HDRP(bp)); void *np = NULL; remove_free_block(bp); /* if the remaining free space is larger than min-block-size, coalesce*/ if ((csize - asize) >= (2*DSIZE)) { if ((csize - asize) >= 200){ PUT(HDRP(bp), PACK(csize - asize, 0)); PUT(FTRP(bp), PACK(csize - asize, 0)); np = NEXT_BLKP(bp); PUT(HDRP(np), PACK(asize, 1)); PUT(FTRP(np), PACK(asize, 1)); insert_free_block(bp, csize - asize); return np; } else { PUT(HDRP(bp), PACK(asize, 1)); PUT(FTRP(bp), PACK(asize, 1)); np = NEXT_BLKP(bp); PUT(HDRP(np), PACK(csize - asize, 0)); PUT(FTRP(np), PACK(csize - asize, 0)); insert_free_block(np, csize - asize); } } else { PUT(HDRP(bp), PACK(csize, 1)); PUT(FTRP(bp), PACK(csize, 1)); } return bp; } /* * mm_malloc- malloc block by finding a block that fits (call find_fit), * if no fit, extend the heap for more space, then call place to place * the block. * Always allocate a block whose size is a multiple of the alignment. */ void *mm_malloc(size_t size) { size_t asize; /*adjusted block size */ size_t extendsize; /*amount ot extend heap if no fit */ char *bp; char *ptr; /*ignore spurious requests */ if (size == 0) return NULL; /*adjusted block size to include overhead and alignment reqs*/ if (size <= DSIZE) asize = 2*DSIZE; else asize = DSIZE * ((size + (DSIZE) + (DSIZE - 1)) / DSIZE); /* Search the free list for a fit */ if ((bp = find_fit(asize)) != NULL) { ptr = place(bp, asize); return ptr; } /*no fit found, get more memory and place the block */ extendsize = MAX(asize, CHUNKSIZE); if ((bp = extend_heap(extendsize/WSIZE)) == NULL) return NULL; ptr = place(bp, asize); return ptr; } /* * mm_free - Freeing a block by update allocation bit, and insert * into the seg_list for reuse. Coalesce if possible. */ void mm_free(void *bp) { size_t size = GET_SIZE(HDRP(bp)); PUT(HDRP(bp), PACK(size, 0)); PUT(FTRP(bp), PACK(size, 0)); insert_free_block(bp, size); coalesce(bp); } /* * coalesce - check four cases and try to merge the freed block at *bp with previous and next block */ static void *coalesce(void *bp) { size_t prev_alloc = GET_ALLOC(HDRP(PREV_BLKP(bp))); size_t next_alloc = GET_ALLOC(HDRP(NEXT_BLKP(bp))); size_t size = GET_SIZE(HDRP(bp)); if (prev_alloc && next_alloc) { /*case 1 - both prev and next block allocated, no coalesce*/ return bp; } else if (prev_alloc && !next_alloc) { /*case 2 - prev block allocated, next not, coalesce with next*/ remove_free_block(bp); remove_free_block(NEXT_BLKP(bp)); size += GET_SIZE(HDRP(NEXT_BLKP(bp))); PUT(HDRP(bp), PACK(size, 0)); PUT(FTRP(bp), PACK(size, 0)); } else if (!prev_alloc && next_alloc) { /*case 3 - prev block free, next allocated, coalesce with prev*/ remove_free_block(bp); remove_free_block(PREV_BLKP(bp)); size += GET_SIZE(HDRP(PREV_BLKP(bp))); PUT(FTRP(bp), PACK(size, 0)); PUT(HDRP(PREV_BLKP(bp)), PACK(size, 0)); bp = PREV_BLKP(bp); } else { /*case 4- both prev and next free, coalsce three blocks into one*/ remove_free_block(PREV_BLKP(bp)); remove_free_block(bp); remove_free_block(NEXT_BLKP(bp)); size += GET_SIZE(HDRP(PREV_BLKP(bp))) + GET_SIZE(FTRP(NEXT_BLKP(bp))); PUT(HDRP(PREV_BLKP(bp)), PACK(size, 0)); PUT(FTRP(NEXT_BLKP(bp)), PACK(size, 0)); bp = PREV_BLKP(bp); } /*put the coalesced block into the seg_list for reuse*/ insert_free_block(bp, size); return bp; } /* * mm_realloc - implementaed with optimzation on every case: * First check edge cases: ptr = null, size = 0, oldptr size = new size * If none of those trivial cases, we consider 3 special cases: * Case 1: If we are shrinking (new size requested < size of oldptr) * We can shrink the size of oldptr, update header footer, * and free & coalesce the remaining free space * If we are getting a larger size, we consider case 2 & 3. * Case 2: Check in-place if next block in memory after ptr is free * and can fit the new size, if yes, then combine the two * Case 3: Last option, to allocate a new block of size by calling * mm_malloc */ void *mm_realloc(void *ptr, size_t size) { void *oldptr = ptr; void *newptr; void * nextptr; size_t copySize, asize, nsize; /*if size = 0, we want to free ptr*/ if (size == 0) { mm_free(oldptr); return NULL; } /*if oldptr is null, we want to call malloc(size) */ if (oldptr == NULL) { return mm_malloc(size); } asize = ALIGN(size); /*realloc ptr with size*/ copySize =GET_SIZE(HDRP(oldptr))-DSIZE; if (asize == copySize) { return oldptr; } /*Case 1: */ /*if size < oldptr size, the oldptr can hold the new size*/ if (asize < copySize) { //if the remaining space is not enough to store anything, return oldptr if (copySize - asize - DSIZE <= DSIZE) return oldptr; PUT(HDRP(oldptr), PACK(asize + DSIZE, 1)); PUT(FTRP(oldptr), PACK(asize + DSIZE, 1)); newptr = oldptr; oldptr = NEXT_BLKP(newptr); /*free the space emptied*/ PUT(HDRP(oldptr), PACK(copySize - asize, 0)); PUT(FTRP(oldptr), PACK(copySize - asize, 0)); insert_free_block(oldptr, GET_SIZE(HDRP(oldptr))); coalesce(oldptr); return newptr; } /*Case 2: */ /*if size > oldptr size, we need to either find a new block, or take the space of next blk*/ nextptr = NEXT_BLKP(oldptr); /*now check if the next block after oldptr block, in-place, is free*/ if (nextptr != NULL && !GET_ALLOC(HDRP(nextptr))) { nsize = GET_SIZE(HDRP(nextptr)); if (nsize + copySize >= asize) { remove_free_block(nextptr); if (nsize + copySize - asize <= DSIZE) { //if remaining space in next block cannot hold any value, just use it all PUT(HDRP(oldptr), PACK(copySize + DSIZE + nsize, 1)); PUT(FTRP(oldptr), PACK(copySize + DSIZE + nsize, 1)); return oldptr; } else{ //coalecse the reamming free sapce after PUT(HDRP(oldptr), PACK(asize + DSIZE, 1)); PUT(FTRP(oldptr), PACK(asize + DSIZE, 1)); newptr = oldptr; oldptr = NEXT_BLKP(newptr); PUT(HDRP(oldptr), PACK(copySize + nsize - asize, 0)); PUT(FTRP(oldptr), PACK(copySize + nsize - asize, 0)); insert_free_block(oldptr, GET_SIZE(HDRP(oldptr))); coalesce(oldptr); return newptr; } } } /*Case 3: */ /*now we have our last option, which is to allocate a completely new block to fit the size*/ newptr = mm_malloc(size); if (newptr == NULL) return NULL; /*copy over the data from oldptr*/ memcpy(newptr, oldptr, copySize); mm_free(oldptr); return newptr; } /* * insert_free_block - takes a pointer to a block bp and add it to the seg list * each individual list of the same size class is sorted by actual block size */ static void insert_free_block(void *bp, size_t block_size) { void *list_ptr = NULL; void *insert_loc = NULL; /*find the list number / index for this block*/ int list_number = 0; while ((list_number < (SEG_LIST_COUNT - 1)) && (block_size > 1)) { block_size = block_size >> 1; list_number++; } list_ptr = SEG_LIST(seg_listp, list_number); /*find the location to insert, so that the list will be sorted by block size*/ while ((list_ptr != NULL) && (block_size > GET_SIZE(HDRP(list_ptr)))) { insert_loc = list_ptr; list_ptr = GET_PREV_BLK(list_ptr); } /*insert the free block based on the condition of insert_loc and list_ptr*/ if (list_ptr) { if (insert_loc) { //in between insert_loc and list_ptr PUT_PTR(GET_PREV(insert_loc), bp); PUT_PTR(GET_NEXT(bp), insert_loc); PUT_PTR(GET_PREV(bp), list_ptr); PUT_PTR(GET_NEXT(list_ptr), bp); } else { // bp smaller than first item in list_ptr, insert at start PUT_PTR(GET_NEXT(list_ptr), bp); PUT_PTR(GET_PREV(bp), list_ptr); PUT_PTR(GET_NEXT(bp), NULL); SEG_LIST(seg_listp, list_number)=bp; } } else { if (insert_loc) { PUT_PTR(GET_NEXT(bp), insert_loc); PUT_PTR(GET_PREV(insert_loc), bp); PUT_PTR(GET_PREV(bp), NULL); } else { SEG_LIST(seg_listp, list_number)= bp; PUT_PTR(GET_PREV(bp), NULL); PUT_PTR(GET_NEXT(bp), NULL); return; } } return; } /* * remove_free_block- remove a free block bp from seg_list * update the prev/next pointers */ static void remove_free_block(void *bp) { int list_number = 0; size_t block_size = GET_SIZE(HDRP(bp)); /*if bp is the head of a seg_list*/ if (GET_NEXT_BLK(bp) == NULL) { // find the list number / index for this block while (list_number < (SEG_LIST_COUNT - 1) && block_size > 1) { block_size = block_size >> 1; list_number++; } SEG_LIST(seg_listp, list_number)= GET_PREV_BLK(bp); if (SEG_LIST(seg_listp, list_number) != NULL) { PUT_PTR(GET_NEXT(SEG_LIST(seg_listp, list_number)), NULL); } return; } /*if bp is not the head of a seg_list, simply update the next pointer of prev block and prev pointer of next block*/ PUT_PTR(GET_PREV(GET_NEXT_BLK(bp)), GET_PREV_BLK(bp)); if (GET_PREV_BLK(bp) != NULL) { PUT_PTR(GET_NEXT(GET_PREV_BLK(bp)), GET_NEXT_BLK(bp)); } } /* * mm_check - check heap consistency, return 0 if all correct, -1 if not * Also print out the error */ static int mm_check(void) { int errorcode = 0; //set to -1 if see any error int list_number = 0; void *blk_ptr = NULL; //point to the current blk examing void *nxt_ptr = NULL; //point to the next blk examing void *help_ptr = NULL; //used to help compare a blk_ptr to every block in seg_list /*loop through seg_list*/ while (list_number < SEG_LIST_COUNT) { blk_ptr = SEG_LIST(seg_listp, list_number); while (blk_ptr != NULL) { /*check if every block in seg_list marked free*/ if (GET_ALLOC(blk_ptr)) { printf("Free block not marked free\n"); errorcode = -1; } blk_ptr = GET_PREV_BLK(blk_ptr); } list_number++; } /*loop through every block*/ nxt_ptr = NULL; blk_ptr = heap_listp; while (!(GET_SIZE(HDRP(blk_ptr))==0) && !GET_ALLOC(HDRP(blk_ptr))== 1) { nxt_ptr = NEXT_BLKP(blk_ptr); /*check if footer/header information match*/ if (GET_SIZE(HDRP(blk_ptr)) != GET_SIZE(FTRP(blk_ptr))) { printf("Header/Footer size field not match\n"); errorcode = -1; } if (GET_ALLOC(HDRP(blk_ptr)) != GET_ALLOC(FTRP(blk_ptr))) { printf("Header/Footer allocation info not match\n"); errorcode = -1; } /*ALIGHTMENT check if block is 8-byte aligned*/ if ((unsigned int)blk_ptr % DSIZE) { errorcode = -1; printf("Block is not DSIZE (8 byte) aligned\n"); } /*check if two continuous free blocks escaped coalescing*/ if (!(GET_ALLOC(HDRP(blk_ptr)) | GET_ALLOC(HDRP(nxt_ptr)))) { errorcode = -1; printf("Two continuous blocks escaped coalescing\n"); } /*if this is a free block, check if it is in seg_list*/ if (!GET_ALLOC(HDRP(blk_ptr))) { list_number = 0; //search for the block in seg_list while (list_number < SEG_LIST_COUNT) { //loop through every block in this seg_list help_ptr = SEG_LIST(seg_listp, list_number); while (help_ptr != NULL){ //check if this free block is the same as list_ptr if (help_ptr == blk_ptr) { break; } help_ptr = GET_PREV_BLK(help_ptr); } if (help_ptr == blk_ptr) break; list_number++; } if (help_ptr != blk_ptr) { errorcode = -1; printf("free block not in the seg_list\n"); } } blk_ptr = NEXT_BLKP(blk_ptr); } return errorcode; }
C
// Potenz zweier ganzer Zahlen (a hoch n) // Programm-Skelett zur Angabe // // Aufruf: power a n // // Klaus Kusche, 2010 #include <stdio.h> // Was steht in der Angabe zu atoi, was an dieser Stelle zu beachten ist? #include <stdlib.h> int main(int argc, const char *argv[]) { // hat der Aufrufer berhaupt zwei Zahlen angegeben? // (damit argv[1] und argv[2] nicht "ins Leere greift") // Wenn nein: Fehlermeldung ausgeben, mit Fehlercode aufhren if(argc < 3) { printf("\nBitte definiere eine Basis und einen Exponenten!\n"); return 0; } // argv[1] und argv[2] in Zahlen verwandeln // und in zwei dafr angelegten Variablen speichern double base = atof(argv[1]); int exponent = atoi(argv[2]); // jetzt sollten wir noch prfen, // ob wir es mit mathematisch sinnvollen Eingaben zu tun haben: // Bei ganzzahliger Rechnung knnen wir nur Exponenten >= 0 berechnen // Sonst: Fehlermeldung, aufhren! // (und "0 hoch 0" sollte auch ausgeschlossen werden, aber das sparen wir uns) if(exponent == 0){ printf("\nDas Ergebnis ist: %d\n", 1); return 0; } // Wir brauchen eine Variable fr das Ergebnis // im Ergebnis speichern wir als Anfangswert einmal 1, // damit wir weiter unten etwas dazumultiplizieren knnen double result = 1.0d; if(exponent < 0) { for(int i = 1; i <= abs(exponent); ++i){ result *= 1/base; } } else { for(int i = 1; i <= exponent; ++i){ result *= base; } } // nach der Schleife kommt noch die Ausgabe ... printf("\nDas Ergebnis ist: %g\n", result); // ... und das Programm-Ende return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <errno.h> #include "logging.h" #define BUF_SIZE 512 #define RESPONSE_SIZE 32 #ifdef DEBON #define LOG_MSG(macrolevel, ...) \ debuglevel >= macrolevel ? logmsg(__FILE__, __FUNCTION__, __LINE__, 0, LOG_INFO, __VA_ARGS__) : 0; #else #define LOG_MSG(macrolevel, ...) #endif extern char *progname; extern FILE *logstream; extern int daemon_proc; int debuglevel; int main(int argc, char **argv) { struct sockaddr_un sockun; int sockfd; char *sockpath = NULL; char buf[BUF_SIZE] = {0}; char response[RESPONSE_SIZE] = {0}; ssize_t n, m; int gopt, ret, status = 0; while ( (gopt = getopt(argc, argv, ":d:s:")) != -1) { switch(gopt) { case 's': sockpath = optarg; break; case 'd': debuglevel = atoi(optarg); break; default: fprintf(stderr, "Use %s -s \"socket_path\"\n", argv[0]); exit(4); break; } } progname = argv[0]; logstream = stderr; daemon_proc = 1; sockfd = socket(AF_UNIX, SOCK_STREAM, 0); if (sockfd == -1) { perror("socket() error"); status = errno; goto exit_point; } memset(&sockun, 0, sizeof(struct sockaddr_un)); sockun.sun_family = AF_UNIX; strncpy(sockun.sun_path, sockpath, sizeof(sockun.sun_path) - 1); ret = connect(sockfd, (const struct sockaddr *) &sockun, sizeof(struct sockaddr_un)); if (ret == -1) { perror("connect() error"); status = errno; goto exit_point; } while ( (n = read(STDIN_FILENO, buf, BUF_SIZE)) > 0) { if ( (m = write(sockfd, buf, n)) < 0) { perror("write() error"); status = errno; goto exit_point; } } shutdown(sockfd, SHUT_WR); if ( (n = read(sockfd, response, RESPONSE_SIZE)) > 0) { switch (*response) { case '<': status = 0; break; case '-': status = 2; break; case '^': status = 3; break; default: break; } } if (n < 0) status = errno; exit_point: // LOG_MSG(2, "sockwrite read %c, exit code = %d", *response, status); return status; }
C
// sum of squares of n numbers using for loop #include <stdio.h> int main() { int n, i, sum = 0; printf("enter the value of n\n"); scanf("%d", &n); for (i = 1; i <= n; i++) { sum = sum + i * i; } printf("the sum of squares of n numbers is %d", sum); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> int main(int argc, char *argv[]) { int a,b,*con,max=100,i,j; char **pal,**bus; scanf("%i",&a); pal=(char**)malloc(a*sizeof(char*)); for(i=0;i<a;i++){ pal[i]=(char*)malloc(max*sizeof(char)); } for(i=0;i<a;i++){ fflush(stdin); gets(pal[i]); } scanf("%i",&b); bus=(char**)malloc(b*sizeof(char*)); for(i=0;i<b;i++){ bus[i]=(char*)malloc(max*sizeof(char)); } con=(int*)malloc(b*sizeof(int)); for(i=0;i<b;i++){ con[i]=0; } for(i=0;i<b;i++){ fflush(stdin); gets(bus[i]); } for(i=0;i<b;i++){ for(j=0;j<a;j++){ if(strcmp(pal[j],bus[i])==0){ con[i]++; } } } for(i=0;i<b;i++){ printf("\n%i",con[i]); } free(pal); free(bus); free(con); return 0; }
C
#include <stdlib.h> #include <string.h> #include "dictionary.h" static void _relocateMemory(struct Dictionary *instance, int newCountItems); struct Dictionary new_Dictionary() { struct Dictionary instance; instance.count = 0; instance.items = malloc(0); return instance; } void free_Dictionary(struct Dictionary *instance) { // TODO: Implement this } void dictAddItem(struct Dictionary *instance, struct DictionaryItem item) { _relocateMemory(instance, instance->count + 1); instance->items[instance->count] = item; instance->count++; } void dictAdd(struct Dictionary *instance, char *key, char *value) { struct DictionaryItem item; item.key = key; item.value = value; dictAddItem(instance, item); } char *dictGet(struct Dictionary *instance, char *key) { // Linear search for (int i = 0; i < instance->count; i++) { if (!strcmp(instance->items[i].key, key)) return instance->items[i].value; } return NULL; } void dictRemove(struct Dictionary *instance, char *key) { // TODO: Implement this } static void _relocateMemory(struct Dictionary *instance, int newCountItems) { instance->items = realloc(instance->items, newCountItems * sizeof(struct DictionaryItem)); }
C
#include<stdio.h> #include<math.h> void getdata(float *a1,float *b1,float *c1) { printf("\nEnter the coefficient of x^2 :"); scanf("%f",a1); printf("Enter the coefficient of x :"); scanf("%f",b1); printf("Enter the constant :"); scanf("%f",c1); } void quad(float a,float b,float c,float *x,float *r1,float *r2) { *x=sqrt((b*b)-4*a*a); *r1=(-b+*x)/(2*a); *r2=(-b-*x)/(2*a); } void print_roots(float x,float r1,float r2) { if(x>=0) { printf("Root1: %f",r1); printf("\nRoot2: %f\n",r2); } else printf("No real roots\n"); }
C
// // Created by A01229895 on 01/06/2019. // #ifndef CDS1LINKEDLIST_STACK_H #define CDS1LINKEDLIST_STACK_H // // Created by A01229895 on 28/05/2019. // #ifndef CDS1LINKEDLIST_LINKED_LIST_H #define CDS1LINKEDLIST_LINKED_LIST_H #include <stdbool.h> //to change type of data just change type of T typedef int T; typedef struct Node { T data; struct Node* next_node; } Node; typedef struct Stack { struct Node* head; int size; } Stack; Node* create_node (T item); //create a new node with data, ref to next node, returns the pointer to mem loc. Node* add_node (Node* node, Stack* stack); Node* push(T item, Stack *stack); T pop(Stack *stack); T peek(Stack *stack); Stack* create_stack(); //create the Stack that stores nodes void delete_stack(Stack* stack); void reverse_stack(Stack* stack); void print_stack(Stack* stack); static void private_remove_adjust (Node* remove, Stack* stack); //adjust size, memory space, recurrent deletion int size(Stack* stack); bool is_empty(Stack* stack); #endif //CDS1LINKEDLIST_LINKED_LIST_H #endif //CDS1LINKEDLIST_STACK_H
C
/** * c_io.c * * Based on Prof. Ooi Wei Tsang's solution from the CS1010 * I/O Library * * https://github.com/nus-cs1010-1819-s1/libcs1010 */ #include <ctype.h> #include <errno.h> #include <float.h> #include <limits.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "my_io.h" const int BUFSIZE_T = 32 const int BASE = 10 /** * remove_spaces() - Removes leading whitespace from stdin. * * Return: int value of first non-whitespace non-EOF character, * or EOF if EOF is reached. */ static int remove_spaces() { int c; while ((c = fgetc(stdin)) && isspace(c) && c != EOF); return c; } /** * fill_buffer() - Reads characters from stdin into the given buffer. * @buf: buffer to be read into. * @bufsize: number of characters to read. * * Reads characters from stdin into the given buffer. The maximum * number of characters that can be read is equal to bufsize. * * Return: Number of characters read into the given buffer. */ static int fill_buffer(char *buf, int bufsize) { int i = 0; int c; while (i < bufsize && (c = fgetc(stdin)) && c != EOF && !isspace(c)) buf[i++] = c; if (c == EOF || isspace(c)) buf[i++] = '\0'; return i; } /** * read_word() - Reads an arbitrary number of non-whitespace * characters from stdin. * * The caller is responsible for freeing the allocated memory returned * by this function. * * Return: Pointer to the first character, or NULL if an error occurs. */ char *read_word() { int c = remove_spaces(); if (c == EOF) return NULL; char *ret = malloc(1); *ret = c; char buf[BUFSIZE_T]; int buf_len; int total_len = 1; /* number of elements in ret excluding '\0' */ do { buf_len = fill_buffer(buf, BUFSIZE_T); char *tmp = realloc(ret, total_len + buf_len + 1); if (tmp == NULL) { free(ret); return NULL; } ret = tmp; memcpy(ret + total_len, buf, buf_len); total_len += buf_len; } while (buf_len == BUFSIZE_T && buf[buf_len - 1] != '\0'); return ret; } /** * read_line() - Reads a line of arbitrary length from stdin. * * Return: Pointer to the first character, or NULL if an error occurs. */ char *read_line() { char *ret = NULL; size_t unused = 0; errno = 0; if ((getline(&ret, &unused, stdin) == -1) && errno == ENOMEM) { free(ret); return NULL; } ret[strcspn(ret, "\n")] = '\0'; /* remove newline from buffer */ return ret; } /** * read_long() - Reads a long int from stdin. * @result: Result to return * * Reads a long int from stdin. * * Return value will be: * - IOE_SUCCESS if the given string is successfully converted. * - IOE_FAILURE if a general I/O error occurs. * - IOE_INVAL if the input is invalid * - IOE_RANGE if the given number is outside the range of long * * The function does not guarantee the value of *result if * the returned value is not IOE_SUCCESS. The function will * consume any non-numerical character before the start of the * given input, and one character at the end of the input. * * Return: The given number if conversion is successful. */ static int read_long_err(char *nptr, char *endptr, long ret) { if (nptr == endptr || '\0' != *endptr) return IOE_INVAL; else if (ERANGE == errno && (ret == LONG_MAX || ret == LONG_MIN)) return IOE_RANGE; else if (0 != errno && 0 == ret) return IOE_FAILURE; else return IOE_SUCCESS; } int read_long(long *result) { int ret; char *nptr = read_word(); if (nptr == NULL) return IOE_FAILURE; errno = 0; char *endptr; *result = strtol(nptr, &endptr, BASE); ret = read_long_err(nptr, endptr, *result); free(nptr); return ret; } /** * read_int() - Reads an int from stdin. * @result: Result to return * * Reads an int from stdin. * * Return value will be: * - IOE_SUCCESS if the given string is successfully converted. * - IOE_FAILURE if a general I/O error occurs. * - IOE_INVAL if the input is invalid * - IOE_RANGE if the given number is outside the range of int * * The function does not guarantee the value of *result if * the returned value is not IOE_SUCCESS. The function will * consume any non-numerical character before the start of the * given input, and one character at the end of the input. * * Return: The given number if conversion is successful. */ int read_int(int *result) { long tmp; int ret = read_long(&tmp); if (ret == 0 && (tmp < INT_MIN || INT_MAX < tmp)) ret = IOE_RANGE; *result = (int)tmp; return ret; } /** * read_double() - Reads a double from stdin. * @result Result to return * * Reads a double from stdin. */ static int read_dbl_err(char *nptr, char *endptr, long val) { if (ERANGE == errno) return IOE_RANGE; else if (nptr == endptr || '\0' != *endptr) return IOE_INVAL; else if (ERANGE == errno && (val == LONG_MAX || val == LONG_MIN)) return IOE_RANGE; else if (0 != errno && 0 == val) return IOE_FAILURE; else return IOE_SUCCESS; } int read_double(double *result) { int ret; char *ptr = read_word(); if (ptr == NULL) return IOE_FAILURE; errno = 0; char *endptr; *result = strtod(ptr, &endptr); ret = read_dbl_err(ptr, endptr, *result); free(ptr); return ret; }
C
/* * leituraFrequencia.c * * Created: 04/04/2021 11:21:11 * Author : mateu */ #include <avr/io.h> int amostraPassadaCentradaEmZero = 0; uint8_t flagPassagemPorZero=0; int analog; float frequenciaCalculada = -1; int amostraCentradaEmZero = 0; static inline void configuracaoADC(){ /* O objetivo dessa funo configurar a referncia de voltagem pro ADC, o prescaler do clock (supe-se 2MHz), e a forma com que o valor convertido ser registrado. Alm disso, realiza-se uma converso inicial para "gastar- se" os 25 pulsos iniciais. Essa funo deve ser chamada no setup. Uma vez chamada, basta-se chamar a funo conversaoADC(). */ /* Setup ADC to use AVcc and select channel ADC0*/ ADMUX = (0<<REFS1) | (1<<REFS0) | (0<<ADLAR) | (0<<MUX3) | (0<<MUX2) | (0<<MUX1) | (0<<MUX0); /* Set conversion time to 104usec = [(1/2MHz/16)*(13 ADC clocks per conversion)] and enable the ADC*/ ADCSRA = (1<<ADPS2) | (1<<ADPS1) | (1<<ADEN); /* Perform Dummy Conversion to complete ADC init */ ADCSRA |= (1<<ADSC); /* wait for conversion to complete */ while ((ADCSRA & (1<<ADSC)) != 0); } static inline int conversaoADC(char canal){ /* Essa funo realiza a amostragem de um valor no ADC. Seu argumento o canal a ser usado (deve ser usado um char pois esse dado s consome um byte de memria). Primeiro realiza-se a multiplexao do canal utilizado, depois inicia-se a converso. Espera-se concluir e retorna-se o valor inteiro. */ if(canal == '0') ADMUX = (0<<REFS1) | (1<<REFS0) | (0<<ADLAR) | (0<<MUX3) | (0<<MUX2) | (0<<MUX1) | (0<<MUX0); else ADMUX = (0<<REFS1) | (1<<REFS0) | (0<<ADLAR) | (0<<MUX3) | (0<<MUX2) | (0<<MUX1) | (1<<MUX0); int valor_convertido; /* start a new conversion on chosen channel */ ADCSRA |= (1<<ADSC); /* wait for conversion to complete */ while ((ADCSRA & (1<<ADSC)) != 0) ; ADCSRA |= (1<<ADIF); // pause conversion (?) //valor_convertido = (ADCH<<8) | ADCL; valor_convertido = ADC; return valor_convertido; } static inline uint8_t controleTimer0( uint8_t ligaDesliga){ /* A funo controleTimer0 serve pra controle do Timer0. O argumento da funo um char pra no ocupar tanta memria. Caso seja '0', o timer desligado. Caso seja '1', ele liga. */ uint8_t pulsosTimer0; TCCR0A = 0; // normal mode if (ligaDesliga == 0){ // desliga o timer TCCR0B = 0; } else{ // liga o timer TCCR0B = 5; // prescaler = 1024 } pulsosTimer0 = TCNT0; return pulsosTimer0; } static inline float leituraFrequencia(int amostra){ // float frequencia = -1; //amostraCentradaEmZero = amostra - (1024/2); uint8_t valorTimer = 0; // (amostraCentradaEmZero*amostraPassadaCentradaEmZero < 0) if((amostra<=512) && (flagPassagemPorZero == 0)){ flagPassagemPorZero = 1; valorTimer = controleTimer0(1); PORTB = 0; } else{ if((amostra>=512)&&(flagPassagemPorZero == 1)){ valorTimer = controleTimer0(0); //frequenciaCalculada = 1.0/(2.0*valorTimer*2000000.0); frequenciaCalculada = (1000000.0/(2*valorTimer*1024.0)); TCNT0 = 0; flagPassagemPorZero = 0; PORTB = 0; } } amostraPassadaCentradaEmZero = amostraCentradaEmZero; return frequenciaCalculada; } int main(void){ CLKPR |= (1<<CLKPCE)|(1<<CLKPS1); /* Replace with your application code */ DDRB |= (1<<DDB0); configuracaoADC(); while (1){ PORTB = 1; analog = conversaoADC('0'); analog = analog + 0; frequenciaCalculada = leituraFrequencia(analog); } }
C
//Write a program to convert centigrate to fahrenheit #include<stdio.h> int main() { float temp_f,temp_c; printf("Hello this is a temperature converter\n"); printf("Enter the centigrate temperature\n"); scanf("%f",&temp_c); temp_f = ((temp_c-32)*5)/9; printf("the converted temperature in fahrenheit is \n"); printf("%f\n",temp_f ); return 0 ; }
C
/** * @project AwesomeProject * This is the description of AwesomeProject. * @file awesomeproject.c * This is the description of the source file for AwesomeProject. * @copyright (C)2100 Awesome Programmer * @contact awesome.programmer@example.com * @license BSD3 * @version 1.0 */ #include <stdio.h> /// @todo the first thing on the to-do list, and showing //. the use of multi-line documentation markup, making it //. possible to write a lot of stuff using slash comments /// @todo the second thing on the to-do list //! @todo the third thing (but it's important!) /// @fix the operation of this code /** * @function awesomeProject * This is the description of this function. * @param int description of the input parameter * @returns int description of the return value * @special This is a special note associated with with the * documentation for the awesomeProject() function. */ int awesomeProject( int things ) { return ++things; } /** * @special This specific note will appear in the docs that * are automatically generated for special functions like * main(), which normally use the @file or @project labels * to construct their documentation. */ int main( int argc, char **argv ) { int stuff = 0; /// @task this label describes a block of documentation //. that may help decipher particularly confusing code stuff = awesomeProject(stuff); printf("Awesome Project has %d things!\n", stuff); return 0; }
C
#include <stdio.h> #pragma warning(disable:4996) int main(){ FILE *file; file = fopen("/dev/random", "r"); int c; int i = 0; while ((c = fgetc(file)) != EOF && i < 20) { printf("%c ",(char)c ); i++; } printf("\n"); return 0; }
C
/* ** client.c -- a stream socket client demo */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <arpa/inet.h> #define TRUE 1 #define FALSE 0 #define ERROR -1 #define PORT "3500" // the port client will be connecting to #define MAXDATASIZE 1000 // max number of bytes we can get at once typedef struct{ char field[MAXDATASIZE]; int numbytes; }Message; void getcmd(Message *cmd, Message *name); int validcmd(Message *cmd); int exten(Message *cmd); // get sockaddr, IPv4 or IPv6: void *get_in_addr(struct sockaddr *sa) { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*)sa)->sin_addr); } return &(((struct sockaddr_in6*)sa)->sin6_addr); } int main(int argc, char *argv[]) { int sockfd, numbytes; struct addrinfo hints, *servinfo, *p; int rv; char s[INET6_ADDRSTRLEN]; Message cmd; Message name; Message input; if (argc != 2) { fprintf(stderr,"usage: client hostname\n"); exit(1); } memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and connect to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("client: socket"); continue; } if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("client: connect"); continue; } break; } if (p == NULL) { fprintf(stderr, "client: failed to connect\n"); return 2; } inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s); printf("client: connecting to %s\n", s); freeaddrinfo(servinfo); // all done with this structure do{ getcmd(&cmd, &name); send(sockfd, cmd.field, cmd.numbytes, 0); if(exten(&cmd)){ sleep(1); send(sockfd, name.field, name.numbytes, 0); }if(!strcmp(cmd.field, "list")){ input.numbytes=recv(sockfd, input.field, MAXDATASIZE-1, 0); input.field[input.numbytes]='\0'; printf("%s", input.field); }else if(!strcmp(cmd.field, "check")){ input.numbytes=recv(sockfd, input.field, MAXDATASIZE-1, 0); input.field[input.numbytes]='\0'; printf("%s", input.field); }else if(!strcmp(cmd.field, "display")){ do{ input.numbytes=recv(sockfd, input.field, MAXDATASIZE, 0); if(input.numbytes!=MAXDATASIZE) input.field[input.numbytes]='\0'; printf("%s", input.field); }while(input.numbytes==MAXDATASIZE); }else if(!strcmp(cmd.field, "download")){ input.numbytes=recv(sockfd, input.field, MAXDATASIZE-1, 0); input.field[input.numbytes]='\0'; printf("%s", input.field); }else if(!strcmp(cmd.field, "help")){ input.numbytes=recv(sockfd, input.field, MAXDATASIZE-1,0); input.field[input.numbytes]='\0'; printf("%s", input.field); } }while(strcmp(cmd.field,"quit")); close(sockfd); return 0; } void getcmd(Message *cmd, Message *name){ int i, j, event; do{ i=0; j=0; event=FALSE; printf("client367: "); while((cmd->field[i]=getchar())!='\n'&&cmd->field[i]!=' '){ i++; }if(cmd->field[i]==' '){ while((name->field[j]=getchar())!='\n'&&name->field[j]!=' '){ j++; }if(name->field[j]==' ') while(getchar()!='\n'){} }cmd->field[i]='\0'; name->field[j]='\0'; if(exten(cmd)){ if(j==0){ event=TRUE; printf("missing parameter\n"); } } }while(!validcmd(cmd)||event); cmd->numbytes=i; name->numbytes=j; return; } int validcmd(Message *cmd){ int i; i=!strcmp(cmd->field, "list"); i=i+!strcmp(cmd->field, "check"); i=i+!strcmp(cmd->field, "display"); i=i+!strcmp(cmd->field, "download"); i=i+!strcmp(cmd->field, "quit"); i=i+!strcmp(cmd->field, "help"); if(i!=TRUE) printf("Invalid Command\n"); return i; } int exten(Message *cmd){ int i; i=!strcmp(cmd->field, "check"); i=i+!strcmp(cmd->field, "display"); i=i+!strcmp(cmd->field, "download"); return i; }
C
/* * Copyright (c) 1980 Regents of the University of California. * All rights reserved. The Berkeley Software License Agreement * specifies the terms and conditions for redistribution. */ #ifdef FILEC /* * Tenex style file name recognition, .. and more. * History: * Author: Ken Greer, Sept. 1975, CMU. * Finally got around to adding to the Cshell., Ken Greer, Dec. 1981. */ #include "sh.h" #include <sgtty.h> #include <sys/dir.h> #include <pwd.h> #define TRUE 1 #define FALSE 0 #define ON 1 #define OFF 0 #define ESC '\033' typedef enum {LIST, RECOGNIZE} COMMAND; int sortscmp(); /* defined in sh.glob.c */ /* * Put this here so the binary can be patched with adb to enable file * completion by default. Filec controls completion, nobeep controls * ringing the terminal bell on incomplete expansions. */ bool filec = 0; static setup_tty(on) int on; { struct sgttyb sgtty; static struct tchars tchars; /* INT, QUIT, XON, XOFF, EOF, BRK */ if (on) { (void) ioctl(SHIN, TIOCGETC, (char *)&tchars); tchars.t_brkc = ESC; (void) ioctl(SHIN, TIOCSETC, (char *)&tchars); /* * This must be done after every command: if * the tty gets into raw or cbreak mode the user * can't even type 'reset'. */ (void) ioctl(SHIN, TIOCGETP, (char *)&sgtty); if (sgtty.sg_flags & (RAW|CBREAK)) { sgtty.sg_flags &= ~(RAW|CBREAK); (void) ioctl(SHIN, TIOCSETP, (char *)&sgtty); } } else { tchars.t_brkc = -1; (void) ioctl(SHIN, TIOCSETC, (char *)&tchars); } } /* * Move back to beginning of current line */ static back_to_col_1() { struct sgttyb tty, tty_normal; long omask; omask = sigblock(sigmask(SIGINT)); (void) ioctl(SHIN, TIOCGETP, (char *)&tty); tty_normal = tty; tty.sg_flags &= ~CRMOD; (void) ioctl(SHIN, TIOCSETN, (char *)&tty); (void) write(SHOUT, "\r", 1); (void) ioctl(SHIN, TIOCSETN, (char *)&tty_normal); (void) sigsetmask(omask); } /* * Push string contents back into tty queue */ static pushback(string) char *string; { register char *p; struct sgttyb tty, tty_normal; long omask; omask = sigblock(sigmask(SIGINT)); (void) ioctl(SHOUT, TIOCGETP, (char *)&tty); tty_normal = tty; tty.sg_flags &= ~ECHO; (void) ioctl(SHOUT, TIOCSETN, (char *)&tty); for (p = string; *p; p++) (void) ioctl(SHOUT, TIOCSTI, p); (void) ioctl(SHOUT, TIOCSETN, (char *)&tty_normal); (void) sigsetmask(omask); } /* * Concatenate src onto tail of des. * Des is a string whose maximum length is count. * Always null terminate. */ static catn(des, src, count) register char *des, *src; register count; { while (--count >= 0 && *des) des++; while (--count >= 0) if ((*des++ = *src++) == 0) return; *des = '\0'; } /* * Like strncpy but always leave room for trailing \0 * and always null terminate. */ static copyn(des, src, count) register char *des, *src; register count; { while (--count >= 0) if ((*des++ = *src++) == 0) return; *des = '\0'; } static char filetype(dir, file) char *dir, *file; { char path[MAXPATHLEN]; struct stat statb; catn(strcpy(path, dir), file, sizeof path); if (lstat(path, &statb) == 0) { switch(statb.st_mode & S_IFMT) { case S_IFDIR: return ('/'); case S_IFLNK: if (stat(path, &statb) == 0 && /* follow it out */ (statb.st_mode & S_IFMT) == S_IFDIR) return ('>'); else return ('@'); case S_IFSOCK: return ('='); default: if (statb.st_mode & 0111) return ('*'); } } return (' '); } static struct winsize win; /* * Print sorted down columns */ static print_by_column(dir, items, count) char *dir, *items[]; { register int i, rows, r, c, maxwidth = 0, columns; if (ioctl(SHOUT, TIOCGWINSZ, (char *)&win) < 0 || win.ws_col == 0) win.ws_col = 80; for (i = 0; i < count; i++) maxwidth = maxwidth > (r = strlen(items[i])) ? maxwidth : r; maxwidth += 2; /* for the file tag and space */ columns = win.ws_col / maxwidth; if (columns == 0) columns = 1; rows = (count + (columns - 1)) / columns; for (r = 0; r < rows; r++) { for (c = 0; c < columns; c++) { i = c * rows + r; if (i < count) { register int w; printf("%s", items[i]); putchar(dir ? filetype(dir, items[i]) : ' '); if (c < columns - 1) { /* last column? */ w = strlen(items[i]) + 1; for (; w < maxwidth; w++) putchar(' '); } } } putchar('\n'); } } /* * Expand file name with possible tilde usage * ~person/mumble * expands to * home_directory_of_person/mumble */ static char * tilde(new, old) char *new, *old; { register char *o, *p; register struct passwd *pw; static char person[40]; if (old[0] != '~') return (strcpy(new, old)); for (p = person, o = &old[1]; *o && *o != '/'; *p++ = *o++) ; *p = '\0'; if (person[0] == '\0') (void) strcpy(new, value("home")); else { pw = getpwnam(person); if (pw == NULL) return (NULL); (void) strcpy(new, pw->pw_dir); } (void) strcat(new, o); return (new); } /* * Cause pending line to be printed */ static retype() { int pending_input = LPENDIN; (void) ioctl(SHOUT, TIOCLBIS, (char *)&pending_input); } static beep() { if (adrof("nobeep") == 0) (void) write(SHOUT, "\007", 1); } /* * Erase that silly ^[ and * print the recognized part of the string */ static print_recognized_stuff(recognized_part) char *recognized_part; { /* An optimized erasing of that silly ^[ */ switch (strlen(recognized_part)) { case 0: /* erase two characters: ^[ */ printf("\210\210 \210\210"); break; case 1: /* overstrike the ^, erase the [ */ printf("\210\210%s \210", recognized_part); break; default: /* overstrike both characters ^[ */ printf("\210\210%s", recognized_part); break; } flush(); } /* * Parse full path in file into 2 parts: directory and file names * Should leave final slash (/) at end of dir. */ static extract_dir_and_name(path, dir, name) char *path, *dir, *name; { register char *p; p = rindex(path, '/'); if (p == NULL) { copyn(name, path, MAXNAMLEN); dir[0] = '\0'; } else { copyn(name, ++p, MAXNAMLEN); copyn(dir, path, p - path); } } static char * getentry(dir_fd, looking_for_lognames) DIR *dir_fd; { register struct passwd *pw; register struct direct *dirp; if (looking_for_lognames) { if ((pw = getpwent()) == NULL) return (NULL); return (pw->pw_name); } if (dirp = readdir(dir_fd)) return (dirp->d_name); return (NULL); } static free_items(items) register char **items; { register int i; for (i = 0; items[i]; i++) free(items[i]); free((char *)items); } #define FREE_ITEMS(items) { \ long omask;\ \ omask = sigblock(sigmask(SIGINT));\ free_items(items);\ items = NULL;\ (void) sigsetmask(omask);\ } /* * Object: extend what user typed up to an ambiguity. * Algorithm: * On first match, copy full entry (assume it'll be the only match) * On subsequent matches, shorten extended_name to the first * character mismatch between extended_name and entry. * If we shorten it back to the prefix length, stop searching. */ static recognize(extended_name, entry, name_length, numitems) char *extended_name, *entry; { if (numitems == 1) /* 1st match */ copyn(extended_name, entry, MAXNAMLEN); else { /* 2nd & subsequent matches */ register char *x, *ent; register int len = 0; x = extended_name; for (ent = entry; *x && *x == *ent++; x++, len++) ; *x = '\0'; /* Shorten at 1st char diff */ if (len == name_length) /* Ambiguous to prefix? */ return (-1); /* So stop now and save time */ } return (0); } /* * Return true if check matches initial chars in template. * This differs from PWB imatch in that if check is null * it matches anything. */ static is_prefix(check, template) register char *check, *template; { do if (*check == 0) return (TRUE); while (*check++ == *template++); return (FALSE); } /* * Return true if the chars in template appear at the * end of check, I.e., are it's suffix. */ static is_suffix(check, template) char *check, *template; { register char *c, *t; for (c = check; *c++;) ; for (t = template; *t++;) ; for (;;) { if (t == template) return 1; if (c == check || *--t != *--c) return 0; } } static ignored(entry) register char *entry; { struct varent *vp; register char **cp; if ((vp = adrof("fignore")) == NULL || (cp = vp->vec) == NULL) return (FALSE); for (; *cp != NULL; cp++) if (is_suffix(entry, *cp)) return (TRUE); return (FALSE); } /* * Perform a RECOGNIZE or LIST command on string "word". */ static search(word, command, max_word_length) char *word; COMMAND command; { static char **items = NULL; register DIR *dir_fd; register numitems = 0, ignoring = TRUE, nignored = 0; register name_length, looking_for_lognames; char tilded_dir[MAXPATHLEN + 1], dir[MAXPATHLEN + 1]; char name[MAXNAMLEN + 1], extended_name[MAXNAMLEN+1]; char *entry; #define MAXITEMS 1024 if (items != NULL) FREE_ITEMS(items); looking_for_lognames = (*word == '~') && (index(word, '/') == NULL); if (looking_for_lognames) { (void) setpwent(); copyn(name, &word[1], MAXNAMLEN); /* name sans ~ */ } else { extract_dir_and_name(word, dir, name); if (tilde(tilded_dir, dir) == 0) return (0); dir_fd = opendir(*tilded_dir ? tilded_dir : "."); if (dir_fd == NULL) return (0); } again: /* search for matches */ name_length = strlen(name); for (numitems = 0; entry = getentry(dir_fd, looking_for_lognames); ) { if (!is_prefix(name, entry)) continue; /* Don't match . files on null prefix match */ if (name_length == 0 && entry[0] == '.' && !looking_for_lognames) continue; if (command == LIST) { if (numitems >= MAXITEMS) { printf ("\nYikes!! Too many %s!!\n", looking_for_lognames ? "names in password file":"files"); break; } if (items == NULL) items = (char **) calloc(sizeof (items[1]), MAXITEMS); items[numitems] = xalloc((unsigned)strlen(entry) + 1); copyn(items[numitems], entry, MAXNAMLEN); numitems++; } else { /* RECOGNIZE command */ if (ignoring && ignored(entry)) nignored++; else if (recognize(extended_name, entry, name_length, ++numitems)) break; } } if (ignoring && numitems == 0 && nignored > 0) { ignoring = FALSE; nignored = 0; if (looking_for_lognames) (void) setpwent(); else rewinddir(dir_fd); goto again; } if (looking_for_lognames) (void) endpwent(); else closedir(dir_fd); if (numitems == 0) return (0); if (command == RECOGNIZE) { if (looking_for_lognames) copyn(word, "~", 1); else /* put back dir part */ copyn(word, dir, max_word_length); /* add extended name */ catn(word, extended_name, max_word_length); return (numitems); } else { /* LIST */ qsort((char *)items, numitems, sizeof(items[1]), sortscmp); print_by_column(looking_for_lognames ? NULL : tilded_dir, items, numitems); if (items != NULL) FREE_ITEMS(items); } return (0); } tenex(inputline, inputline_size) char *inputline; int inputline_size; { register int numitems, num_read; setup_tty(ON); while ((num_read = read(SHIN, inputline, inputline_size)) > 0) { static char *delims = " '\"\t;&<>()|^%"; register char *str_end, *word_start, last_char, should_retype; register int space_left; COMMAND command; last_char = inputline[num_read - 1] & 0177; if (last_char == '\n' || num_read == inputline_size) break; command = (last_char == ESC) ? RECOGNIZE : LIST; if (command == LIST) putchar('\n'); str_end = &inputline[num_read]; if (last_char == ESC) --str_end; /* wipeout trailing cmd char */ *str_end = '\0'; /* * Find LAST occurence of a delimiter in the inputline. * The word start is one character past it. */ for (word_start = str_end; word_start > inputline; --word_start) if (index(delims, word_start[-1])) break; space_left = inputline_size - (word_start - inputline) - 1; numitems = search(word_start, command, space_left); if (command == RECOGNIZE) { /* print from str_end on */ print_recognized_stuff(str_end); if (numitems != 1) /* Beep = No match/ambiguous */ beep(); } /* * Tabs in the input line cause trouble after a pushback. * tty driver won't backspace over them because column * positions are now incorrect. This is solved by retyping * over current line. */ should_retype = FALSE; if (index(inputline, '\t')) { /* tab char in input line? */ back_to_col_1(); should_retype = TRUE; } if (command == LIST) /* Always retype after a LIST */ should_retype = TRUE; if (should_retype) printprompt(); pushback(inputline); if (should_retype) retype(); } setup_tty(OFF); return (num_read); } #endif /* FILEC */
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <dirent.h> #include <errno.h> #include <string.h> #include <jansson.h> #include "data.h" #include "config.h" #include "verlet.h" #include "jsonUtils.h" int extractJsonObjectFromJsonObject(json_t * json, char * name, json_t ** field) { int rc = 0; if (json == NULL) { rc = 1; *field = NULL; printf("%s was not found\n", name); } else if (json_is_object(json)) { *field = json; } else { rc = 2; printf("%s is not a JSONObject: type = %d\n", name, json_typeof(json)); } return rc; } int extractJsonArrayFromJsonObject(json_t * json, char * name, json_t ** field) { int rc = 0; if (json == NULL) { rc = 1; printf("%s was not found\n", name); } else if (json_is_array(json)) { *field = json; } else { rc = 2; printf("%s is not a JSONArray: type = %d\n", name, json_typeof(json)); } return rc; } int extractStringFromJsonObject(json_t * json, char * name, char * field, size_t sizeoffield) { int rc = 0; if (json == NULL) { rc = 1; memset(field, 0, sizeoffield); printf("%s was not found\n", name); } else if (json_is_string(json)) { char *value = (char*) json_string_value(json); if (strlen(value) + 1 > sizeoffield) { rc = 2; printf("The string '%s' is too large for the buffer: strlen = %d, sizeoffield = %d\n", name, (int) strlen(value), (int) sizeoffield); } else { strncpy(field, value, sizeoffield); } } else { rc = 3; printf("%s is not a String: type = %d\n", name, json_typeof(json)); } return rc; } int extractDoubleFromJsonObject(json_t * json, char * name, double * field) { int rc = 0; if (json == NULL) { rc = 1; *field = 0; printf("%s was not found", name); } else if (json_is_real(json)) { double value = (double) json_real_value(json); *field = value; } else { rc = 2; printf("%s is not a real number: type = %d", name, json_typeof(json)); } return rc; } int extractDoubleFromJsonArray(json_t * json, int i, double * field) { int rc = 0; if (json == NULL) { rc = 1; *field = 0; printf("Json array element %d could not be found\n", i); } else if (json_is_real(json)) { double value = (double) json_real_value(json); *field = value; } else { rc = 2; printf("Json not of type REAL. type = %d\n", json_typeof(json)); } return rc; } int getJsonObjectFromJsonObject(json_t * parent, char * fieldname, json_t ** value) { json_t * json = json_object_get(parent, fieldname); return extractJsonObjectFromJsonObject(json, fieldname, value); } int getJsonObjectFromJsonArray(char * name, json_t * array, size_t index, json_t ** value) { json_t * json; char description[128]; snprintf(description, sizeof(description), "%s[%d]", name, (int) index); json = json_array_get(array, index); return extractJsonObjectFromJsonObject(json, description, value); } int getJsonArrayFromJsonObject(json_t * parent, char * fieldname, json_t ** value) { json_t * json = json_object_get(parent, fieldname); return extractJsonArrayFromJsonObject(json, fieldname, value); } int getStringFromJsonObject(json_t * parent, char * fieldname, char * value, size_t size) { json_t * json = json_object_get(parent, fieldname); return extractStringFromJsonObject(json, fieldname, value, size); } int getDoubleFromJsonObject(json_t * parent, char * fieldname, double * value) { json_t * json = json_object_get(parent, fieldname); return extractDoubleFromJsonObject(json, fieldname, value); } int getDoubleFromJsonArray(json_t * array, int index, double * value) { json_t * json = json_array_get(array, index); return extractDoubleFromJsonArray(json, index, value); }
C
#include "lists.h" /** * add_dnodeint_end - adds a new node at the end * @head: head of the list * @n: value of the element * Return: the address of the new element * Aladin Bensassi */ dlistint_t *add_dnodeint_end(dlistint_t **head, const int n) { dlistint_t *h; dlistint_t *new; new = malloc(sizeof(dlistint_t)); if (new == NULL) return (NULL); new->n = n; new->next = NULL; h = *head; if (h != NULL) { while (h->next != NULL) h = h->next; h->next = new; } else { *head = new; } new->prev = h; return (new); }
C
/*------------------------------------------------------------------------------ -- Source File: gps-utils.c -- -- Program: Wireless GPS Program -- -- Functions: -- int gps_search_sat (struct gps_data_t* gpsdata) -- -- Date: Nov 2 2017 -- -- Designer: Alfred Swinton -- -- Programmer: Alfred Swinton -- -- Notes: -- The program is a location finding application that uses the gpsd utility -- along with assocaited C service library. -- -- The gps-utils code grabs data from the gpsd daemon and sends the data -- to a print function -- ------------------------------------------------------------------------------*/ #include "gps-utils.h" #include <stdlib.h> /*------------------------------------------------------------------------------ -- Function: gps_search_sat -- -- Date: Nov 2 2017 -- -- Designer: Alfred Swinton -- -- Programmer: Alfred Swinton -- -- Interface: int gps_search_sat(struct gps_data_t* gpsdata) -- struct gps_data_t* gpsdata: a pointer to the data structure -- -- Returns: -1 on exit -- -- Notes: -- Waits for the gpsd daemon to have data and stores it in the gps_data_t -- struture when it does. Sends the structure to the print function once -- the data is grabbed. -- ------------------------------------------------------------------------------*/ int gps_search_sat(struct gps_data_t* gpsdata) { int timeouts = 0; while (true) { //Wait for new gps signals, fail on ten consecutive timeouts if (!gps_waiting(gpsdata, 3000000)) { fprintf(stderr,"GPS timeout \n"); ++timeouts; if (timeouts >= 3) { errno = 16; return -1; } } else { //Read info from gps signals timeouts = 0; if (gps_read(gpsdata) == -1) { fprintf(stderr,"Error Reading Device Failed \n"); errno = 5; return -1; } else { if(gpsdata->fix.mode > 0) PrintGpsData(gpsdata); } } } } /*------------------------------------------------------------------------------ -- Function: cleanup -- -- Date: Nov 2 2017 -- -- Designer: Alfred Swinton -- -- Programmer: Alfred Swinton -- -- Interface: void cleanup(struct gps_data_t* gpsdata) -- struct gps_data_t* gpsdata: a pointer to the data structure -- -- Returns: void -- -- Notes: -- Closes the connection to the gpsd daemon and frees the memory used for the -- data structure. -- ------------------------------------------------------------------------------*/ void cleanup(struct gps_data_t* gpsdata) { gps_stream(gpsdata,WATCH_DISABLE,NULL); gps_close(gpsdata); free(gpsdata); }
C
#ifndef SERVICIOS_H_INCLUDED #define SERVICIOS_H_INCLUDED typedef struct { int id; char descripcion[20]; int precio; } eServicio; #endif // SERVICIO_H_INCLUDED int validarServicio(eServicio vec[],int tam,int idBusqueda); /** @brief recorre el vector vec[] y pregunta si hay al menos un dato con vec[].id == idBusqueda * @param mas[] vector de tipo eServicio * @param tamVec tamaño del vector eServicio * @param idServicio valor que se usara para buscar * * @return (0) si no se encontro - (int) valor vec.precio donde vec[].id == idBusqueda */ int descripccionServicio(eServicio vec[],int tam, int idBusqueda, char descipcion[]); /** @brief pide un id por parametro y busca ese id dentro de vec[].id si lo encuentra carga lo que este en * vec.descripcion dentro del string descripcion * @param vec[] vector de tipo eServicio * @param tamMas tamaño del vector eServicio * @param idBusqueda valor que sera buscado dentro del vector * @param descripcion string de estritura * * @return (-1) si huvo un error - (-2) no se encontro el id cargado - (0) todo ok */ int mostrarServicio( eServicio vec[], int tam ); /** @brief muestra una tabla con todos los valores en vec que esten con el espacio vec.isempty en 1 * @param vec[] vector de tipo eServicio * @param tamMas tamaño del vector eSericio * * @return (-1) si huvo un error - (0) si todo ok */
C
#include "purGLUtils.h" #include <limits.h> #define purGLAABBResetMin INT_MAX #define purGLAABBResetMax INT_MIN #define purGLAABBfResetMin FLT_MAX #define purGLAABBfResetMax (-FLT_MAX) const purGLAABB purGLAABBReset = {purGLAABBResetMin, purGLAABBResetMin, purGLAABBResetMax, purGLAABBResetMax}; const purGLAABBf purGLAABBfReset = {purGLAABBfResetMin, purGLAABBfResetMin, purGLAABBfResetMax, purGLAABBfResetMax}; purGLVertex purGLVertexMake(GLfloat x, GLfloat y) { purGLVertex retVal; retVal.x = x; retVal.y = y; return retVal; } purGLColorVertex purGLColorVertexMake(GLfloat x, GLfloat y, GLubyte r, GLubyte g, GLubyte b, GLubyte a) { purGLColorVertex retVal; retVal.x = x; retVal.y = y; retVal.r = r; retVal.g = g; retVal.b = b; retVal.a = a; return retVal; } purGLTextureVertex purGLTextureVertexMake(GLfloat x, GLfloat y, GLfloat s, GLfloat t) { purGLTextureVertex retVal; retVal.x = x; retVal.y = y; retVal.s = s; retVal.t = t; return retVal; } purGLColoredTextureVertex purGLColoredTextureVertexMake(GLfloat x, GLfloat y, GLubyte r, GLubyte g, GLubyte b, GLubyte a, GLfloat s, GLfloat t) { purGLColoredTextureVertex retVal; retVal.x = x; retVal.y = y; retVal.r = r; retVal.g = g; retVal.b = b; retVal.a = a; retVal.s = s; retVal.t = t; return retVal; } purGLAABB purGLAABBMake(GLint xMin, GLint yMin, GLint xMax, GLint yMax) { purGLAABB retVal; retVal.xMin = xMin; retVal.yMin = yMin; retVal.xMax = xMax; retVal.yMax = yMax; return retVal; } purGLAABBf purGLAABBfMake(GLfloat xMin, GLfloat yMin, GLfloat xMax, GLfloat yMax) { purGLAABBf retVal; retVal.xMin = xMin; retVal.yMin = yMin; retVal.xMax = xMax; retVal.yMax = yMax; return retVal; } purGLColorVerticesRef purGLColorVerticesRefMake(unsigned vertexCount, unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha) { purGLColorVerticesRef ref = calloc(1, sizeof(purGLColorVertices)); if (ref) { if (vertexCount > 0) { ref->vertices = calloc(vertexCount, sizeof(purGLVertex)); if (ref->vertices) ref->vertexCount = vertexCount; } // Else is taken care of by calloc... ref->r = red; ref->g = green; ref->b = blue; ref->a = alpha; } return ref; } void purGLColorVerticesRefFree(purGLColorVertices * ref) { if (ref) { if (ref->vertices) { free(ref->vertices); ref->vertices = 0; ref->vertexCount = 0; } free(ref); } } purGLColorVertices purGLColorVerticesMake(unsigned vertexCount, unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha) { purGLColorVertices ref; if (vertexCount > 0) { ref.vertices = calloc(vertexCount, sizeof(purGLVertex)); if (ref.vertices) ref.vertexCount = vertexCount; } else { ref.vertices = 0; ref.vertexCount = 0; } ref.r = red; ref.g = green; ref.b = blue; ref.a = alpha; return ref; } void purGLColorVerticesFree(purGLColorVertices *colorVertices) { if (colorVertices) { if (colorVertices->vertices) { free(colorVertices->vertices); colorVertices->vertices = 0; } colorVertices->vertexCount = 0; } } /*purGLAABB purGLAABBReset() { return purGLAABBMake(purGLAABBResetMin, purGLAABBResetMin, purGLAABBResetMax, purGLAABBResetMax); }*/ void purGLAABBUpdate(purGLAABB *toBeUpdated, purGLAABB *checkVals) { *toBeUpdated = purGLAABBMake(fminf(toBeUpdated->xMin, checkVals->xMin), fminf(toBeUpdated->yMin, checkVals->yMin), fmaxf(toBeUpdated->xMax, checkVals->xMax), fmaxf(toBeUpdated->yMax, checkVals->yMax)); } void purGLAABBExpand(purGLAABB *aabb, inkPoint point) { return purGLAABBExpandv(aabb, roundf(point.x), roundf(point.y)); } void purGLAABBExpandv(purGLAABB *aabb, GLint x, GLint y) { *aabb = purGLAABBMake(fminf(aabb->xMin, x), fminf(aabb->yMin, y), fmaxf(aabb->xMax, x), fmaxf(aabb->yMax, y)); } void purGLAABBInflate(purGLAABB *aabb, inkPoint point) { return purGLAABBInflatev(aabb, roundf(point.x), roundf(point.y)); } void purGLAABBInflatev(purGLAABB *aabb, GLint x, GLint y) { aabb->xMin -= x; aabb->yMin -= y; aabb->xMax += x; aabb->yMax += y; } bool purGLAABBIsReset(purGLAABB *aabb) { return (aabb->xMin == purGLAABBResetMin || aabb->yMin == purGLAABBResetMin || aabb->xMax == purGLAABBResetMax || aabb->yMax == purGLAABBResetMax); } bool purGLAABBContainsPoint(purGLAABB *aabb, inkPoint point) { return purGLAABBContainsPointv(aabb, (GLint)(point.x), (GLint)(point.y)); } bool purGLAABBContainsPointv(purGLAABB *aabb, GLint x, GLint y) { return ((x >= aabb->xMin) && (x <= aabb->xMax) && (y >= aabb->yMin) && (y <= aabb->yMax)); } bool purGLAABBIsEqual(purGLAABB *aabb1, purGLAABB *aabb2) { return (aabb1->xMin == aabb2->xMin && aabb1->yMin == aabb2->yMin && aabb1->xMax == aabb2->xMax && aabb1->yMax == aabb2->yMax); } //purGLAABBf purGLAABBfReset() //{ // return purGLAABBfMake(purGLAABBfResetMin, purGLAABBfResetMin, purGLAABBfResetMax, purGLAABBfResetMax); //} void purGLAABBfUpdate(purGLAABBf *toBeUpdated, purGLAABBf *checkVals) { *toBeUpdated = purGLAABBfMake(fminf(toBeUpdated->xMin, checkVals->xMin), fminf(toBeUpdated->yMin, checkVals->yMin), fmaxf(toBeUpdated->xMax, checkVals->xMax), fmaxf(toBeUpdated->yMax, checkVals->yMax)); } void purGLAABBfExpand(purGLAABBf *aabb, inkPoint point) { return purGLAABBfExpandv(aabb, point.x, point.y); } void purGLAABBfExpandv(purGLAABBf *aabb, GLfloat x, GLfloat y) { *aabb = purGLAABBfMake(fminf(aabb->xMin, x), fminf(aabb->yMin, y), fmaxf(aabb->xMax, x), fmaxf(aabb->yMax, y)); } void purGLAABBfInflate(purGLAABBf *aabb, inkPoint point) { return purGLAABBfInflatev(aabb, point.x, point.y); } void purGLAABBfInflatev(purGLAABBf *aabb, GLfloat x, GLfloat y) { aabb->xMin -= x; aabb->yMin -= y; aabb->xMax += x; aabb->yMax += y; } bool purGLAABBfIsReset(purGLAABBf *aabb) { return (inkIsEqualf(aabb->xMin, purGLAABBfResetMin) || inkIsEqualf(aabb->xMin, purGLAABBfResetMin) || inkIsEqualf(aabb->xMax, purGLAABBfResetMax) || inkIsEqualf(aabb->xMax, purGLAABBfResetMax)); } bool purGLAABBfContainsPoint(purGLAABBf *aabb, inkPoint point) { return purGLAABBfContainsPointv(aabb, point.x, point.y); } bool purGLAABBfContainsPointv(purGLAABBf *aabb, GLfloat x, GLfloat y) { return ((x >= aabb->xMin) && (x <= aabb->xMax) && (y >= aabb->yMin) && (y <= aabb->yMax)); } bool purGLAABBfIsEqual(purGLAABBf *aabb1, purGLAABBf *aabb2) { return (inkIsEqualf(aabb1->xMin, aabb2->xMin) && inkIsEqualf(aabb1->xMin, aabb2->yMin) && inkIsEqualf(aabb1->xMax, aabb2->xMax) && inkIsEqualf(aabb1->xMax, aabb2->yMax)); } void inkMatrixConvertPoints(inkMatrix matrix, inkPoint *points, unsigned count) { inkPoint *point; unsigned index; for (index = 0, point = points; index < count; ++index, ++point) { *point = inkMatrixTransformPoint(matrix, *point); } } void inkMatrixConvertPointsv(inkMatrix matrix, float *xs, float *ys, unsigned count) { float *curX; float *curY; unsigned int index; for (index = 0, curX = xs, curY = ys; index < count; ++curX, ++curY) { inkMatrixConvertPointv(matrix, curX, curY); } } void inkMatrixConvert4Points(inkMatrix matrix, inkPoint *point0, inkPoint *point1, inkPoint *point2, inkPoint *point3) { inkMatrixConvertPointv(matrix, &(point0->x), &(point0->y)); inkMatrixConvertPointv(matrix, &(point1->x), &(point1->y)); inkMatrixConvertPointv(matrix, &(point2->x), &(point2->y)); inkMatrixConvertPointv(matrix, &(point3->x), &(point3->y)); } void inkMatrixConvert4Pointsv(inkMatrix matrix, float *x0, float *y0, float *x1, float *y1, float *x2, float *y2, float *x3, float *y3) { inkMatrixConvertPointv(matrix, x0, y0); inkMatrixConvertPointv(matrix, x1, y1); inkMatrixConvertPointv(matrix, x2, y2); inkMatrixConvertPointv(matrix, x3, y3); } inkRect inkMatrixConvertRect(inkMatrix matrix, inkRect rect) { inkRect retVal = rect; inkMatrixConvertRectv(matrix, &(rect.origin.x), &(rect.origin.y), &(rect.size.width), &(rect.size.height)); return retVal; } void inkMatrixConvertRectv(inkMatrix matrix, float *x, float *y, float *width, float *height) { purGLAABBf aabb = purGLAABBfMake(*x, *y, *x + *width, *y + *height); aabb = inkMatrixConvertAABBf(matrix, aabb); *x = aabb.xMin; *y = aabb.yMin; *width = aabb.xMax - aabb.xMin; *height = aabb.yMax - aabb.yMin; } purGLAABB inkMatrixConvertAABB(inkMatrix matrix, purGLAABB aabb) { purGLAABB retVal = aabb; inkMatrixConvertAABBv(matrix, (&(retVal.xMin)), (&(retVal.yMin)), (&(retVal.xMax)), (&(retVal.yMax))); return retVal; } void inkMatrixConvertAABBv(inkMatrix matrix, GLint *xMin, GLint *yMin, GLint *xMax, GLint *yMax) { float xMinf = *xMin; float yMinf = *yMin; float xMaxf = *xMax; float yMaxf = *yMax; inkMatrixConvertAABBfv(matrix, &xMinf, &yMinf, &xMaxf, &yMaxf); *xMin = floorf(xMinf); *yMin = floorf(yMinf); *xMax = ceilf(xMaxf); *yMax = ceilf(yMaxf); } purGLAABBf inkMatrixConvertAABBf(inkMatrix matrix, purGLAABBf aabb) { purGLAABBf retVal = aabb; inkMatrixConvertAABBfv(matrix, &(retVal.xMin), &(retVal.yMin), &(retVal.xMax), &(retVal.yMax)); return retVal; } void inkMatrixConvertAABBfv(inkMatrix matrix, GLfloat *xMin, GLfloat *yMin, GLfloat *xMax, GLfloat *yMax) { inkPoint p1 = inkPointMake(*xMin, *yMin); inkPoint p2 = inkPointMake(*xMax, *yMin); inkPoint p3 = inkPointMake(*xMin, *yMax); inkPoint p4 = inkPointMake(*xMax, *yMax); inkMatrixConvert4Points(matrix, &p1, &p2, &p3, &p4); *xMin = fminf(p1.x, fminf(p2.x, fminf(p3.x, p4.x))); *yMin = fminf(p1.y, fminf(p2.y, fminf(p3.y, p4.y))); *xMax = fmaxf(p1.x, fmaxf(p2.x, fmaxf(p3.x, p4.x))); *yMax = fmaxf(p1.y, fmaxf(p2.y, fmaxf(p3.y, p4.y))); } bool _purGLRectContainsAABB(_purGLRect *rect, purGLAABB *aabb) { // If max is less then, or min is greater then, then it is out of bounds. if (aabb->xMax < rect->x || aabb->yMax < rect->y || aabb->xMin > rect->x + rect->width || aabb->yMin > rect->y + rect->height) { return false; } return true; }
C
#pragma once struct Coord { int X; int Y; Coord(int x = 0, int y = 0) : X(x), Y(y) {} };
C
/** * Copyright (C) EEMBC(R). All Rights Reserved * * All EEMBC Benchmark Software are products of EEMBC and are provided under the * terms of the EEMBC Benchmark License Agreements. The EEMBC Benchmark Software * are proprietary intellectual properties of EEMBC and its Members and is * protected under all applicable laws, including all applicable copyright laws. * * If you received this EEMBC Benchmark Software without having a currently * effective EEMBC Benchmark License Agreement, you must discontinue use. */ #include "ee_profile.h" /** * These varaibles describe the generic buffer. The buffer is created via * LIBC malloc()/free(). */ uint8_t *gp_buff = NULL; size_t g_buff_size = 0u; size_t g_buff_pos = 0u; arg_claimed_t ee_buffer_parse(char *p_command) { char *p_next; if (th_strncmp(p_command, "db", EE_CMD_SIZE) != 0) { return EE_ARG_UNCLAIMED; } p_next = th_strtok(NULL, EE_CMD_DELIMITER); if (p_next == NULL) { th_printf("e-[Command 'db' requires a subcommand]\r\n"); } else if (th_strncmp(p_next, "load", EE_CMD_SIZE) == 0) { p_next = th_strtok(NULL, EE_CMD_DELIMITER); if (p_next == NULL) { th_printf("e-[Command 'db load' requires the # of bytes]\r\n"); } else { g_buff_size = (size_t)atoi(p_next); if (g_buff_size == 0) { th_printf("e-[Command 'db load' must be >0 bytes]\r\n"); } else { g_buff_pos = 0; if (gp_buff != NULL) { th_free(gp_buff); gp_buff = NULL; } gp_buff = (void *)th_malloc(g_buff_size); if (gp_buff == NULL) { th_printf("e-[Unable to malloc %u bytes]\r\n", g_buff_size); } else { th_printf("m-[Expecting %d bytes]\r\n", g_buff_size); } } } } else if (th_strncmp(p_next, "print", EE_CMD_SIZE) == 0) { if (gp_buff == NULL) { th_printf("e-[Buffer not allocated]\r\n"); } else { size_t i = 0; const size_t max = 8; for (; i < g_buff_size; ++i) { if ((i + max) % max == 0 || i == 0) { th_printf("m-buffer-"); } /* N.B. Not every `printf` supports the spacing prefix! */ th_printf("%02x", gp_buff[i]); if (((i + 1) % max == 0) || ((i + 1) == g_buff_size)) { th_printf("\r\n"); } else { th_printf("-"); } } if (i % max != 0) { th_printf("\r\n"); } } } else { size_t numbytes; char test[3]; long res; if (gp_buff == NULL) { th_printf("e-[Buffer not allocated]\r\n"); return EE_ARG_CLAIMED; } /* Two hexdigits per byte */ numbytes = th_strnlen(p_next, EE_CMD_SIZE); if ((numbytes & 1) != 0) { th_printf("e-[Insufficent number of hex digits]\r\n"); return EE_ARG_CLAIMED; } test[2] = 0; for (size_t i = 0; i < numbytes;) { test[0] = p_next[i++]; test[1] = p_next[i++]; res = ee_hexdec(test); if (res < 0) { th_printf("e-[Invalid hex digit '%s']\r\n", test); return EE_ARG_CLAIMED; } else { gp_buff[g_buff_pos] = (uint8_t)res; g_buff_pos++; if (g_buff_pos == g_buff_size) { th_printf("m-load-done\r\n"); /* Disregard the remainder of the digits when done. */ return EE_ARG_CLAIMED; } } } } return EE_ARG_CLAIMED; }
C
#include <stdio.h> #include <stdlib.h> #include "Grafo.h" int main(void){ Grafo *gr = cria_grafo(5, 5, 0); //Busca em profundidade int eh_digrafo = 1; insere_aresta(gr, 0, 1, eh_digrafo, 0); insere_aresta(gr, 1, 2, eh_digrafo, 0); insere_aresta(gr, 1, 3, eh_digrafo, 0); insere_aresta(gr, 2, 4, eh_digrafo, 0); insere_aresta(gr, 3, 0, eh_digrafo, 0); insere_aresta(gr, 3, 4, eh_digrafo, 0); insere_aresta(gr, 4, 1, eh_digrafo, 0); insere_aresta(gr, 4, 3, eh_digrafo, 0); float dist[5]; int ant[5]; busca_dijkstra(gr, 0, ant, dist); for(int i = 0; i < 5; i++){ printf("%i = %f -- %i\n",i, dist[i], ant[i]); } libera_grafo(gr); return 0; }
C
/* Title: consonants.c Description: This program takes command line arguments as input and prints out all the consonants in the input. Author: Omar Abdelrahman */ #include <stdio.h> #include <string.h> // Main function int main(int argc, char *argv[]){ // Declaring variables int i=0; char consonant[100]; for(i=1;i<argc;i++){ int j=0; // Copying each command line argument to the array strcpy(consonant,argv[i]); // Iterating over the array while(consonant[j]!='\0'){ // Checking each character to see if its a consonant and printing it if(((consonant[j] >= 'a' && consonant[j] <= 'z') || (consonant[j] >= 'A' && consonant[j] <= 'Z')) && !(consonant[j]=='a' || consonant[j]=='e' || consonant[j]=='i' || consonant[j]=='o' || consonant[j]=='u' || consonant[j]=='A' || consonant[j]=='E' || consonant[j]=='I' || consonant[j]=='O' || consonant[j]=='U')){ printf("%c",consonant[j]); } j++; // Incrementing to get next character } } printf("\n"); return 0; }
C
/** ****************************************************************************** * @file : bootloader.c * @brief : Functions related to bootloader * ---------------------------------------------------------------------------- * @author : Sebastian Popa * @date : Dec, 2020 ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "bootloader.h" #include "uartMsg.h" /* Private variables ---------------------------------------------------------*/ FLASH_EraseInitTypeDef EraseInitStruct; /* Functions declaration- ----------------------------------------------------*/ /*********************bootloader_JumpToUserApp********************************** ** * @brief Jumps to the user application located at a specified memory location. * Gets the user app Main Stack Pointer (MSP) and the address of the * user app reset_handler() function. * Calls user app reset_handler() to start execution of user app. * @param user_flash represents start of user flash memory address * @retval None */ void bootloader_JumpToUserApp(uint32_t user_flash) { typedef void (*pFunction)(void); union { uint32_t ulValue; pFunction pfnPointer; } uResetHandler; //---------------------------------------------------------------- // Jump to user application // //!- calculate jump address: reset handler of new application uResetHandler.ulValue = *(uint32_t volatile *) (user_flash + 4); //!- Initialize user application's Stack Pointer __set_MSP(user_flash); SCB->VTOR = 0x8040000; SysTick->CTRL = 0; //!- jump to application uResetHandler.pfnPointer(); #ifdef BOOTLOADER_1 // define a function pointer to user reset handler void (*user_reset_handler)(void); // set the MSP // MSP located at start of user flash (eg: @0x0800 8000) uint32_t user_msp_value = *((volatile uint32_t *) user_flash); __set_MSP(user_msp_value); // reset handler address is the next location (eg: @ 0x0800 8004) uint32_t user_reset_handler_address = *((volatile uint32_t*) (user_flash + 4U)); user_reset_handler = (void*) user_reset_handler_address; // cast to function pointer // call of user_reset handler starts execution of user app user_reset_handler(); #endif } /*********************bootloader_FlashEraseBank2******************************** ** * @brief This function erases Bank2 of the memory. (page 128 - page 255) * @param None * @retval HAL_FLASH_GetError */ uint32_t bootloader_FlashEraseBank2(void) { uint32_t Status = HAL_OK; HAL_FLASH_Unlock(); uint32_t BankNumber = 2; // uint32_t PageNumber; uint32_t PageError; //uint32_t src_addr = (uint32_t)DATA_64; /* Fill EraseInit structure*/ EraseInitStruct.TypeErase = FLASH_TYPEERASE_MASSERASE; EraseInitStruct.Banks = BankNumber; if (HAL_FLASHEx_Erase(&EraseInitStruct, &PageError) != HAL_OK) { Status = HAL_FLASH_GetError(); } HAL_FLASH_Lock(); return Status; } /*********************bootloader_FlashErasePage********************************* ** * @brief This function erases a number of pages starting from the specified * page number * @param Page, starting page to begin erase * @retval HAL_FLASH_GetError */ uint32_t bootloader_FlashErasePage(uint32_t Page) { uint32_t Status = HAL_OK; /* Unlock the Flash to enable the flash control register access *************/ HAL_FLASH_Unlock(); /* Clear OPTVERR bit set on virgin samples */ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR); uint32_t PageError; uint32_t BankNumber; uint32_t NumberPages; if (Page < 128) { BankNumber = FLASH_BANK_1; NumberPages = 127 - Page + 1; } else { BankNumber = FLASH_BANK_2; NumberPages = 255 - Page + 1; } /* Fill EraseInit structure*/ EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES; EraseInitStruct.Banks = BankNumber; EraseInitStruct.Page = Page; EraseInitStruct.NbPages = NumberPages; if (HAL_FLASHEx_Erase(&EraseInitStruct, &PageError) != HAL_OK) { Status = HAL_FLASH_GetError(); } HAL_FLASH_Lock(); return Status; } /*********************bootloader_FlashWrite************************************* ** * @brief This function writes 2KB of data starting from a given address * @param StartAddress is the starting address from where to start the flash write * @param DATA_64 is a pointer to an array of data to be written of size (32 x 64bit) * @retval HAL_FLASH_GetError */ uint32_t bootloader_FlashWrite(uint32_t StartAddress, uint64_t *DATA_64) { uint32_t Status = HAL_OK; HAL_FLASH_Unlock(); /* HAL_FLASH_Program() requires the address of the data to be flashed in u_integer * format (e.g. 0x2000008) and not pointer format. So we need to do the following * type casting. */ uint32_t data_address_uint = (uint32_t)DATA_64; // stores the address in integer format if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_FAST, StartAddress, (uint64_t)data_address_uint) != HAL_OK) { Status = HAL_FLASH_GetError(); } HAL_FLASH_Lock(); return Status; } /***************************END OF FILE****************************************/
C
#include <stdio.h> int main() { int a; int* ptrtoa; ptrtoa = &a; a = 5; printf("The value of a is %d\n", a); *ptrtoa = 6; printf("The value of a is %d\n", a); printf("The value of ptrtoa is %d\n", ptrtoa); printf("It stores the value %d\n", *ptrtoa); printf("The address of a is %d\n", &a); float d; float e; d = 5.5; e = 6.6; printf("The value of d is %f\n",d); printf("The address of d is %d\n", &d); printf("The value of e is %f\n",e); printf("The address of e is %d\n", &e); float *ptrtod = &d; float *ptrtoe = &e; float temp; temp = *ptrtod; *ptrtod = *ptrtoe; *ptrtoe = temp; printf(" d = %f, e = %f\n", *ptrtod, *ptrtoe); }
C
/** * @file slider.h * */ #ifndef GUI_SLIDER_H #define GUI_SLIDER_H #ifdef __cplusplus extern "C" { #endif /********************* * INCLUDES *********************/ #include "RTE_Include.h" #if GUI_USE_SLIDER != 0 /*Testing of dependencies*/ #if GUI_USE_BAR == 0 #error "slider: bar is required. Enable it in conf.h (GUI_USE_BAR 1) " #endif /********************* * DEFINES *********************/ /********************** * TYPEDEFS **********************/ /*Data of slider*/ typedef struct { bar_ext_t bar; /*Ext. of ancestor*/ /*New data for this type */ action_t action; /*Function to call when a new value is set*/ style_t *style_knob; /*Style of the knob*/ int16_t drag_value; /*Store a temporal value during press until release (Handled by the library)*/ uint8_t knob_in :1; /*1: Draw the knob inside the bar*/ }slider_ext_t; /*Built-in styles of slider*/ typedef enum { GUI_SLIDER_STYLE_BG, GUI_SLIDER_STYLE_INDIC, GUI_SLIDER_STYLE_KNOB, }slider_style_t; /********************** * GLOBAL PROTOTYPES **********************/ /** * Create a slider objects * @param par pointer to an object, it will be the parent of the new slider * @param copy pointer to a slider object, if not NULL then the new object will be copied from it * @return pointer to the created slider */ obj_t * slider_create(obj_t * par, obj_t * copy); /*===================== * Setter functions *====================*/ /** * Set a new value on the slider * @param slider pointer to a slider object * @param value new value */ static inline void slider_set_value(obj_t * slider, int16_t value) { bar_set_value(slider, value); } /** * Set a new value with animation on a slider * @param slider pointer to a slider object * @param value new value * @param anim_time animation time in milliseconds */ static inline void slider_set_value_anim(obj_t * slider, int16_t value, uint16_t anim_time) { bar_set_value_anim(slider, value, anim_time); } /** * Set minimum and the maximum values of a bar * @param slider pointer to the slider object * @param min minimum value * @param max maximum value */ static inline void slider_set_range(obj_t *slider, int16_t min, int16_t max) { bar_set_range(slider, min, max); } /** * Set a function which will be called when a new value is set on the slider * @param slider pointer to slider object * @param action a callback function */ void slider_set_action(obj_t * slider, action_t action); /** * Set the 'knob in' attribute of a slider * @param slider pointer to slider object * @param in true: the knob is drawn always in the slider; * false: the knob can be out on the edges */ void slider_set_knob_in(obj_t * slider, bool in); /** * Set a style of a slider * @param slider pointer to a slider object * @param type which style should be set * @param style pointer to a style */ void slider_set_style(obj_t *slider, slider_style_t type, style_t *style); /*===================== * Getter functions *====================*/ /** * Get the value of a slider * @param slider pointer to a slider object * @return the value of the slider */ int16_t slider_get_value(obj_t * slider); /** * Get the minimum value of a slider * @param slider pointer to a slider object * @return the minimum value of the slider */ static inline int16_t slider_get_min_value(obj_t * slider) { return bar_get_min_value(slider); } /** * Get the maximum value of a slider * @param slider pointer to a slider object * @return the maximum value of the slider */ static inline int16_t slider_get_max_value(obj_t * slider) { return bar_get_max_value(slider); } /** * Get the slider action function * @param slider pointer to slider object * @return the callback function */ action_t slider_get_action(obj_t * slider); /** * Give the slider is being dragged or not * @param slider pointer to a slider object * @return true: drag in progress false: not dragged */ bool slider_is_dragged(obj_t * slider); /** * Get the 'knob in' attribute of a slider * @param slider pointer to slider object * @return true: the knob is drawn always in the slider; * false: the knob can be out on the edges */ bool slider_get_knob_in(obj_t * slider); /** * Get a style of a slider * @param slider pointer to a slider object * @param type which style should be get * @return style pointer to a style */ style_t * slider_get_style(obj_t *slider, slider_style_t type); /********************** * MACROS **********************/ #endif /*GUI_USE_SLIDER*/ #ifdef __cplusplus } /* extern "C" */ #endif #endif /*GUI_SLIDER_H*/
C
#include<stdio.h> // PARIDADE // AULA 01 EXERCICIO 01 int par(int num){ if(num%2==0){ num=1; } else{ num=0; } return num; } int main(){ int n; printf("introduza o numero:\n"); scanf("%d",&n); if(par(n)==0){ printf("%d e' impar.\n",n); } else{ printf("%d e' par.\n",n); } return 0; }
C
/* ============================================================================ Name : PrimerParcialProgra.c Author : Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ Dada una estructura ePais cuyos campos son id(int), nombre(20 caracteres), infectados(int), recuperados(int) y muertos(int). Desarrollar una funcin llamada actualizarRecuperados que reciba el pas y los recuperados del dia y que acumule estos a los que ya tiene el pas. La funcin no devuelve nada. * */ #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct{ int id; char nombre[20]; int infectados; int recuperados; int muertos; }ePais; //1 void actualizarRecuperados(ePais pais, int recuperadosDelDia){ pais.recuperados = pais.recuperados + recuperadosDelDia; } //2 char invertirCadena(char cadena[]){ char auxCad; int largoCad; int j; if(cadena != NULL){ largoCad = strlen(cadena); j = largoCad; for(int i = 0 ; i<(largoCad/2); i++){ j--; auxCad = cadena[i]; cadena[i] = cadena[j]; cadena[j] = auxCad; } } return cadena; } //3 void ordenarCaracteres(char str[]){ int tamCadena = strlen(str); char auxChar; for(int i = 0; i < tamCadena-1; i++){ for(int j = i + 1; j < tamCadena; j++){ if(str[i] > str[j]){ auxChar = str[i]; str[i] = str[j]; str[j] = auxChar; } } } } int main(void) { char ordenar[10] = {"VACAFEA"}; char cadenaInvertida[10]; int recuperadosDelDia = 1000; ePais pais = {1,"Argentina",80000,35000,780}; actualizarRecuperados(pais, recuperadosDelDia); printf("1 - Recuperados totales a hoy: %d\n",pais.recuperados); strcpy(cadenaInvertida,invertirCadena(ordenar)); printf("2) Cadena %s que se invierte queda %s\n","VACAFEA",cadenaInvertida); ordenarCaracteres(ordenar); printf("3 - cadena %s que se ordena queda: %s\n","VACAFEA",ordenar); return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> // MANUAL POLYMORPHISM WITH C typedef struct iRenderer { void(*Render)(int x, int y); void(*Dispose)(); }iRenderer; typedef struct iInput { void(*GetKey)(struct iInput *self,int x); void(*Dispose)(struct iInput *self); }iInput; void SDL_Input_GetKey(iInput *self, int x) { printf("getting key from SDL_INPUT_GETKEY, key == %i\n", x); } void SDL_Input_Dispose(iInput *self) { printf("Disposing of SDL_Input\n"); //free(self); } void GFLW_Input_GetKey(iInput *self, int x) { printf("getting key from GFLW_INPUT_GETKEY, key == %i\n", x); } void GFLW_Input_Dispose(iInput *self) { printf("Disposing of GFLW_Input\n"); //free(self); } void Init_SDL_Input(iInput **input) { (*input) = (iInput*) malloc (sizeof(iInput)); (*input)->GetKey = &SDL_Input_GetKey; (*input)->Dispose = &SDL_Input_Dispose; } void Init_GFLW_Input(iInput **input) { (*input) = (iInput*) malloc(sizeof(iInput)); (*input)->GetKey = &GFLW_Input_GetKey; (*input)->Dispose = &GFLW_Input_Dispose; } typedef struct GAME { iRenderer *renderer_; iInput *input_; }GAME; int main() { GAME game; begin: { Init_SDL_Input(&game.input_); game.input_->GetKey(game.input_, 10); game.input_->Dispose(game.input_); Init_GFLW_Input(&game.input_); game.input_->GetKey(game.input_, 20); game.input_->Dispose(game.input_); } goto begin; }
C
/* ** EPITECH PROJECT, 2018 ** my_putstr ** File description: ** 1 */ #include "my_pushswap.h" void my_putstr(char *str) { int a; a = 0; while (str[a] != '\0'){ my_putchar(str[a]); a++; } }
C
#include "philo.h" static void init_data(t_philo *philo, char **argv, char argc) { philo->data.nbr_p = ft_atoi(argv[1]); philo->data.time_to_die = ft_atoi(argv[2]); philo->data.time_to_eat = ft_atoi(argv[3]); philo->data.time_to_sleep = ft_atoi(argv[4]); philo->data.nbr_time_eat = 0; if (argc == 6) philo->data.nbr_time_eat = ft_atoi(argv[5]); philo->philo_fed = 0; } static void init_philo(t_philo *philo) { int i; i = 0; philo->one_p = (struct s_one_p *)malloc(sizeof(t_one_p) \ * philo->data.nbr_p); if (!philo->one_p) return ; while (i <= philo->data.nbr_p) { philo->one_p[i].one_philo_dead = 0; philo->one_p[i].lst_time_eat = 0; philo->one_p[i].count_eat = 0; philo->one_p[i].index = i + 1; philo->one_p[i].stop_progr = 0; philo->one_p[i].main = philo; philo->one_p[i].data = philo->data; i++; } } static void init_forks(t_philo *philo) { int i; i = 0; philo->forks = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t) \ * philo->data.nbr_p); if (!philo->forks) return ; while (i < philo->data.nbr_p) { pthread_mutex_init(&philo->forks[i], NULL); i++; } } static void philos_forks(t_philo *philo) { int i; i = 0; while (i < philo->data.nbr_p) { if (i != philo->data.nbr_p - 1) { philo->one_p[i].left_f = &philo->forks[i]; philo->one_p[i].right_f = &philo->forks[i + 1]; } else { philo->one_p[i].left_f = &philo->forks[i]; philo->one_p[i].right_f = &philo->forks[0]; } i++; } } void parser(t_philo *philo, char **argv, int argc) { init_data(philo, argv, argc); init_philo(philo); init_forks(philo); philos_forks(philo); }
C
#include <stdio.h> #include <stdlib.h> int main(int argc,char *argv[]){ char mpoint[256]; int check=-1; strcpy(mpoint,"/mnt/tmp/mpoint_"); strcat(mpoint,argv[1]); check=setuid(0); if(check<0) perror("Setuid Error "); check=execl("/bin/umount","umount",mpoint,NULL); if(check<0) perror("Umount Error "); }
C
int smallest_number(int *array[], int size);
C
#include <math.h> #include <stdio.h> int main(int argc, char** argv) { int num_test_cases; scanf("%d", &num_test_cases); for(int i = 0; i < num_test_cases; i++) { int n; scanf("%d", &n); int pow = 5; int addend = 0; int res = 0; while((addend = n / pow) > 0) { res += addend; pow *= 5; } printf("%d\n", res); } return 0; }
C
/******************************************************************** * * File: ics9db1200.c * Name: * * Description: * Clock Buffer ICS chip lib * * * Copyright (c) 1985-2009 by Cisco Systems, Inc. * All rights reserved. * * *********************************************************************/ #include <stdio.h> #include <stdint.h> #include <string.h> #define ICS9DB1200_REG_COUNT 8 #define ICS9DB1200_FREQUENCY_SELECT 0x00 #define ICS9DB1200_OUTPUT_CONTROL_0 0x01 #define ICS9DB1200_OUTPUT_CONTROL_1 0x02 #define ICS9DB1200_OUTPUT_ENABLE_R0 0x03 #define ICS9DB1200_OUTPUT_ENABLE_R1 0x04 #define ICS9DB1200_VENDOR_REVISION 0x05 #define ICS9DB1200_DEVICE_ID 0x06 #define ICS9DB1200_BYTE_COUNT 0x07 extern int I2CByteRead_Block ( int Fh, unsigned char Bus, unsigned char Dev, unsigned char Reg, unsigned char *rxBuf, int bytes, int verbose); extern int I2CByteWrite_Block (int Fh, unsigned char Bus, unsigned char Dev, unsigned char *txBuf, int bytes, int verbose); int ics9db1200_rd(int fd, uint8_t bus, uint8_t i2c_addr, uint8_t addr, uint8_t *data, uint8_t data_sz) { return(I2CByteRead_Block(fd, bus, i2c_addr, addr, data, data_sz, 0)); } int ics9db1200_wr(int fd, uint8_t bus, uint8_t i2c_addr, uint8_t addr, uint8_t *data, uint8_t data_sz) { uint8_t wr_data[256+1]; wr_data[0] = addr; memcpy(wr_data+1, data, data_sz); return(I2CByteWrite_Block(fd, bus, i2c_addr, wr_data, data_sz+1, 0)); } static char *ics_reg_names[] = { "FREQUENCY_SELECT", "OUTPUT_CONTROL_0", "OUTPUT_CONTROL_1", "OUTPUT_CONTROL_READBACK_0", "OUTPUT_CONTROL_READBACK_1", "VENDOR_REVISION", "DEVICE_ID", "BYTE_COUNT", }; int ics9db1200_dump (int fd, uint8_t bus, uint8_t i2c_addr) { int rc; uint8_t data[ICS9DB1200_REG_COUNT+1], cnt; rc = ics9db1200_rd(fd, bus, i2c_addr, ICS9DB1200_FREQUENCY_SELECT, data, ICS9DB1200_REG_COUNT); if (rc) { printf(" Error: ics9db1200 rd (rc=%d)\n", rc); return (rc); } for (cnt = 0; cnt < ICS9DB1200_REG_COUNT; cnt++) { printf(" %-18s : 0x%X\n", ics_reg_names[cnt], data[cnt+1]); } return (rc); }
C
/* * * matrix.c * Tim Green * 3/20/14 * version 1.0 * * Project 3, Part 1 - Matrix Multiplication * */ #define M 3 #define K 2 #define N 3 #include <stdio.h> #include <stdlib.h> #include <pthread.h> void *CalcProduct(void *param); typedef struct v { int i; int j; } Element; // A[COLS] == B[ROWS] int A[M][K] = { {1,4}, {2,5}, {3,6} }; // 3x2 int B[K][N] = { {8,7,6}, {5,4,3} }; // 2x3 int C[M][N]; int main(void) { Element E[M][N]; pthread_t tid[M][N]; pthread_attr_t attr; int i, j; printf("Matrix A:\n"); for (i=0; i<M; i++) { for (j=0; j<K; j++) printf("%d ", A[i][j]); printf("\n"); } printf("\n"); printf("Matrix B:\n"); for (i=0; i<K; i++) { for (j=0; j<M; j++) printf("%d ", B[i][j]); printf("\n"); } printf("\n"); // Explicitly create joinable threads, even though it should be the default. pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i=0; i<M; i++) { for (j=0; j<N; j++) { E[i][j].i = i; E[i][j].j = j; int rc = pthread_create(&tid[i][j], &attr, CalcProduct, (void *) &E[i][j]); if (rc) { perror("[ERROR]"); exit(EXIT_FAILURE); } } } pthread_attr_destroy(&attr); for (i=0; i<M; i++) { for (j=0; j<N; j++) { int rc = pthread_join(tid[i][j], NULL); if (rc) { printf("[ERROR]: return code from pthread_join is %d", rc); exit(EXIT_FAILURE); } } } printf("Matrix C = AB\n"); for (i=0; i<M; i++) { for (j=0; j<N; j++) printf("%d ", C[i][j]); printf("\n"); } printf("\n"); pthread_exit(NULL); } /* * * This function builds a sum of i products. Take element i of row j from Matrix A, * and multiply it by element i of column k from Matrix B. The result is stored in a * global data structure so no value is returned. * */ void *CalcProduct(void *param) { Element *row_col = (Element *) param; int i; const int ROW = row_col->i; const int COL = row_col->j; C[ROW][COL] = 0; for (i=0; i<K; i++) C[ROW][COL] += (A[ROW][i] * B[i][COL]); pthread_exit(NULL); }
C
/* * Soubor: proj2.c * Datum: 20.11.2014 * Autor: Adam Bezak - 1BIA - xbezak01@stud.fit.vutbr.cz * Projekt: Iteracne vypocty * Popis: Implementujte vypocet vzdalenosti a vysky mereneho objektu pomoci udaju ze senzoru * natoceni mericiho pristroje. Vypocet provedte pouze pomoci matematickych operaci +,-,*,/. * */ #include <stdio.h> // vstup a vystup #include <string.h> // strtod #include <stdlib.h> // vseobecne funkcie #include <math.h> // tangens #define ERR_TOO_FEW_ARGS 11 #define ERR_TOO_MANY_ARGS 12 #define ERR_UNDEFINED_ARG 13 #define ERR_INVALID_LIMITS 14 #define ARGV_MAX_COUNT 5 #define TRUE 1 #define ACTION_HELP 1 #define ACTION_TAN 2 #define ACTION_RANGE 3 #define RADIANS 0 #define WHERE_N 1 #define WHERE_M 2 #define RADIANS_A 0 #define RADIANS_B 1 #define HEIGHT 2 #define UNDEF -1 #define MAX 14 #define MAX_RAD 1.4 #define CONST_HEIGHT 1.5 #define MAX_HEIGHT 100 #define ITERATIONS 9 /* konstanty */ const long long citatel[] = {1, 1, 2, 17, 62, 1382, 21844, 929569, 6404582, 443861162, 18888466084, 113927491862, 58870668456604}; const long long menovatel[] = {1, 3, 15, 315, 2835, 155925, 6081075, 638512875, 10854718875, 1856156927625, 194896477400625, 49308808782358125, 3698160658676859375}; /* protypy funkcii */ int parse_args(int argc, char *args[], int *action, double *params_tan, double *params_range); // kontrola argumentov a spracovanie void print_errors(int error); // vypis errorov void help(); // vypis napovedy void iteration_tan(double *params_tan); // iteracie tangens void iteration_range(double *params_range, int argc); // iteracie vypocet vzdialenosti double taylor_tan(double x, unsigned int n); // taylorov polynom double cfrac_tan(double x, unsigned int n); // zretazeny zlomok double f_ak(int i, double x); // pomocna funkcia pri vypocte zretazeneho zlomku int f_bk(int i); // pomocna funkcia pri vypocte zretazeneho zlomku double myabs(double n); // absolutna hodnota /* MAIN */ int main(int argc, char *argv[]) { int action, setup_result; double params_tan[3]; // pomocne pole pre vypocet tangensu double params_range[3]; // pomocne pole pre vypocet vzdialenosti setup_result = parse_args(argc, argv, &action, params_tan, params_range); if (setup_result != TRUE) { print_errors(setup_result); return setup_result; } switch (action) { // switch vyhodnoti dany case na zaklade funkcie parse_args v ktorej sa meni hodnota premennej action (odkazom) case ACTION_HELP: help(); break; case ACTION_TAN: iteration_tan(params_tan); break; case ACTION_RANGE: iteration_range(params_range, argc); break; } return 0; } int parse_args(int argc, char *args[], int *action, double *params_tan, double *params_range) { //////////////////// INICIALIZIACIA //////////////////// *action = 0; argc --; char *endptr = NULL; params_tan[RADIANS] = UNDEF; params_tan[WHERE_N] = UNDEF; params_tan[WHERE_M] = UNDEF; params_range[RADIANS_A] = UNDEF; params_range[RADIANS_B] = UNDEF; params_range[HEIGHT] = CONST_HEIGHT; //////////////////// ACTION /////////////////////// if (argc < 1) return ERR_TOO_FEW_ARGS; // max parametrov 5 - [-c X] -m A [B] if (argc > ARGV_MAX_COUNT) return ERR_TOO_MANY_ARGS; if (strcmp(args[1], "--help") == 0){ if (argc > 1) return ERR_TOO_MANY_ARGS; *action = ACTION_HELP; return TRUE; } else if (strcmp(args[1], "--tan") == 0) *action = ACTION_TAN; else if (argc == 2) { // ak su argumenty ./proj2 -m A if (strcmp(args[1], "-m") == 0) { params_range[RADIANS_A] = strtod(args[2], &endptr); if (*endptr != '\0') return ERR_UNDEFINED_ARG; // ak argument A nie je cislo if (params_range[RADIANS_A] < 0) return ERR_INVALID_LIMITS; // ak argument A je mensi ako 0 *action = ACTION_RANGE; } else return ERR_UNDEFINED_ARG; } else if (argc == 3) { // ./proj2 -m A B if (strcmp(args[1], "-m") == 0) { params_range[RADIANS_A] = strtod(args[2], &endptr); if (*endptr != '\0') return ERR_UNDEFINED_ARG; params_range[RADIANS_B] = strtod(args[3], &endptr); if (*endptr != '\0') return ERR_UNDEFINED_ARG; if ((params_range[RADIANS_A] < 0) || (params_range[RADIANS_B]) < 0) return ERR_INVALID_LIMITS; *action = ACTION_RANGE; } else return ERR_UNDEFINED_ARG; } else if (argc == 4) { // ./proj2 -c X -m A if (strcmp(args[1], "-c") == 0) { params_range[HEIGHT] = strtod(args[2], &endptr); if (*endptr != '\0') return ERR_UNDEFINED_ARG; if (params_range[HEIGHT] < 0) return ERR_INVALID_LIMITS; } else return ERR_UNDEFINED_ARG; if (strcmp(args[3], "-m") == 0) { params_range[RADIANS_A] = strtod(args[4], &endptr); if (*endptr != '\0') return ERR_UNDEFINED_ARG; if (params_range[RADIANS_A] < 0) return ERR_INVALID_LIMITS; *action = ACTION_RANGE; } else return ERR_UNDEFINED_ARG; } else if (argc == 5) { // ./proj2 -c X -m A B if (strcmp(args[1], "-c") == 0) { params_range[HEIGHT] = strtod(args[2], &endptr); if (*endptr != '\0') return ERR_UNDEFINED_ARG; if (params_range[HEIGHT] < 0) return ERR_INVALID_LIMITS; } else return ERR_UNDEFINED_ARG; if (strcmp(args[3], "-m") == 0) { params_range[RADIANS_A] = strtod(args[4], &endptr); if (*endptr != '\0') return ERR_UNDEFINED_ARG; if (params_range[RADIANS_A] < 0) return ERR_INVALID_LIMITS; } else return ERR_UNDEFINED_ARG; *action = ACTION_RANGE; params_range[RADIANS_B] = strtod(args[5], &endptr); if (*endptr != '\0') return ERR_UNDEFINED_ARG; if (params_range[RADIANS_B] < 0) return ERR_INVALID_LIMITS; } else return ERR_UNDEFINED_ARG; switch (*action) { case ACTION_TAN: if (argc < 4) return ERR_TOO_FEW_ARGS; if (argc > 4) return ERR_TOO_MANY_ARGS; params_tan[RADIANS] = strtod(args[2], &endptr); if (*endptr != '\0') return ERR_UNDEFINED_ARG; params_tan[WHERE_N] = strtod(args[3], &endptr); if (*endptr != '\0') return ERR_UNDEFINED_ARG; params_tan[WHERE_M] = strtod(args[4], &endptr); if (*endptr != '\0') return ERR_UNDEFINED_ARG; if ((params_tan[RADIANS] < 0) || (params_tan[WHERE_N] < 0)) return ERR_INVALID_LIMITS; break; } for (int i = 0; i!=3; i++) { // iteracia na poli params_tan, ak nejaka hodnota == 0 tak error if ((params_tan[i] == 0) || (params_range[i] == 0)) { return ERR_INVALID_LIMITS; } } /* kontrola podmienok zo zadania projektu */ if ( (params_tan[WHERE_M] < params_tan[WHERE_N]) || (params_tan[WHERE_M] > MAX) || (params_tan[RADIANS] > MAX_RAD) ) { return ERR_INVALID_LIMITS; } if ( (params_range[RADIANS_A] > MAX_RAD) || (params_range[RADIANS_B] > MAX_RAD) || (params_range[HEIGHT] > MAX_HEIGHT) ) { return ERR_INVALID_LIMITS; } return TRUE; } void iteration_tan(double *params_tan) { double math_tan = tan(params_tan[RADIANS]); // tangens uhla z math.h double result_taylor, result_cfrac; double f_abs_taylor, f_abs_cfrac; for(int i = (int) params_tan[WHERE_N] ; i<=params_tan[WHERE_M]; i++) { // iterovanie i s pociatocnou hodnotou zadanou od uzivatela (params_tan[WHERE_N]) result_taylor = taylor_tan(params_tan[RADIANS], (unsigned int) i); // do funkcie taylor_tan sa posiela zadany uhol a dane i result_cfrac = cfrac_tan(params_tan[RADIANS], (unsigned int) i); // do funkcie cfrac_tan sa posiela zadany uhol a dane i f_abs_taylor = myabs(result_taylor - math_tan); // absolutna odchylka medzi vysledkom z taylorovho polynomu a matematickou knihovnou f_abs_cfrac = myabs(result_cfrac - math_tan); // absolutna odchylka medzi zretazenym zlomkom a matematickou knihovnou printf("%d %e %e %e %e %e\n", (int) i, math_tan, result_taylor, f_abs_taylor, result_cfrac, f_abs_cfrac); // vypis vysledku } } void iteration_range(double *params_range, int argc) { argc--; double result_alfa, result_beta, range, height; if ((argc == 2) && ((params_range[RADIANS_B] != UNDEF) || (params_range[HEIGHT] != MAX_HEIGHT))) { // ak bolo zadane len ./proj2 -m A result_alfa = cfrac_tan(params_range[RADIANS_A], ITERATIONS); // do funkcie cfrac_tan sa posiela zadany uhol A a pocet iteracii (9) range = (params_range[HEIGHT] / result_alfa); // matematicky vzorec, podla vztahov goniometrickych funkcii v pravouhlom trojuholniku printf("%e\n", range); } else if ((argc == 3) && (params_range[HEIGHT] != MAX_HEIGHT)) { // ./proj2 -m A B result_alfa = cfrac_tan(params_range[RADIANS_A], ITERATIONS); result_beta = cfrac_tan(params_range[RADIANS_B], ITERATIONS); range = (params_range[HEIGHT] / result_alfa); height = (params_range[HEIGHT] + (result_beta * range)); printf("%.10e\n%.10e\n", range, height); } else if ((argc == 4) && (params_range[RADIANS_B]) == UNDEF) { // ./proj2 -c X -m A result_alfa = cfrac_tan(params_range[RADIANS_A], ITERATIONS); range = (params_range[HEIGHT] / result_alfa); printf("%.10e\n", range); } else if (argc == 5) { // ./proj2 -c X -m A B result_alfa = cfrac_tan(params_range[RADIANS_A], ITERATIONS); result_beta = cfrac_tan(params_range[RADIANS_B], ITERATIONS); range = (params_range[HEIGHT] / result_alfa); height = (params_range[HEIGHT] + (result_beta * range)); printf("%.10e\n%.10e\n", range, height); } } double taylor_tan(double x, unsigned int n) { double result; double help_y; unsigned int i = 0; double x_x = x*x; result = help_y = (x * citatel[i]/menovatel[i]); // pociatocny stav vysledku for(i = 1; i < n; i++) { // cyklus je true pokial i < pocet iteracii z iteration_tan x = x * x_x; // zo vzorca x^2 help_y = (x * citatel[i]/menovatel[i]); result += help_y; } return result; } double cfrac_tan(double x, unsigned int n) { double result = 0.0; double ak, bk; for (unsigned int i = n; i > 0; i--) { // dekrementovanie i, pretoze zretazeny zlomok treba pocitat od konca ak = f_ak(i, x); bk = f_bk(i); result = (ak / (bk + result)); } return result; } double f_ak(int i, double x){ // ak i > 1 tak je minus.. podla vzorca return i > 1 ? -(x*x) : x; } int f_bk(int i){ // 1,3,5,7 .... return (2*i)-1; } double myabs(double n) { return n < 0 ? -n : n; } void print_errors(int error) { fprintf(stderr, "Chyba: "); switch (error) { case ERR_TOO_FEW_ARGS: fprintf(stderr, "Zadal si malo argumentov, napis --help pre napovedu.\n"); break; case ERR_TOO_MANY_ARGS: fprintf(stderr, "Zadal si vela argumentov, napis --help pre napovedu.\n"); break; case ERR_UNDEFINED_ARG: fprintf(stderr, "Zadal si nedefinovane argumenty, napis --help pre napovedu.\n"); break; case ERR_INVALID_LIMITS: fprintf(stderr, "Zadal si zle limity alebo 0, napis --help pre napovedu.\n"); break; } } void help() { printf ("\n-------------------------------NAPOVEDA-------------------------------\n" "\nPopis programu:\n" "\nImplementujte vypocet vzdalenosti a vysky mereneho objektu pomoci udaju ze senzoru\n" "natoceni mericiho pristroje. Vypocet provedte pouze pomoci matematickych operaci +,-,*,/.\n" "\nARGUMENTY PROGRAMU:\n" "\nArgument --help: \n" "-------Pri zadani argumentu --help sa vytiskne napoveda pouzivani programu.\n" "-------Tento argument funguje len samostatne!\n" "\nArgument --tan\n" "\nVzor: --tan A N M\n" "\nVypise tangens radianu A z math.h, tangens pomocou taylorovho polynomu, odchylku\n " "\ntangens pomocou zretazenych zlomkov a jeho odchylku\n" "\nArgument -m\n" "\nVzor: [-c X] -m -A [B] // udaje v zatvorkach su nepovinne\n" "\n-c X : vyska 'cloveka'\n" "\n-m A : uhol alfa\n" "\n[B] : uhol beta\n" "\nPoradie argumentov je pevne dane a nemoze sa lubovolne zamienat!!!\n"); }
C
//640p 6 #include <stdio.h> #define SET_BIT(n,pos) ( n |= (0x01 << pos) )// SET Ʈ ũ #define CLR_BIT(n,pos) ( n &= (~0x01 << pos) )// CLR Ʈ ũ #define GET_BIT(n,pos) ( (n >> pos) & 0x01 )// GET Ʈ ũ void main(void) { int n; printf("Enter n "); scanf_s("%d", &n);// Ʈ Է printf("SET_BIT : %d \n", SET_BIT(n, 1));// SET Ʈ printf("CLR_BIT : %d \n", CLR_BIT(n, 0));// CLR Ʈ printf("GET_BIT : %d \n", GET_BIT(n, 1));// GET Ʈ }
C
#include <stdio.h> #include <stdlib.h> main() { incre(); incre(); incre(); } incre() { static char var =65; printf("\n The character stored in var is %c ",var++); }
C
#ifndef _VECTOR_H #define _VECTOR_H #include <assert.h> #include <stdlib.h> #define STRUCT_BODY(type) \ struct { \ size_t size : 54, on_heap : 1, capacity : 6, flag1 : 1, flag2 : 1, \ flag3 : 1; \ type *ptr; \ } #define NEXT_POWER_OF_2(s) \ (s & (s - 1)) == 0 \ ? s \ : (size_t) 1 << (64 - __builtin_clzl(s)) /* next power of 2 */ #define v(t, s, name, ...) \ _Static_assert(__builtin_strncmp(#t, "void", 4), "error type"); \ union { \ STRUCT_BODY(t); \ struct { \ size_t filler; \ t buf[NEXT_POWER_OF_2(s)]; \ }; \ } name __attribute__((cleanup(vec_free))) = {.buf = {__VA_ARGS__}}; \ name.size = sizeof((__typeof__(name.buf[0])[]){0, __VA_ARGS__}) / \ sizeof(name.buf[0]) - \ 1; \ name.capacity = sizeof(name.buf) / sizeof(name.buf[0]) #define vec_size(v) v.size #define vec_capacity(v) \ (v.on_heap ? (size_t) 1 << v.capacity : sizeof(v.buf) / sizeof(v.buf[0])) #define vec_data(v) (v.on_heap ? v.ptr : v.buf) /* always contiguous buffer */ #define vec_elemsize(v) sizeof(v.buf[0]) #define vec_pos(v, n) \ *(__typeof__(v.buf[0]) *) __vec_pos(&v, n, vec_elemsize(v)) #define vec_reserve(v, n) __vec_reserve(&v, n, vec_elemsize(v), vec_capacity(v)) #define vec_push_back(v, e) \ __vec_push_back(&v, &(__typeof__(v.buf[0])[]){e}, vec_elemsize(v), \ vec_capacity(v)) #define vec_pop_back(v) \ assert(v.size > 0); \ v.size -= 1 #define display(v) \ do { \ for (size_t i = 0; i < vec_size(v); i++) \ printf("%d ", vec_pos(v, i)); \ puts(v.on_heap ? "heap" : "stack"); \ } while (0) #define vec_front(v) vec_pos(v, 0) #define vec_back(v) vec_pos(v, v.size - 1) #define vec_insert(v, p, e) \ do { \ assert(p >= 0 && p < v.size); \ __typeof__(v.buf[0]) __tmp; \ for (int i = 0; i < (signed) v.size; i++) { \ if (i == p) { \ __tmp = vec_pos(v, i); \ vec_pos(v, i) = e; \ } else if (i > p) { \ __typeof__(v.buf[0]) __t; \ __t = __tmp; \ __tmp = vec_pos(v, i); \ vec_pos(v, i) = __t; \ } \ } \ vec_push_back(v, __tmp); \ } while (0) #define vec_insert_n(v, p, n, e) \ do { \ assert(p >= 0 && p < v.size); \ assert(n > 0); \ __typeof__(v.buf[0]) *__tmp = \ malloc(sizeof(__typeof__(v.buf[0])) * (v.size - p)); \ int cnt = 0; \ for (int i = 0; i < (signed) v.size; i++) { \ if (i >= p) { \ __tmp[cnt++] = vec_pos(v, i); \ } \ } \ for (int i = 0; i < (signed) v.size - p; i++) \ vec_pop_back(v); \ vec_reserve(v, v.size + n + cnt); \ for (int i = 0; i < n; i++) \ vec_push_back(v, e); \ for (int i = 0; i < cnt; i++) \ vec_push_back(v, __tmp[i]); \ free(__tmp); \ } while (0) #define NON_NULL __attribute__((nonnull)) static NON_NULL void __attribute__((unused)) vec_free(void *p) { STRUCT_BODY(void) *s = p; if (s->on_heap) free(s->ptr); } static inline int ilog2(size_t n) { return 64 - __builtin_clzl(n) - ((n & (n - 1)) == 0); } NON_NULL void __vec_reserve(void *vec, size_t n, size_t elemsize, size_t capacity); NON_NULL void __vec_push_back(void *restrict vec, void *restrict e, size_t elemsize, size_t capacity); NON_NULL void *__vec_pos(void *vec, size_t n, size_t elemsize); #endif
C
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<fcntl.h> #include<sys/stat.h> int main(int argc,char *argv[]){ if(argc!=2){ printf("usage:access<pathname>"); } if(access(argv[1],R_OK)<0){ printf("access error for %s\n",argv[1]); } else printf("read access OK\n"); if(open(argv[1],O_RDONLY)<0){ printf("open error for %s\n",argv[1]); } else printf("open for reading OK\n"); exit(0); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { FILE *file = fopen(argv[1], "r"); if (file == NULL) { printf("empty file"); return 0; } unsigned short x; fscanf(file, "%d", &x); printf("%d", x); unsigned short n, v; char action[5]; while (fscanf(file, "%s%d%d", action, n, v) == 3) { if (strcmp(action, "set") == 0) { set(x, n, v); } if (strcmp(action, "comp") == 0) { comp(x, v); } if (strcmp(action, "get") == 0) { get(x, v); } else { printf("invalid file"); return 0; } } } void set(unsigned short x, unsigned short n, unsigned short v) { } void comp(unsigned short x, unsigned short v) { } void get(unsigned short x, unsigned short v) { }
C
#include "ficheros.h" /* 1.Pasarlo como argumento escribiéndolo en consola y utilizar la función strlen() para calcular su longitud 2.Pasarlo como argumento haciendo el cat de cualquier fichero, por ejemplo un fichero.c de vuestra práctica de la siguiente manera: “$(cat dir_practica/fichero.c)” 3.Asignarlo a un buffer desde código de esta manera: char buffer[tamanyo]; strcpy (buffer, "blablabla..."); 4.Pasar como argumento el nombre de un fichero externo que contenga el texto */ int main(int argc, char **argv){ struct superbloque SB; int ninodo; const char *dir; unsigned int length; length = strlen(argv[2]); char *buf = malloc(length); int inodos, nBytes = 0; int offset[5] = {9000, 209000, 30725000, 409605000, 480000000}; struct STAT p_stat; struct tm * info; char afecha[24], cfecha[24], mfecha[24]; if(argv[1] == NULL || argv[2] == NULL || argv[2] == NULL || argv[3] == NULL){ fprintf(stderr,"La sintaxi correcta es: escribir <nombre_dispositivo> <\"$(cat fichero)\"> <diferentes_inodos>\n"); return EXIT_FAILURE; } dir = argv[1]; inodos = atoi(argv[3]); bmount(dir); bread(posSB, &SB); if(inodos == 0){ // si la opción de diferentes inodos es 0 ninodo = reservar_inodo('f', 6); //reservamos inodo r/w strcpy(buf, argv[2]); //copiamos el texto pasado por parámetro a un buffer for(int i = 0; i < 5; i++){ //para cada offset el mismo inodo fprintf(stderr, "El nº de inodo reservado es: %i\n", ninodo); fprintf(stderr, "Offset: %i\n", offset[i]); nBytes += mi_write_f(ninodo, buf, offset[i], length);//sumamos en una variable los bytes escritos mi_stat_f(ninodo, &p_stat); strftime(afecha, 24, "%a %d-%m-%Y %H:%M:%S", info = localtime(&p_stat.atime)); strftime(cfecha, 24, "%a %d-%m-%Y %H:%M:%S", info = localtime(&p_stat.ctime)); strftime(mfecha, 24, "%a %d-%m-%Y %H:%M:%S", info = localtime(&p_stat.mtime)); fprintf(stderr, "DATOS INODO %i\n\ tipo=%c\n\ permisos=%i\n\ atime: %s\n\ ctime: %s\n\ mtime: %s\n\ nlinks: %i\n\ tamEnBytesLog=%i\n\ numBloquesOcupados=%i\n", ninodo, p_stat.tipo, p_stat.permisos, afecha, cfecha, mfecha, p_stat.nlinks, p_stat.tamEnBytesLog, p_stat.numBloquesOcupados); } } else if(inodos == 1){ strcpy(buf, argv[2]); for(int i = 0; i < 4; i++){ ninodo = reservar_inodo('f', 6); fprintf(stderr, "El nº de inodo reservado es: %i\n", ninodo); fprintf(stderr, "Offset: %i\n", offset[i]); nBytes += mi_write_f(ninodo, buf, offset[i], length); mi_stat_f(ninodo, &p_stat); strftime(afecha, 24, "%a %d-%m-%Y %H:%M:%S", info = localtime(&p_stat.atime)); strftime(cfecha, 24, "%a %d-%m-%Y %H:%M:%S", info = localtime(&p_stat.ctime)); strftime(mfecha, 24, "%a %d-%m-%Y %H:%M:%S", info = localtime(&p_stat.mtime)); fprintf(stderr, "DATOS INODO %i\n\ tipo=%c\n\ permisos=%i\n\ atime: %s\n\ ctime: %s\n\ mtime: %s\n\ nlinks: %i\n\ tamEnBytesLog=%i\n\ numBloquesOcupados=%i\n", ninodo, p_stat.tipo, p_stat.permisos, afecha, cfecha, mfecha, p_stat.nlinks, p_stat.tamEnBytesLog, p_stat.numBloquesOcupados); } } else{ fprintf(stderr, "No es una opción de inodo válida, %i", inodos); } bumount(dir); return EXIT_SUCCESS; }
C
#ifndef MAIN_H #define MAIN_H /* begin standard C header files */ #include <stdlib.h> #include <stdarg.h> #include <unistd.h> #include <limits.h> #include <stdio.h> /* macros */ #define BUFSIZE 1024 #define TRUE (1 == 1) #define FALSE !TRUE #define LOWHEX 0 #define UPHEX 1 /* structs */ /** * struct inventory_s - inventory of common variables needed * @fmt: the input format string * @i: index to traverse the format string * @args: the variadic arguments list of input arguments * @buffer: buffer to be written to before writing to stdout * @buf_index: index to traverse the buffer, also total chars written * @flag: notifies if there was a modifier flag * @space: notifies if space was printed * @c0: character to be written to buffer * @c1: character checking after % character * @c2: character to check 2 spaces after % symbol * @c3: unused for now, but may become a third specifier * @error: indicates error or not (0 no error, 1 error) */ typedef struct inventory_s { const char *fmt; int i; va_list *args; char *buffer; int buf_index; int flag; int space; char c0; char c1; char c2; char c3; int error; } inventory_t; /** * struct matches_s - printf specifiers and paired function * @ch: the specifier * @func: pointer to the conversion specifier function */ typedef struct matches_s { char ch; void (*func)(inventory_t *inv); } matches_t; /* initializing and ending functions */ int _printf(const char *format, ...); inventory_t *build_inventory(va_list *args_list, const char *format); int end_func(inventory_t *arg_inv); /* custom memory allocation and buffer */ void *_calloc(unsigned int nmemb, unsigned int size); void *_realloc(void *ptr, unsigned int old_size, unsigned int new_size); void write_buffer(inventory_t *inv); void puts_buffer(inventory_t *inv, char *str); /* string functions */ void rev_string(char *s); int _strlen(char *s); int _strlenconst(const char *s); int _putchar(char c); void puts_mod(char *str, unsigned int l); /* parse and match functionality */ void (*match_specifier(inventory_t *inv))(inventory_t *inv); void parse_specifiers(inventory_t *inv); /* hexadecimal */ void print_hex(inventory_t *inv, unsigned long int n, int hexcase, int size); void print_longlowhex(inventory_t *inv); void print_longuphex(inventory_t *inv); void print_lowhex(inventory_t *inv); void print_uphex(inventory_t *inv); /* integers */ void print_integers(inventory_t *inv, long int n); void print_int(inventory_t *inv); void print_longint(inventory_t *inv); void print_unsign(inventory_t *inv, unsigned long int n); void print_uint(inventory_t *inv); void print_ulongint(inventory_t *inv); /* octals */ void print_oct(inventory_t *inv, unsigned long int n, int size); void print_oct2(inventory_t *inv); void print_longoct(inventory_t *inv); /* handles specifier functions */ void print_char(inventory_t *inv); void print_string(inventory_t *inv); void print_string_hex(inventory_t *inv); void print_pointer(inventory_t *inv); void print_rev_string(inventory_t *inv); void print_rot13(inventory_t *inv); void print_percent(inventory_t *inv); void print_binary(inventory_t *inv); #endif /* end include guard for header files */
C
#include <stdio.h> #include <stdlib.h> #define MAXN 100//Ʒ int w[MAXN],V[MAXN]; int C;// int n;//Ʒ int d[MAXN][MAXN]; int jMax; int min(int,int); //֮Сֵ int max(int,int); //ֵ֮ void print_ans(int d[][MAXN],int,int); //ŽⲢ int main() { int i,j; printf("Ʒn(1-100):\n"); scanf("%d",&n); printf("ÿ\n"); for(i=1; i<=n; i++) { scanf("%d",&w[i]); } printf("ÿļֵ\n"); for(i=1; i<=n; i++) { scanf("%d",&V[i]); } printf("뱳C\n"); scanf("%d",&C); jMax=min(C,w[n]-1); for(j=0; j<=jMax; j++) d[n][j]=0; for(j=w[n]; j<=C; j++) d[n][j]=V[n]; for(i=n-1; i>1; i--) { jMax=min(C,w[i]-1); for(j=0; j<=jMax; j++) d[i][j]=d[i+1][j]; for(j=w[i]; j<=C; j++) d[i][j]=max(d[i+1][j],d[i+1][j-w[i]]+V[i]); } d[1][C]=d[2][C]; if(C>=w[i]) d[1][C]=max(d[1][C],d[2][C-w[i]]+V[1]); printf("ɣ%d\n",d[1][C]); return 0; } int min(int x,int y) { if(x>y) return y; else return x; } int max(int x,int y) { if(x<y) return y; else return x; }
C
/************************************************************** Problem: 1337 User: jhyunlee Language: C++ Result: Success Time:1 ms Memory:1092 kb ****************************************************************/ #include<stdio.h> #include<malloc.h> int main() { int N; int map[100+1][100+1]; //freopen("DATA.txt", "r", stdin); scanf("%d", &N); int x1=1, x2=N, y1=1, y2=N; int num=-1; int x = x1, y = y2; for (int i = N; i >= 1; i--) for (int j = 1; j <= N; j++) map[i][j] = 0; while (map[y][x] == 0) { x = x1, y = y2; while( (x<=x2)&&(y>=y1)){ map[y--][x++] = (num >= 9)? num = 0: ++num; } x2--; y2--; x = x2; y = y1; while ((x>=x1)&&(y==y1)){ map[y][x--] = (num >= 9) ? num = 0 : ++num; } y1++; x2--; x = x1; y = y1; while((x==x1)&&(y<=y2)){ map[y++][x] = (num >= 9) ? num = 0 : ++num; } x1++; y2--; x = x1; y = y2; } for (int i = N; i >= 1; i--) { for (int j = 1; j <= N-i+1; j++) { printf("%d ", map[i][j]); } printf("\n"); } return 1; }
C
#include"fct_aux.h" /* ensures retourne 1 si la case selectionnee est valide 0 sinon */ int is_valid_indice(char str[4], int n) { int tmp; char *buftmp; if (str[0]<'a' || str[0]>'a'+n-1) return 0; buftmp = str; /* on utilise buftmp pour ne pas modifier str */ buftmp++; tmp = (int) strtol(buftmp, NULL, 10); if (tmp < 1 || tmp > n) return 0; return 1; } /* requires 0 <= i < len(tab), tab[i] pile non vide ensures retourne 1 si la case i contient des pieces blanches, 0 sinon */ int is_white(stack *tab, int i) { char *buf; buf = malloc(3*sizeof(char)); buf = top(&tab[i]); return (buf[1] == 'B'); } /* requires str est une case valide du jeu ensures retourne l'indice du talbeau de jeu correspondant à la case selectionnee par le joueur */ int get_indice(char str[4], int n) { int line; int col; char *buftmp; col = str[0] - 'a'; buftmp = str; /* on utilise buftmp pour ne pas modifier str */ buftmp++; line = n - strtol(buftmp, NULL, 10); return (n*line + col); } /* requires *white et *black valides, tab de taille n*n assigns modifie white et black ensures white (resp black) contient le nombre de pieces blanches (resp noires) */ void count_pcs(stack *tab, int n, int *white, int *black) { int i; for (i=0 ; i<n*n ; i=i+1) { if (is_empty(tab[i])) ; else if (is_white(tab, i)) *white = *white + 1; else *black = *black + 1; } } /* requires tab de taille n*n, old et new indices valides ensures retourne 1 si le deplacement de old a new ne pass pas au-dessus d'une autre piece, 0 sinon */ int is_jumping(stack *tab, int n, int old, int new) { int i_old[2]; int i_new[2]; int i; int j; i_old[0] = old/n; i_old[1] = old%n; i_new[0] = new/n; i_new[1] = new%n; /* sur une meme ligne */ if (i_old[0] == i_new[0]) { if (i_old[1] > i_new[1]) { for (i=1; i<i_old[1]-i_new[1]; i=i+1) if (!is_empty(tab[old-i])) return 0; } else { for (i=1; i<i_new[1]-i_old[1]; i=i+1) if (!is_empty(tab[old+i])) return 0; } } /* sur une meme colonne */ else if (i_old[1] == i_new[1]) { if (i_old[0] > i_new[0]) { for (i=1; i<i_old[0]-i_new[0]; i=i+1) if (!is_empty(tab[old-i*n])) return 0; } else { for (i=1; i<i_new[0]-i_old[0]; i=i+1) if (!is_empty(tab[old+i*n])) return 0; } } /* sur une meme diagonale */ else if (abs(i_old[1]-i_new[1]) == abs(i_old[0]-i_new[0])) { if (i_old[0]<i_new[0] && i_old[1]<i_new[1]) { for (i=i_old[0]+1 ; i<i_new[0] ; i++) for (j=i_old[1]+1 ; j<i_new[1] ; j++) if (!is_empty(tab[i*n+j])) return 0; } else if (i_old[0]<i_new[0] && i_old[1]>i_new[1]) { for (i=i_old[0]+1 ; i<i_new[0] ; i++) for (j=i_new[1]+1 ; j<i_old[1] ; j++) if (!is_empty(tab[i*n+j])) return 0; } else if (i_old[0]>i_new[0] && i_old[1]<i_new[1]) { for (i=i_new[0]+1 ; i<i_old[0] ; i++) for (j=i_old[1]+1 ; j<i_new[1] ; j++) if (!is_empty(tab[i*n+j])) return 0; } else { for (i=i_new[0]+1 ; i<i_old[0] ; i++) for (j=i_new[1]+1 ; j<i_old[1] ; j++) if (!is_empty(tab[i*n+j])) return 0; } } return 1; } /* requires 0 < nbr < len(tab[old]) ensures retourne 1 si toutes les nbr pieces peuvent se deplacer de tab[old] a tab[new], 0 sinon */ int is_valid_deplacemt(stack *tab, int n, int nbr, int old, int new){ stack tmp; char c; int i_old[2]; int i_new[2]; i_old[0] = old/n; i_old[1] = old%n; i_new[0] = new/n; i_new[1] = new%n; tmp = tab[old]; /* terminaison : la pile tmp est vide */ while (!is_empty(tmp) && nbr > 0){ c = pop(&tmp)[0]; switch (c) { case 'T' : if (i_old[0] != i_new[0] && i_old[1] != i_new[1]) return 0; break; case 'F' : if (abs(i_old[0] - i_new[0]) != abs(i_old[1] - i_new[1])) return 0; break; case 'P' : if (is_white(tab, old)) { if (i_old[0] == n-2 && i_new[0]== n-4) break; else if (i_old[0]-i_new[0] == 1 && i_new[1] == i_old[1] && (is_empty(tab[new]) || is_white(tab, new))) break; else if (abs(i_new[1]-i_old[1]) == 1 && i_old[0]-i_new[0] == 1 && !is_empty(tab[new]) && !is_white(tab, new)) break; else return 0; } else { if (i_old[0] == 1 && i_new[0] == 3) continue; else if (i_new[0]-i_old[0] == 1 && i_new[1] == i_old[1] && (is_empty(tab[new]) || !is_white(tab, new))) break; else if (abs(i_new[1]-i_old[1]) == 1 && i_new[0]-i_old[0] == 1 && !is_empty(tab[new]) && is_white(tab, new)) break; else return 0; } break; case 'D' : if (i_old[0] == i_new[0] || i_old[1] == i_new[1]) break; else if (abs(i_old[0] - i_new[0]) == abs(i_old[1] - i_new[1])) break; else return 0; break; case 'R' : if (i_new[0]>i_old[0]+1 || i_new[0] < i_old[0]-1 || i_new[1] > i_old[1]+1 || i_new[1] < i_old[1]-1) return 0; break; } nbr = nbr - 1; } return 1; }
C
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Copyright (C) Simon Gomizelj, 2012 */ #define _GNU_SOURCE #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <string.h> #include <getopt.h> #include <errno.h> #include <err.h> #include "backlight.h" enum action { ACTION_SET, ACTION_INC, ACTION_DEC, ACTION_INVALID }; static void __attribute__((__noreturn__)) usage(FILE *out) { fprintf(out, "usage: %s [options] [value]\n", program_invocation_short_name); fputs("Options:\n" " -h, --help display this help and exit\n" " -v, --version display version\n" " -i, --inc increment the backlight\n" " -d, --dec decrement the backlight\n", out); exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS); } int main(int argc, char *argv[]) { enum action action = ACTION_SET; struct backlight_t b; char *arg; long value = 0; double current; static const struct option opts[] = { { "help", no_argument, 0, 'h' }, { "version", no_argument, 0, 'v' }, { "inc", no_argument, 0, 'i' }, { "dec", no_argument, 0, 'd' }, { 0, 0, 0, 0 } }; while (true) { int opt = getopt_long(argc, argv, "hvid", opts, NULL); if (opt == -1) break; switch (opt) { case 'h': usage(stdout); break; case 'v': printf("%s %s\n", program_invocation_short_name, LIGHTD_VERSION); return 0; case 'i': action = ACTION_INC; break; case 'd': action = ACTION_DEC; break; default: usage(stderr); } } if (backlight_find_best(&b) < 0) errx(EXIT_FAILURE, "couldn't get backlight information"); current = backlight_get(&b); if (optind == argc) { printf("%.1f%%\n", backlight_get(&b)); return 0; } arg = argv[optind++]; if (action == ACTION_SET && strcmp("max", arg) == 0) value = 100; else { char *end = NULL; value = strtol(arg, &end, 10); if (errno || arg == end) errx(EXIT_FAILURE, "invalid setting: %s", arg); } switch (action) { case ACTION_SET: return backlight_set(&b, value); case ACTION_INC: return backlight_set(&b, current + value); case ACTION_DEC: return backlight_set(&b, current - value); case ACTION_INVALID: break; } return -1; } // vim: et:sts=4:sw=4:cino=(0
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* draw.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: byoung-w <byoung-w@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/04/29 17:03:10 by byoung-w #+# #+# */ /* Updated: 2015/04/29 17:03:12 by byoung-w ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" static void init(t_render *render, t_pixel *start, t_pixel *end) { render->x_start = start->x; render->y_start = start->y; render->x_end = end->x; render->y_end = end->y; render->x_slope = abs(render->x_end - render->x_start); render->y_slope = abs(render->y_end - render->y_start); render->error = (render->x_slope > render->y_slope ? render->x_slope : -render->y_slope) / 2; } static void x_move(t_render *render) { render->error -= render->y_slope; render->x_start += render->x_start < render->x_end ? 1 : -1; } static void y_move(t_render *render) { render->error += render->x_slope; render->y_start += render->y_start < render->y_end ? 1 : -1; } int rgb_to_color(int red, int green, int blue) { return (red * 256 * 256 + green * 256 + blue); } void render_line(t_window *data , t_pixel *start, t_pixel *end) { t_render render; init(&render, start, end); while (1) { mlx_pixel_put(data->mlx_ptr, data->mlx_win, render.x_start, render.y_start, rgb_to_color(255, 255, 255)); if (render.x_start == render.x_end && render.y_start == render.y_end) break ; if (render.error > -render.x_slope) x_move(&render); if (render.error < render.y_slope) y_move(&render); } }
C
/* Include file for grid.c - for more details see there */ /* Written by I.J.Bush March 2011 - if it breaks your computer or aught else, tough. */ /* The grid and associated data. Note we will need two versions of the data on the grid, one to hold the current values, and one to write the results into when we are updating the grid. Hence the grid has 4 dimensions not 3, the last dimension being the two versions of the grid. We swap between the two versions as we go from iteration to iteration, the current member of the derived type indicating which version is the most up to date.*/ struct grid { double ***data[ 2 ]; /* The (two versions of) the data on the grid */ int current; /* Which version of the grid we are currently using */ int whole_size[ 3 ]; /* The size of the overall grid */ int nx, ny, nz; /* The size of the chunk given to this process */ int nux, nuy, nuz; /* The actual usable dimensions of this chunk - ignoring the edge bits used for halos/boundaries */ int px, py, pz; /* Positions in the grid */ int npx, npy, npz; /* Number of processors in the grid */ int up_x, down_x, up_y, down_y, up_z, down_z; /* Neighbours */ int n_iter; /* The number of iterations */ double t_iter; /* The time in the iterations */ }; /* The prototypes */ int grid_init( int ng[ 3 ], int npx, int npy, int npz, struct grid *g ); /* Initialise the grid */ void grid_finalize( struct grid *g ); /* Finalise the grid */ void grid_initial_guess( struct grid *g ); /* The initial guess at the solution */ void grid_set_boundary( struct grid *g ); /* Set the bondary conditions */ double grid_update( struct grid *g ); /* Perform one iteration of the grid update */ double grid_checksum( struct grid g ); /* provide a checksum as a check of the answer */ void grid_print_times( struct grid g ); /* Report timing data */
C
Any year is input through the keyboard. Write a program to determine whether the year is a leap year or not. (Hint: Use the % (modulus) operator) #include<stdio.h> int main() { int year; printf("enter year\n"); scanf("%d",&year); if(year%400==0) { printf("leap year"); } else if(year%4==0) { printf(" leap year"); } else { printf("not a leap year"); } return 0; }
C
#include <stdio.h> void print_matrix_spiral(int arr[3][6], int max_row, int max_col) { int row=0, col=0; int i; while(row <= max_row && col <= max_col) { for (i = col; i <= max_col; i++) printf("%d,",arr[row][i]); printf("\n"); row++; for (i = row; i <= max_row; i++) printf("%d,",arr[i][max_col]); printf("\n"); max_col--; if (row < max_row) { for (i = max_col; i >= col; i--) printf("%d,",arr[max_row][i]); printf("\n"); max_row--; } if (col < max_col) { for (i = max_row; i >= row; i--) printf("%d,",arr[i][col]); printf("\n"); col++; } } } int main() { int arr[3][6] = { {1, 2, 3, 4, 5 , 6}, {7, 8, 9, 10, 11, 12}, {13, 14, 15, 16, 17, 18}}; print_matrix_spiral(arr, 2, 5); }
C
/* PL/0' 用 LL(1)再帰下降型構文解析器 No.03 * 2015年後期 鹿児島高専 * 3年生 言語処理系 授業用 * * 構文解析/意味解析を行っている * * ループを使わず再帰のみでやっている * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../lexer/tokentable.h" #include "symbol_table.h" #include "misc.h" extern FILE *yyin; /* 読み込むソースファイル */ extern int yylex(); /* lex の字句解析 */ extern int line_no; /* 行番号 */ extern int t_num_value; /* T_NUMBER の実際の値 */ extern char *yytext; /* lex よりレクシムが入る */ int getToken(void); /* 非終端記号に対応した関数 */ void parse_Program(void); void parse_Block(void); void parse_Decl(void); void parse_ConstDecl(void); void parse_ConstIdList(void); void parse_ConstIdList_dash(void); void parse_VarDecl(void); void parse_VarIdList(void); void parse_VarIdList_dash(void); void parse_FuncDecl(void); void parse_FuncDeclIdList(void); void parse_FuncDeclIdList_dash(void); void parse_Statement(void); void parse_StatementList(void); void parse_StatementList_dash(void); void parse_Condition(void); void parse_Expression(void); void parse_Expression_dash(void); void parse_Term(void); void parse_Term_dash(void); void parse_Factor(void); int parse_FuncArgList(void); int parse_FuncArgList_dash(void); int nextToken; /* 次のトークンが入る変数 */ int getToken(void) { /* トークンを取得する関数 */ int token = yylex(); if (token == 0) { /* yylex()が0を返す時がEOFのようだ */ token = T_EOF; } return token; } int main(int argc, char *argv[]) { if (argc != 2) { fprintf (stderr, "引数が違います。\n"); exit(EXIT_FAILURE); } yyin = fopen(argv[1], "r"); if (yyin == NULL) { fprintf (stderr, "%s というファイルがありません。\n", argv[1]); exit(EXIT_FAILURE); } /* 構文解析スタート */ nextToken = getToken(); parse_Program(); if (nextToken != T_EOF) pl0_error("構文", "EOF", line_no, "ファイルの最後にきてしまいました。"); fprintf(stderr, "解析終了。全てOK。\n"); } void parse_Program() { fprintf(stderr, "解析開始。\n"); parse_Block(); if (nextToken != T_PERIOD) pl0_error("構文", yytext, line_no, "ピリオドでない。"); nextToken = getToken(); } void parse_Block() { parse_Decl(); parse_Statement(); } void parse_Decl() { if (nextToken == T_CONST) { parse_ConstDecl(); parse_Decl(); } else if (nextToken == T_VAR) { parse_VarDecl(); parse_Decl(); } else if (nextToken == T_FUNC) { parse_FuncDecl(); parse_Decl(); } else { } } void parse_ConstDecl() { /* T_CONST では何もしない。次のトークンを読む */ nextToken = getToken(); parse_ConstIdList(); if (nextToken != T_SEMIC) pl0_error("構文", yytext, line_no, ";がない。"); nextToken = getToken(); } void parse_ConstIdList() { char cur_const_id[MAX_ID_NAME]; if (nextToken != T_ID) pl0_error("構文", yytext, line_no, "定数名でない。"); strcpy(cur_const_id, yytext); nextToken = getToken(); if (nextToken != T_EQ) pl0_error("構文", yytext, line_no, "=がない。"); nextToken = getToken(); if (nextToken != T_NUMBER) pl0_error("構文", yytext, line_no, "数値でない。"); /* 定数名の登録および値の設定 */ register_const_in_tbl(cur_const_id, t_num_value, line_no); nextToken = getToken(); parse_ConstIdList_dash(); } void parse_ConstIdList_dash() { char cur_const_id[MAX_ID_NAME]; if (nextToken == T_COMMA) { nextToken = getToken(); if (nextToken != T_ID) pl0_error("構文", yytext, line_no, "定数名でない。"); strcpy(cur_const_id, yytext); nextToken = getToken(); if (nextToken != T_EQ) pl0_error("構文", yytext, line_no, "=がない。"); nextToken = getToken(); if (nextToken != T_NUMBER) pl0_error("構文", yytext, line_no, "数値でない。"); /* 定数名の登録および値の設定 */ register_const_in_tbl(cur_const_id, t_num_value, line_no); nextToken = getToken(); parse_ConstIdList_dash(); } } void parse_VarDecl() { /* T_VAR では何もしない。次のトークンを読む */ nextToken = getToken(); parse_VarIdList(); if (nextToken != T_SEMIC) pl0_error("構文", yytext, line_no, ";がない。"); nextToken = getToken(); } void parse_VarIdList() { if (nextToken != T_ID) pl0_error("構文", yytext, line_no, "変数名でない。"); /* 変数名の登録 */ register_var_in_tbl(yytext, line_no); nextToken = getToken(); parse_VarIdList_dash(); } void parse_VarIdList_dash() { if (nextToken == T_COMMA) { nextToken = getToken(); if (nextToken != T_ID) pl0_error("構文", yytext, line_no, "変数名でない。"); /* 変数名の記号表への登録 */ register_var_in_tbl(yytext, line_no); nextToken = getToken(); parse_VarIdList_dash(); } } void parse_FuncDecl() { /* T_FUNC では何もしない。次のトークンを読む */ nextToken = getToken(); if (nextToken != T_ID) pl0_error("構文", yytext, line_no, "関数名でない。"); /* 関数名の記号表への登録 */ register_func_in_tbl(yytext, line_no); nextToken = getToken(); if (nextToken != T_LPAR) pl0_error("構文", yytext, line_no, "(がない。"); blk_level_up(); /* ブロックレベルを上げる */ nextToken = getToken(); parse_FuncDeclIdList(); if (nextToken != T_RPAR) pl0_error("構文", yytext, line_no, ")がない。"); nextToken = getToken(); parse_Block(); if (nextToken != T_SEMIC) pl0_error("構文", yytext, line_no, ";がない。"); blk_level_down(); /* ブロックレベルを下げる */ nextToken = getToken(); } void parse_FuncDeclIdList() { if (nextToken == T_ID) { /* 仮引数の記号表への登録 */ register_param_in_tbl(yytext, line_no); nextToken = getToken(); parse_FuncDeclIdList_dash(); } } void parse_FuncDeclIdList_dash() { if (nextToken == T_COMMA) { nextToken = getToken(); if (nextToken != T_ID) pl0_error("構文", yytext, line_no, "仮引数名でない。"); /* 仮引数の記号表への登録 */ register_param_in_tbl(yytext, line_no); nextToken = getToken(); parse_FuncDeclIdList_dash(); } } void parse_Statement() { int ptr; /* 現在の T_IDの記号表での位置 */ if (nextToken == T_ID) { /* 代入文 */ /* T_ID が変数/仮引数かの判断 */ ptr = search_tbl(yytext); /* 現在の T_ID を検索 */ if (ptr == 0) { /* なかった場合 */ pl0_error("意味", yytext, line_no, "定義されていない名前を使用している。"); } else if ((get_symbol_type(ptr) != var_id) && (get_symbol_type(ptr) != param_id)) { /* 変数/仮引数以外の場合 */ info_ref_symbol(ptr, line_no); /* 情報出力 */ pl0_error("意味", yytext, line_no, "変数/仮引数以外に代入している。"); } info_ref_symbol(ptr, line_no); /* 情報出力 */ nextToken = getToken(); if (nextToken != T_COLEQ) pl0_error("構文", yytext, line_no, ":=がない。"); nextToken = getToken(); parse_Expression(); } else if (nextToken == T_BEGIN) { /* begn ~ end */ nextToken = getToken(); parse_StatementList(); if (nextToken != T_END) pl0_error("構文", yytext, line_no, "endがない。"); nextToken = getToken(); } else if (nextToken == T_IF) { /* if then */ nextToken = getToken(); parse_Condition(); if (nextToken != T_THEN) pl0_error("構文", yytext, line_no, "thenがない。"); nextToken = getToken(); parse_Statement(); } else if (nextToken == T_WHILE) { /* while do */ nextToken = getToken(); parse_Condition(); if (nextToken != T_DO) pl0_error("構文", yytext, line_no, "doがない。"); nextToken = getToken(); parse_Statement(); } else if (nextToken == T_RETURN) { /* return */ nextToken = getToken(); parse_Expression(); } else if (nextToken == T_WRITE) { /* write */ nextToken = getToken(); parse_Expression(); } else if (nextToken == T_WRITELN) { /* writeln */ nextToken = getToken(); } else { } } void parse_StatementList() { parse_Statement(); parse_StatementList_dash(); } void parse_StatementList_dash() { if (nextToken == T_SEMIC) { nextToken = getToken(); parse_Statement(); parse_StatementList_dash(); } } void parse_Condition() { int operator ; /* T_EQ や T_GT を一時格納 */ if (nextToken == T_ODD) { nextToken = getToken(); parse_Expression(); /* ここで T_ODDの処理 */ } else { parse_Expression(); if (nextToken == T_EQ || nextToken == T_NOTEQ || nextToken == T_LT || nextToken == T_GT || nextToken == T_LE || nextToken == T_GE) { operator = nextToken; } else { pl0_error("構文", yytext, line_no, "比較演算子がない。"); } nextToken = getToken(); parse_Expression(); /* ここで operator 処理 */ } } void parse_Expression() { if (nextToken == T_PLUS) { nextToken = getToken(); parse_Term(); /* ここで 0 Term + をスタックにつむ */ parse_Expression_dash(); } else if (nextToken == T_MINUS) { nextToken = getToken(); parse_Term(); /* ここで 0 Term - をスタックにつむ */ parse_Expression_dash(); } else { parse_Term(); parse_Expression_dash(); } } void parse_Expression_dash() { if (nextToken == T_PLUS) { nextToken = getToken(); parse_Term(); /* ここで + の処理 */ parse_Expression_dash(); } else if (nextToken == T_MINUS) { nextToken = getToken(); parse_Term(); /* ここで - の処理 */ parse_Expression_dash(); } else { } } void parse_Term() { parse_Factor(); parse_Term_dash(); } void parse_Term_dash() { if (nextToken == T_MULTI) { nextToken = getToken(); parse_Factor(); /* ここで * の処理 */ parse_Term_dash(); } else if (nextToken == T_DIVIDE) { nextToken = getToken(); parse_Factor(); /* ここで / の処理 */ parse_Term_dash(); } else { } } void parse_Factor() { int ptr; /* 現在の T_IDの記号表での位置 */ int args; /* 関数の引数 */ if (nextToken == T_ID) { /* T_ID が関数/変数/定数かの判断 */ ptr = search_tbl(yytext); /* 現在の T_ID を検索 */ if (ptr == 0) { /* なかった場合 */ pl0_error("意味", yytext, line_no, "定義されていない。"); } else if (get_symbol_type(ptr) == func_id) { /* 関数の場合 */ nextToken = getToken(); if (nextToken != T_LPAR) pl0_error("構文", yytext, line_no, "(がない。"); else { nextToken = getToken(); args = parse_FuncArgList(); if (nextToken != T_RPAR) pl0_error("構文", yytext, line_no, ")がない。"); /* 関数のチェック */ info_ref_symbol(ptr, line_no); /* 情報出力 */ if (get_func_args(ptr) != args) pl0_error("意味", get_symbol_name(ptr), line_no,"引数の個数が違う"); } } else { /* 関数以外(定数/変数/仮引数)の場合 */ info_ref_symbol(ptr, line_no); /* 情報出力 */ } nextToken = getToken(); } else if (nextToken == T_NUMBER) { /* ここで数字の処理 */ nextToken = getToken(); } else if (nextToken == T_LPAR) { nextToken = getToken(); parse_Expression(); if (nextToken != T_RPAR) pl0_error("構文", yytext, line_no, ")がない。"); nextToken = getToken(); } else { pl0_error("構文", yytext, line_no, "数値/変数/定数/関数でない。"); } } int parse_FuncArgList() { /* 返り値は引数の個数 */ int n_args = 0; if (nextToken == T_PLUS || nextToken == T_MINUS || nextToken == T_ID || nextToken == T_NUMBER || nextToken == T_LPAR) { /* First(<Expression>)に含まれるもの */ parse_Expression(); n_args = 1 + parse_FuncArgList_dash(); } else { } return n_args; } int parse_FuncArgList_dash() { /* 返り値は引数の個数 */ int n_args = 0; if (nextToken == T_COMMA) { nextToken = getToken(); parse_Expression(); n_args = 1 + parse_FuncArgList_dash(); } else { } return n_args; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "data_inout.h" #define N 1 /* ソート関数 */ int int_sort( const void * a , const void * b ) { /* 引数はvoid*型と規定されているのでint型にcastする */ if( *( int * )a < *( int * )b ) { return -1; } else if( *( int * )a == *( int * )b ) { return 0; } return 1; } main(){ unsigned char image1[256][256], image2[256][256]; int i, j, i2, j2, k, l, number; read_image(image1, 65536, "lenad"); for(i=0; i<256; i++) for(j=0; j<256; j++){ number = (2 * N + 1) * (2 * N + 1); int valArray[(2 * N + 1) * (2 * N + 1)]; int m = 0; for(k=-N; k<=N; k++) { for(l=-N; l<=N; l++){ i2 = i + k; j2 = j + l; if(i2<0 || i2>255 || j2<0 || j2>255){ number = number-1; } else { //配列に画素値を確保 valArray[m] = image1[i2][j2]; m++; } } } // 大きい順にソートして中央値を取る qsort(( void * )valArray , number , sizeof( valArray[0] ), int_sort ); image2[i][j] = valArray[number/2 +1]; } write_image(image2, 65536, "out"); }
C
#include <stdio.h> unsigned int mystery(unsigned int a , unsigned int b); int main() { unsigned int x; unsigned int y; scanf("%u%u",&x,&y); printf("%d",mystery(x,y)); } unsigned int mystery(unsigned int a , unsigned int b){ if(b==0){ return 0; } else{ return a + mystery(a,b-1); } }
C
#include<stdio.h> #include<math.h> int main() { float N; scanf("%f",&N); N=fabs(N); printf("%.2f",N); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<signal.h> void dis(int sig) { static int i=0; sleep(2); printf("Sig is %d\n",i++); } int main() { sigset_t s1,s2; struct sigaction act1; char buf[100]; int ret; sigemptyset(&s1); sigaddset(&s1,SIGINT); act1.sa_handler=dis; sigfillset(&act1.sa_mask); act1.sa_flags=0; sigaction(SIGINT,&act1,NULL); while(1) { printf("in sleep\n"); sleep(1); } return 0; }
C
#include "libft.h" void *ft_memmove(void *dst, const void *src, size_t len) { unsigned const char *s; unsigned char *d; size_t i; s = src; d = dst; i = 0; if (len == 0 || d == s) return (d); while (d <= s && len > i) { d[i] = s[i]; i++; } while (d > s && len > 0) { d[len - 1] = s[len - 1]; len--; } return (dst); }
C
#include<stdio.h> int main() { int i, n;/*={10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200};*/ printf("Enter the number of array: "); scanf("%d",&n); int a[n]; printf("Please enter the value in serial order in the array:\n"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } printf("a[%d]=",n); for(i=0;i<n;i++) { printf("%d ",a[i]); } int start=0,end=n+1,mid,key,k; printf("\nEnter the Key value: "); scanf("%d",&k); key=k; do { mid=(int)((start+end)/2); printf("Start:%d\tEnd:%d\tMid:%d\tKey:%d\n",start,end,a[mid],key); if(a[mid]==key) { printf("Position of Key value is: %d",mid+1); break; } else if(key<a[mid]) { end=mid-1; } else start=mid+1; }while(start<=end); if(start>end) { printf("failed\n"); printf("Start: %d\t End: %d\t Mid: %d\t Key: %d\n",a[start],a[end],a[mid],key); } getch(); }
C
#ifndef SNAKE_H #define SNAKE_H #define MAXCASES 12 #define MAXSNAKE 5000 #include <stdio.h> #include <stdlib.h> #include <time.h> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_mixer.h> #include <SDL2/SDL_ttf.h> /* Type booléen */ typedef enum _bool {FALSE, TRUE} bool; /* Type codant l'état d une case du serpent */ typedef enum _stateSnake { VOID, TETE, CORPS, QUEUE }StateSnake; /* Structure indiquant la position (x,y) d' une case */ typedef struct _position { int x; int y; }Position; /* Structure d'une case du serpent */ typedef struct _case { StateSnake etat; Position position; }CaseSnake; /* Structure du serpent */ typedef struct _snake { int tete, queue; CaseSnake posSnake[MAXSNAKE]; }Snake; /* Codes d' erreurs */ typedef enum _err { ERR_SIZE_SNAKE = -1, ERR_POSITION = -2, NO_ERR = 1 }Erreur; Position initPosition(); CaseSnake initCaseSnake(); Snake initSnake(); Position newPosition(int x, int y); CaseSnake newCaseSnake(StateSnake etat, Position pos); Snake newSnake(int tete, int queue, CaseSnake posSnake[]); bool testPosSnake(Position pos); #endif
C
#include "reweight_layer.h" #include "cuda.h" #include "blas.h" #include <stdio.h> reweight_layer make_reweight_layer(int batch, int n, int *input_layers, int *input_sizes, ACTIVATION activation) { fprintf(stderr,"reweight "); reweight_layer l = {0}; l.type = REWEIGHT; l.batch = batch; l.n = n; l.input_layers = input_layers; l.input_sizes = input_sizes; int i; int outputs = 0; for(i = 0; i < n; ++i){ fprintf(stderr," %d", input_layers[i]); } outputs += input_sizes[1]; fprintf(stderr, "\n"); l.outputs = outputs; l.inputs = outputs; l.delta = calloc(outputs*batch, sizeof(float)); l.output = calloc(outputs*batch, sizeof(float));; l.forward = forward_reweight_layer; l.backward = backward_reweight_layer; #ifdef GPU l.forward_gpu = forward_reweight_layer_gpu; l.backward_gpu = backward_reweight_layer_gpu; l.delta_gpu = cuda_make_array(l.delta, outputs*batch); l.output_gpu = cuda_make_array(l.output, outputs*batch); #endif l.activation = activation; return l; } void resize_reweight_layer(reweight_layer *l, network *net) { layer second = net->layers[l->input_layers[1]]; l->out_w = second.out_w; l->out_h = second.out_h; l->out_c = second.out_c; l->outputs = second.outputs; l->input_sizes[1] = second.outputs; layer first = net->layers[l->input_layers[0]]; if(first.out_c == second.out_c){ l->out_c = second.out_c; }else{ printf("%d %d\n", first.out_c, second.out_c); l->out_h = l->out_w = l->out_c = 0; } l->inputs = l->outputs; l->delta = realloc(l->delta, l->outputs*l->batch*sizeof(float)); l->output = realloc(l->output, l->outputs*l->batch*sizeof(float)); #ifdef GPU cuda_free(l->output_gpu); cuda_free(l->delta_gpu); l->output_gpu = cuda_make_array(l->output, l->outputs*l->batch); l->delta_gpu = cuda_make_array(l->delta, l->outputs*l->batch); #endif } void forward_reweight_layer(const reweight_layer l, network net) { int i, j; int scale_offset = 0; int x_offset = 0; float *scale = net.layers[l.input_layers[0]].output; float *x = net.layers[l.input_layers[1]].output; for(i = 0; i < l.batch; ++i){ for (j = 0; j < l.out_c; ++j) { scale_offset = i * l.out_c + j; x_offset = i * l.outputs + j * l.out_h * l.out_w; copy_cpu(l.out_h*l.out_w, x + x_offset, 1, l.output + x_offset, 1); scal_cpu(l.out_h*l.out_w, scale[scale_offset], l.output + x_offset, 1); } } activate_array(l.output, l.outputs*l.batch, l.activation); } void backward_reweight_layer(const reweight_layer l, network net) { gradient_array(l.output, l.outputs*l.batch, l.activation, l.delta); int i, j, k; int scale_offset = 0; int x_offset = 0; float *scale = net.layers[l.input_layers[0]].output; float *scale_delta = net.layers[l.input_layers[0]].delta; float *x = net.layers[l.input_layers[1]].output; float *x_delta = net.layers[l.input_layers[1]].delta; for(i = 0; i < l.batch; ++i){ for (j = 0; j < l.out_c; ++j) { scale_offset = i * l.out_c + j; x_offset = i * l.outputs + j * l.out_h * l.out_w; axpy_cpu(l.h*l.w, scale[scale_offset], l.delta + x_offset, 1, x_delta+x_offset, 1); scale_delta[scale_offset] = 0; for (k = 0; k < l.out_h * l.out_w; ++k) { scale_delta[scale_offset] += l.delta[x_offset+k] * x[x_offset+k]; } } } } #ifdef GPU void forward_reweight_layer_gpu(const reweight_layer l, network net) { int i, j; int scale_offset = 0; int x_offset = 0; float *scale = net.layers[l.input_layers[0]].output_gpu; float *x = net.layers[l.input_layers[1]].output_gpu; for(i = 0; i < l.batch; ++i){ for (j = 0; j < l.out_c; ++j) { scale_offset = i * l.out_c + j; x_offset = i * l.outputs + j * l.out_h * l.out_w; reweight_gpu(l.out_h*l.out_w, scale, scale_offset, x + x_offset, 1, l.output_gpu + x_offset, 1); } } activate_array_gpu(l.output_gpu, l.outputs*l.batch, l.activation, 0); } void backward_reweight_layer_gpu(const reweight_layer l, network net) { gradient_array_gpu(l.output_gpu, l.outputs*l.batch, l.activation, l.delta_gpu, 0); int i, j, k; int scale_offset = 0; int x_offset = 0; int scale_num = net.layers[l.input_layers[0]].batch * net.layers[l.input_layers[0]].outputs; int x_num = net.layers[l.input_layers[1]].batch * net.layers[l.input_layers[1]].outputs; cuda_pull_array(net.layers[l.input_layers[0]].output_gpu, net.layers[l.input_layers[0]].output, scale_num); cuda_pull_array(net.layers[l.input_layers[1]].output_gpu, net.layers[l.input_layers[1]].output, x_num); cuda_pull_array(l.delta_gpu, l.delta, l.batch*l.outputs); float *scale = net.layers[l.input_layers[0]].output; float *scale_delta = net.layers[l.input_layers[0]].delta; float *x = net.layers[l.input_layers[1]].output; float *x_delta = net.layers[l.input_layers[1]].delta_gpu; for(i = 0; i < l.batch; ++i){ for (j = 0; j < l.out_c; ++j) { scale_offset = i * l.out_c + j; x_offset = i * l.outputs + j * l.out_h * l.out_w; // x_delta axpy_gpu(l.out_h*l.out_w, scale[scale_offset], l.delta_gpu + x_offset, 1, x_delta+x_offset, 1); // scale_delta scale_delta[scale_offset] = 0; for (k = 0; k < l.out_h*l.out_w; ++k) { scale_delta[scale_offset] += l.delta[x_offset+k] * x[x_offset+k]; } } } cuda_push_array(net.layers[l.input_layers[0]].delta_gpu, scale_delta, scale_num); } #endif
C
#include <stdio.h> #include "cipherUtils.h" //These global variables are inherently private to the current file FILE *rFile = NULL, *wFile = NULL; // rFile = file being read from, wFile = file being written to char *string = NULL; // current string that is divided into blocks int stringSize = 0; // current string full length int inputMode = 1; // 1 if string inputMode, 0 if file inputMode /** * @brief Treats input and output as file paths that can be used to write them. Opens the files in their respective access modes(input -> read-only, output -> write) and assigns them to global pointers that can be used by other functions. * NOTE: output file will be created if it doesn't already exist and will be overwritten if it exists * Non-existent or invalid file paths will return 0 * * @param input Read file path * @param output Write file path * @return int 1 if successfully opened, 0 if unsuccessful */ int addFiles(char *input, char *output) { rFile = fopen(input, "r"); if (rFile == NULL) { fprintf(stderr, "Could not open %s or File not found\n", input); return 0; } wFile = fopen(output, "w+"); if (wFile == NULL) { fprintf(stderr, "Could not open or create file: %s\n", output); return 0; } string = NULL; inputMode = 0; // file inputMode return 1; } /** * @brief adds the new string to divide into blocks. Its full size is also stored. * * @param fullString pointer to large string being divided * @param size size of fullString */ void addString(char* fullString, int size) { closeFiles(); string = fullString; stringSize = size; inputMode = 1; // string inputMode } /** * @brief Closes files linked to rFile and wFile and sets them to NULL * NOTE: this is called automatically after the last block from rFile is encrypted and written to wFile automatically. But when stopping early, this should be called by user program. */ void closeFiles() { if (rFile != NULL) fclose(rFile); if (wFile != NULL) fclose(wFile); rFile = wFile = NULL; string = NULL; } /** * @brief Reads the next block of bytes into bc, either from the file being read or the string based on the inputMode. Returns the number of bytes that were read into bc. This number lower than blockSize if there are not enough bytes left in the string. * * @param bc block will be loaded into this array * @param blockSize number of bytes to be loaded into this block * @return int number of bytes actually read into bc */ int getNextBlock(char *bc, int blockSize) { int size = 0; if (inputMode) { // string inputMode if (stringSize == 0) return 0; size = (stringSize > blockSize) ? blockSize : stringSize; // stream cipher requirement for (int i = 0; i < size; bc[i++] = *(string++)); // string ptr will point to the beginning of the new block each call of this function stringSize -= size; } else { //file inputMode if (rFile == NULL) return 0; size = fread(bc, sizeof(char), blockSize, rFile); } return size; } /** * @brief Copies bytes from bc to the respective output based on the inputMode(to output if inputMode=1 and to file if inputMode=0). If output == NULL and inputMode=0, write to file else write to output array. Size is the number of bytes to be written from bc to the correct output. * NOTE: if output is specified, user's responsibility to ensure that size doesn't exceed the length of output * * @param bc block to copy from * @param output copy destination array * @param size size of bc to be copied * @return int 1 if write success else 0 */ int writeBlock(char *bc, char* output, int size) { if (inputMode && output != NULL) { //string inputMode for (int i = 0; i < size; output[i++] = bc[i]); } else if (!inputMode && output == NULL) { //file inputMode fwrite(bc, sizeof(char), size, wFile); if (feof(rFile)) closeFiles(); } else return 0; // invalid parameters return 1; // write success } /** * @brief Utility for xor operation across two arrays(one and two). Result is loaded to output. * NOTE: all arrays to be at least of length size * @param one * @param two * @param output * @param size size of arrays in bytes */ void ArrayXor(char *one, char *two, char *output, int size) { for (int i = 0; i < size; i++) *(output++) = *(one++) ^ *(two++); // note that pointers one, two and output will remain unchanged when function call returns but data will change } /** * @brief shifts the shiftRegister sr to the left by sl bytes. fills in the new space at the end with fill if fill doesn't point to NULL * * @param sr shiftRegister * @param size size of the shiftRegister sr * @param sl shiftLeft = number of bytes to shift left * @param fill fill in characters into the new space - use NULL if no fill array */ void leftShift(char *sr, int size, int sl, char *fill) { int i = 0; for (int j = sl; j < size; sr[i++] = sr[j++]); if (fill != NULL) for (; i < size; sr[i++] = *(fill++)); else for (; i < size; sr[i++] = 0); } /** * @brief Utility function to pad zeros to the right. Copies src to dest and pads the remaining of dest with zeros. * * @param src unpadded array * @param dest padded array * @param srcSize size of src array * @param destSize size of dest array. */ void padRight (char* src, char* dest, int srcSize, int destSize) { int i = 0; for (; i < srcSize; dest[i++] = src[i]); for (; i < destSize; dest[i++] = 0); // pad with zeros to the right }
C
#include "Portfolio.h" Portfolio *newPortfolio() { Portfolio *temp; temp=malloc(sizeof(Portfolio)); return temp; } void setBankAccount(Portfolio *ptfolio, double cash) { ptfolio->bankAccount=cash; } void initializePortfolio(Portfolio *port, CAsset *assets) { int i; Asset *currentAsset; port->bankAccount=traderStartingCash; for(i=1;i<sizeCAsset(assets);i++) {currentAsset=elementAtCAsset(assets,i); setAsset(currentAsset,i,initialPrice,assetStartingQuantity); } } Portfolio *expectedPortfolio(Portfolio *port, Belief *belief) { Portfolio *answer; answer =newPortfolio(); return answer; } void executeOrder(Portfolio *portfolio,Order *anOrder,CAsset *assets,COrder *pending) { double cash; int assetId; int quantity; int size; int index; Order *order; Asset *currentAsset; quantity=anOrder->quantity; assetId=anOrder->assetId; cash=(anOrder->price)*(anOrder->quantity); portfolio->bankAccount=portfolio->bankAccount-cash; size=sizeCAsset(assets); currentAsset=elementAtCAsset(assets,assetId); currentAsset->quantity=currentAsset->quantity+quantity; size=sizeCOrder(pending); index=findCOrder(pending,assetId); if(index>-1) { order=elementAtCOrder(pending,index); order->quantity=order->quantity-quantity; } else {printf("assetId =%d size= %d",assetId,size);getchar();} } double wealth(Portfolio *port, CAsset *assetsowned) { double wea,price; int i; int size,quantity; Asset *asset; size=sizeCAsset(assetsowned); wea=0; for(i=0; i<size ;i++) { asset=elementAtCAsset(assetsowned,i); quantity=(asset->quantity); price=asset->lastPrice; wea=wea+(quantity*price); } wea=wea+port->bankAccount; return wea; } int totalassets(CAsset *assetsowned) { int quantity,total,i,size; Asset *asset; size=sizeCAsset(assetsowned); total=0; for(i=0; i<size ;i++) { asset=elementAtCAsset(assetsowned,i); quantity=(asset->quantity); total=total+quantity; } return total; }
C
#include <stdio.h> enum directions { UPRIGHT = 1, UPLEFT, DOWNLEFT, DOWNRIGHT }; void tile(int, int, int, int, int); int main(void) { int l, m; scanf("%d%d", &l, &m); tile(l, m, UPRIGHT, l / 2, l / 2); return 0; } void tile(int l, int m, int direction, int x, int y) { if (l == m) { return; } if (l == 2) { switch (direction) { case UPRIGHT: printf("%d %d %d\n", UPRIGHT, x, y); break; case UPLEFT: printf("%d %d %d\n", UPLEFT, x, y); break; case DOWNLEFT: printf("%d %d %d\n", DOWNLEFT, x, y); break; case DOWNRIGHT: printf("%d %d %d\n", DOWNRIGHT, x, y); break; } return; } if (direction == UPRIGHT) { printf("%d %d %d\n", UPRIGHT, x, y); tile(l / 2, 1, UPRIGHT, x - l / 4, y - l / 4); tile(l / 2, 1, DOWNRIGHT, x - l / 4, y + l / 4); tile(l / 2, 1, UPLEFT, x + l / 4, y - l / 4); tile(l / 2, m, UPRIGHT, x + l / 4, y + l / 4); } if (direction == UPLEFT) { printf("%d %d %d\n", UPLEFT, x, y); tile(l / 2, 1, UPLEFT, x + l / 4, y - l / 4); tile(l / 2, 1, DOWNLEFT, x + l / 4, y + l / 4); tile(l / 2, 1, UPRIGHT, x - l / 4, y - l / 4); tile(l / 2, m, UPLEFT, x - l / 4, y + l / 4); } if (direction == DOWNLEFT) { printf("%d %d %d\n", DOWNLEFT, x, y); tile(l / 2, 1, DOWNLEFT, x + l / 4, y + l / 4); tile(l / 2, 1, DOWNRIGHT, x - l / 4, y + l / 4); tile(l / 2, 1, UPLEFT, x + l / 4, y - l / 4); tile(l / 2, m, DOWNLEFT, x - l / 4, y - l / 4); } if (direction == DOWNRIGHT) { printf("%d %d %d\n", DOWNRIGHT, x, y); tile(l / 2, 1, DOWNRIGHT, x - l / 4, y + l / 4); tile(l / 2, 1, DOWNLEFT, x + l / 4, y + l / 4); tile(l / 2, 1, UPRIGHT, x - l / 4, y - l / 4); tile(l / 2, m, DOWNRIGHT, x + l / 4, y - l / 4); } }
C
#include <stdio.h> #include <stdlib.h> struct Node{ int data; struct Node *next; }; struct Node *headNode=NULL; void insert(int num){ struct Node *temp=(struct Node*)malloc(sizeof(struct Node)); temp->data=num; temp->next=NULL; if(headNode==NULL){ headNode=temp; return ; } struct Node *temp1=headNode; while(temp1->next!=NULL) temp1=temp1->next; temp1->next=temp; } void print(){ struct Node *temp; temp=headNode; while(temp!=NULL){ printf("%d\t",temp->data); temp=temp->next; } } void swapNodePairWise(){ struct Node *p,*q,*temp; p=headNode; headNode=headNode->next; while(headNode!=NULL){ q=p->next; temp=q->next; q->next=p; if(temp==NULL||temp->next==NULL){ p->next=temp; break; } p->next=temp->next; p=temp; } } int main() { insert(1); insert(2); insert(3); insert(4); insert(5); swapNodePairWise(); print(); }
C
unsigned int fib(unsigned int param0) { unsigned int result = param0; if((int)param0 > 1) { unsigned int v0 = 1; unsigned int v1 = 1; if((int)param0 > 2) { unsigned int v2 = param0 - 2; do { unsigned int v3 = v0; v0 += v1; --v2; v1 = v3; } while(v2); } result = v0; } return result; } int main() { unsigned int v0; →printf("Input number: "); →scanf((char*)&gvar_804848B); unsigned int v1 = fib(v0); →printf("fibonacci(%d) = %d\n", v0, v1); return 0; } int sub_8048272() { return gvar_8049598(); }
C
#include <stdio.h> #include <math.h> #include <stdint.h> uint32_t primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311 }; int main(int argc, char *argv[]){ long double cuberoot; long double fraction; long double multiply; for (int i =0; i < 64; i++){ cuberoot = cbrtl((long double)primes[i]); fraction = cuberoot - floorl(cuberoot); multiply = fraction * 0x100000000; // multiply = floor(multiply); printf("%3d -> %3.6LF -> %3.6LF -> %08x \n", primes[i], cuberoot, fraction,(uint32_t) multiply); } // end loop return 0; } // end main
C
#include <stdio.h> #include <sorted_list.h> /*private functions*/ static int IsIntBefore(const void *element_data, const void *user_data, void *param); static int CompareInt(const void *list_data, const void *user_data); void TestFlow1(); void TestFlow2(); void TestFlow3(); void TestFlow4(); int main() { TestFlow1(); TestFlow2(); TestFlow3(); TestFlow4(); return 0; } static int IsIntBefore(const void *list_data, const void *user_data, void *param) { (void)param; return (*(int *)list_data < *(int *)user_data); } static int CompareInt(const void *list_data, const void *user_data) { return (!(*(int *)list_data == *(int *)user_data)); } void TestFlow1() { sorted_list_t *sorted_test = NULL; sorted_list_iter_t iter; int num; sorted_test = SortedListCreate(IsIntBefore, NULL); iter = SortedListBegin(sorted_test); num = 33; printf("\nCreate sorted linked list, insert, check if is empty, get data, size, remove, find if and destroy:\n"); if (!SortedListIsEmpty(sorted_test)) { printf("\033[1;31m- Problem in functionality of IsEmpty\033[0m\n"); } else { printf("\033[1;32m- IsEmpty works as expected\033[0m\n"); } iter = SortedListInsert(sorted_test, &num); if (*(int *)(SortedListGetData(iter)) != num) { printf("\033[1;31m- Problem in functionality of GetData\033[0m\n"); } else { printf("\033[1;32m- GetData works\033[0m\n"); } if (SortedListIsEmpty(sorted_test)) { printf("\033[1;31m- Problem in functionality of Insert - list already contains one element\033[0m\n"); } else { printf("\033[1;32m- Insert works\033[0m\n"); } if (1 != SortedListSize(sorted_test)) { printf("\033[1;31m- Problem in functionality of size - list already contains one element\033[0m\n"); } else { printf("\033[1;32m- Size works\033[0m\n"); } if (*(int*)SortedListGetData(SortedListFindIf(sorted_test, SortedListBegin(sorted_test), SortedListEnd(sorted_test), CompareInt, &num)) != num) { printf("\033[1;31m- Problem in functionality of sizeFindIf\033[0m\n"); } SortedListRemove(iter); if (0 != SortedListSize(sorted_test)) { printf("\033[1;31m- Problem in functionality of size - list already contains one element\033[0m\n"); } else { printf("\033[1;32m- Size works\033[0m\n"); } SortedListDestroy(sorted_test); sorted_test = NULL; } void TestFlow2() { sorted_list_t *sorted_test2 = SortedListCreate(IsIntBefore, NULL); int num1 = 100; int num2 = 20; int num3 = 30; int num4 = 20; int num5 = 30; SortedListInsert(sorted_test2 ,&num1); SortedListInsert(sorted_test2 ,&num2); SortedListInsert(sorted_test2 ,&num3); SortedListInsert(sorted_test2 ,&num4); SortedListInsert(sorted_test2 ,&num5); printf("\nCreate sorted linked list, check begin, pop back, pop front and destroy:\n"); SortedListPopBack(sorted_test2 ); if (SortedListGetData(SortedListBegin(sorted_test2 )) != &num1) { printf("\033[1;31m- Problem in functionality of pop back\033[0m\n"); } else { printf("\033[1;32m- Pop back works\033[0m\n"); } SortedListPopFront(sorted_test2); if (SortedListGetData(SortedListBegin(sorted_test2 )) != &num3) { printf("\033[1;31m- Problem in functionality of Pop front\033[0m\n"); } else { printf("\033[1;32m- Pop front works\033[0m\n"); } SortedListDestroy(sorted_test2); sorted_test2 = NULL; } void TestFlow3() { size_t dest_tests[] = {1, 10, 11, 12, 13}; size_t src_tests[] = {2, 3, 4, 5, 19}; size_t num_of_tests = sizeof(dest_tests)/sizeof(dest_tests[0]); size_t i = 0; sorted_list_t *dest = NULL; sorted_list_t *src = NULL; dest = SortedListCreate(IsIntBefore, NULL); src = SortedListCreate(IsIntBefore, NULL); printf("\nCreate two lists and check merge:\n"); for (i = 0; i < num_of_tests; ++i) { SortedListInsert(src, &src_tests[i]); } for (i = 0; i < num_of_tests; ++i) { SortedListInsert(dest, &dest_tests[i]); } SortedListMerge(dest, src); if (10 != SortedListSize(dest)) { printf("\033[1;31m- Problem in functionality of merge\033[0m\n"); } else { printf("\033[1;32m- Merge works\033[0m\n"); } SortedListDestroy(dest); dest = NULL; SortedListDestroy(src); src = NULL; } void TestFlow4() { sorted_list_t *sorted_list3 = NULL; size_t list[] = {1,2,4,6}; size_t find_num1 = 6; size_t find_num2 = 11; size_t num_of_tests = sizeof(list)/sizeof(list[0]); size_t i = 0; sorted_list3 = SortedListCreate(IsIntBefore,NULL); printf("\nCreate list and check find:\n"); for (i = 0; i < num_of_tests; ++i) { SortedListInsert(sorted_list3, &list[i]); } if (!SortedListIsSameIter(SortedListFind(sorted_list3, SortedListBegin(sorted_list3), SortedListEnd(sorted_list3), &find_num1), SortedListBegin(sorted_list3))) { printf("\033[1;32m- find works - the data is founded\033[0m\n"); } if (!SortedListIsSameIter(SortedListFind(sorted_list3, SortedListBegin(sorted_list3), SortedListEnd(sorted_list3), &find_num2), SortedListBegin(sorted_list3))) { printf("\033[1;32m- find works - data isn't exist in list\033[0m\n"); } SortedListDestroy(sorted_list3); sorted_list3 = NULL; }
C
#include <stdio.h> #include <stdlib.h> int main(void){ char* buf; buf = malloc(1LL << 60); fgets(buf,1024,stdin); printf("buf = %s\n",buf); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> main() { int i, j; double a, max, min; min = 32000.0; max = -32000.0; for (i = 1; i <= 50; i++) { a = cos (2 * 3.14 * i / 50 + 3.14 / 2) / sin (2 * 3.14 * i / 50 + 3.14 / 2); if (a < min) min = a; else if (a > max) max = a; for (j = 1; j <= 50; j++) { if (ceil(((cos (2 * 3.14 * i / 50 + 3.14 / 2) / sin (2 * 3.14 * i / 50 + 3.14 / 2)) - min) * 50 / (max - min)) == 50 - j) printf("*"); else printf(" "); } } //printf("%d 襥 祭 㭪樨 楫 㬥⮢ 1 50\n", min); //printf("%d 襥 祭 㭪樨 楫 㬥⮢ 1 50\n", max); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vsarapin <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/12/05 15:41:06 by vsarapin #+# #+# */ /* Updated: 2017/12/05 16:55:32 by vsarapin ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" void free_square(char **square) { int i; i = 0; while (square[i]) { free(square[i]); i++; } free(square); square = NULL; } void free_lst(t_tetra *div_prog) { t_tetra *tmp; while (div_prog != NULL) { tmp = div_prog->next; free(div_prog); div_prog = tmp; } } int main(int argc, char **argv) { char *array; int fd; int i; t_tetra *div_prog; i = 0; if (argc != 2) { ft_putstr("usage fillit <file>\n"); return (1); } fd = open(argv[1], O_RDONLY); array = read_write(fd); if (!array || !lets_check_all(array) || counter_tetramino(array) > 26) { ft_putstr("error\n"); return (0); } close(fd); div_prog = mem_for_tetraminos(array); result(array, div_prog); free_lst(div_prog); free(array); return (0); }
C
#include <stdlib.h> #include <stdio.h> #include "disassembler.h" int main(int argc, char const *argv[]) { FILE *f = fopen(argv[1], "rb"); if (f == NULL) { printf("Error - couldn't open %s\n", argv[1]); exit(1); } fseek(f, 0L, SEEK_END); int fsize = ftell(f); fseek(f, 0L, SEEK_SET); unsigned char *buffer = malloc(fsize); int r = fread(buffer, fsize, 1, f); fclose(f); int pc = 0; while (pc < fsize) { pc += disassemble8080Op(buffer, pc); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <stdio_ext.h> #include "funciones.h" int utn_getNumeroMio(int* pResultado,char *mensaje,char *mensajeError,int minimo,int maximo,int reintentos) { int ret; int num; while (reintentos>0) { printf("%s",mensaje); if (getInt(&num)==0) { if (num<=maximo && num>=minimo) { break; } } __fpurge(stdin); reintentos--; printf("%s\n",mensajeError); } if(reintentos==0) { ret=-1; }else { ret=0; *pResultado = num; } return ret; } int getInt(int *pResultado) { char buffer[64]; scanf("%s",buffer); *pResultado = atoi(buffer); return 0; } int utn_getFloatMio(float *pResultado,char *mensaje,char *mensajeError,int minimo,int maximo,int reintentos) { int ret; float num; while (reintentos>0) { printf("%s",mensaje); if (getFloat(&num)==0) { if (num<=maximo && num>=minimo) { break; } } __fpurge(stdin); reintentos--; printf("%s\n",mensajeError); } if(reintentos==0) { ret=-1; }else { ret=0; *pResultado = num; } return ret; } int getFloat(float *pResultado) { char buffer[64]; scanf("%s",buffer); *pResultado = atof(buffer); return 0; } int utn_getChar(char* pResultado,char *mensaje,char *mensajeError,char *minimo,char *maximo,int reintentos) { int ret = -1; char buffer[64]; int i; do{ printf("%s",mensaje); scanf("%s", buffer); i=0; while (buffer[i]!='\0' && i<2) { if (buffer[0]>=minimo[0] && buffer[0]<=maximo[0]) { ret=0; } i++; } if (ret==0 && i==1) { pResultado = buffer; break; } reintentos--; printf("%s\n",mensajeError); ret = -1; __fpurge(stdin); }while (reintentos>0); return ret; } int calcularMax (int *pArray, int len, int *maximo) { int i; int buffer; for(i=0;i<len;i++) { if (i==0 || buffer>pArray[i]) { buffer = pArray[i]; } } *maximo = buffer; return 0; } int calcularMin (int *pArray, int len, int *minimo) { int i; int buffer; for(i=0;i<len;i++) { if (i==0 || buffer<pArray[i]) { buffer = pArray[i]; } } *minimo = buffer; return 0; } int calcularPromedio(int *pArrayResultado, float *promedio, int tamArray) { int i; int acumulador=0; for (i=0; i<tamArray; i++) { acumulador+= pArrayResultado[i]; } *promedio = (float)acumulador/tamArray; return 0; } int buscarNumeroArray(int *pArray, int len, int numero) { int i; int ret=-1; for (i=0;i<len;i++) { if (numero == pArray[i]) { ret = 0; break; } } return ret; } int swap(int *A, int *B) { int buffer; buffer = *A; *A = *B; *B = buffer; return 0; } int ordenarBurbujeo(int *pArrayInt, int limite, int menorMayor) { //0 para mayor y 1 para menor; int i; int flagSwap; do{ flagSwap=0; for (i=0 ; i<limite-1; i++) { if (menorMayor==0 && pArrayInt[i]<pArrayInt[i+1]) { swap(&pArrayInt[i],&pArrayInt[i+1]); flagSwap++; } if (menorMayor==1 && pArrayInt[i]>pArrayInt[i+1]) { swap(&pArrayInt[i],&pArrayInt[i+1]); flagSwap++; } } }while(flagSwap!=0); return 0; } int mostrarArray (int *pArray,int limite) { int i; for(i=0;i<limite;i++) { printf("%d, ",pArray[i]); } return 0; }
C
// Copyright 2016 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #pragma once #include <magenta/processargs.h> #include <stdint.h> #ifdef __cplusplus extern "C" { #endif // The mx_tls_root_t describes the object pointed to by the thread-local // storage (TLS) register in a Magenta process. It holds TLS slots that // are used by libraries and language runtimes. // // To claim a slot, increment the next_tls_slot field in mx_proc_info // with a compare-and-swap and take the old value as an index into the // slots array. // // Any user code that calls the mx_thread_create system call is // responsible for allocating an mx_tls_root_t object with at least 8 // slots, setting its fields correctly, and placing a pointer to it in // the TLS register appropriately for the current architecture. // // On X86_64, *mx_tls_root_t should be loaded into the FS register. // On ARM64, *mx_tls_root_t should be loaded into the TPIDR_EL0 register. // On ARM32, *mx_tls_root_t should be loaded into the CP15 readonly register. typedef struct mx_tls_root mx_tls_root_t; struct mx_tls_root { mx_tls_root_t* self; mx_proc_info_t* proc; uint32_t magic; // MX_TLS_ROOT_MAGIC uint16_t flags; // Reserved for future use. uint16_t maxslots; // Number of slots in this object, minimum 8. void* slots[1]; // TLS slots. Has length maxslots. }; #define MX_TLS_ROOT_MAGIC 0x2facef0e #define MX_TLS_MIN_SLOTS 8 #define MX_TLS_ROOT_SIZE(x) \ (sizeof(mx_tls_root) + sizeof(void*) * (x->maxslots - 1)) #ifdef __cplusplus } #endif
C
#include<stdio.h> int main() { int num,remainder,result=0; printf("enter a number:"); scanf("%d",&num); num=number; while(number!=0) { remainder=number%10; result=remainder*remainder*remainder; number/=10; } if(result==num) printf("%d is an armstrong number:"); return(0); } }
C
/***************************************************************************** * * File: delays.c * * Copyright S. Brennen Ball, 2006-2007 * * The author provides no guarantees, warantees, or promises, implied or * otherwise. By using this software you agree to indemnify the author * of any damages incurred by using it. * *****************************************************************************/ //This code depends on a clock frequency of 40 MHz. #include "delays.h" void DelayUS(unsigned long microseconds) { int j; for (j = 0; j < 40*microseconds; j++) { // number is 1 million // do nothing } } void DelayMS(unsigned long milliseconds) { unsigned long count; for(count = 0; count < milliseconds; count++) DelayUS(1000);// 1000 us = 1 ms } void DelayS(unsigned long seconds) { unsigned long count; for(count = 0; count < seconds; count++) { DelayMS(1000);// 1 s = 1000 ms } }
C
/* *strings.c */ #include<stdio.h> #include<stdlib.h> #include<string.h> #include"strings.h" #include"errorhandler.h" string String(char *s) { string p = checked_malloc(strlen(s) + 1); strcpy(p,s); return p; } void *checked_malloc(int len) { void *p = malloc(len); if(!p) { fprintf(stderr, "\nRan out of usable memory!\n"); exit(1); } return p; }
C
#include<stdio.h> int num_list[10]= {2,5,7,9,3,1,0,6,4,8}; void selection_sort(); int main(){ int iswitch = 1;/*odering switch, 0:ascendeing, 1:descending*/ int i; selection_sort(iswitch); for(i=0;i<10;i++){ printf("%d",num_list[i]); } printf("\n"); } void selection_sort(int mode){ int i, j, min, temp; for (i = 0; i < 10-1; ++i){ min = i; for (j = i+1; j < 10; ++j){ if (num_list[j] < num_list[min]){ min = j; } } temp = num_list[min]; num_list[min] = num_list[i]; num_list[i] = temp; } if (mode == 1){ int start = 0, end = 9; while (start < end){ int temp = num_list[start]; num_list[start] = num_list[end]; num_list[end] = temp; start++; end--; } } }
C
#ifndef _DS_TRIE_H #define _DS_TRIE_H #include <stdbool.h> // The trie only accepts lower 26 characters, 'a' - 'z'. struct Trie; struct Trie* createTrie(); void destroyTrie(struct Trie* trie); bool trieAddWord(struct Trie* trie, const char* s); struct Trie* trieGetSubTrie(struct Trie* trie, char c); struct Trie* trieGetSubTrieByString(struct Trie* trie, const char* s); int trieGetCount(struct Trie* trie); void trieDecCount(struct Trie* trie); int trieGetTrieSize(struct Trie* trie); #endif // _DS_TRIE_H
C
#include <stdio.h> //program:复制字符串 //date:2018.05.23 int main(int argc, char *argv[]) { char *p = "123 456 789"; char buff[20] = {0}; int sum = 0; __asm__ __volatile__ ( "mov r0, %1 \n" "mov r3, %2 \n" "mov r1, #0 \n" "loop: \n" "ldr r2, [r0] \n" "ldr r4, [r3] \n" "cmp r2, #0 \n" "strne r2, [r3] \n" "addne r1, #1 \n" "addne r0, #1 \n" "addne r3, #1 \n" "bne loop \n" "mov %0, r1 \n" :"=r"(sum) :"r"(p),"r"(buff) :"r0", "r3","r1", "r2", "r4" ); printf("sum:%d\n", sum); printf("buff:%s\n", buff); return 0; }
C
int findx(int **ball,int N, int *arr) { int i,j=0,a=0; int x; while (a < N) { i = 0; j = 0; while (j < N) { x = ball[0][a] - ball[1][j]; for (i = 0; i < N; i++) { if (ball[1][j] - ball[2][i] == x) { /* temp = ball[2][0]; ball[2][0] = ball[2][i]; ball[2][i] = temp; temp2 = ball[1][0]; ball[1][0] = ball[1][j]; ball[1][j] = temp2; */ arr[a] = -x; a++; j = N; } else if (i == N - 1) { j++; i = 0; } } } } }
C
#include <log.h> #include <statedef.h> #include <script.h> #include <sprite.h> #include <level.h> #include <gameglobal.h> #include <physics.h> #include <string.h> #include <object.h> #include <camera.h> //Object type names const char object_typename_table[OBJECT_TYPES][MAXSTR] = { "unknown", "player", "enemy", "item", "door", "platform", "trigger", "npc", "rope", }; typedef struct { object_pair_handler_func_ptr func; } interaction_handler; static interaction_handler interaction_handlers[MAX_OBJECTS][MAX_OBJECTS]; void om_reset (objectmanager * om) { object **obj; int o; if(!om) return; //Empty the set obj = om->objectset; for(o=0;o<MAX_OBJECTS; ++o, ++obj) { if(*obj) free(*obj); *obj = NULL; } //Reset level pointer om->level = NULL; //Default: No interactions between object pairs { int a, b; for(a=0;a<MAX_OBJECTS;++a) { for(b=0;b<MAX_OBJECTS;++b) { interaction_handlers[a][b].func = (object_pair_handler_func_ptr) NULL; } } } #ifdef VERBOSE log_printf ("Reset ObjectManager ..."); #endif //VERBOSE } objectmanager * om_start (level * l) { objectmanager *om = (objectmanager *) malloc (sizeof (objectmanager)); int o; objectptr_iterator obj; om->begin = om->objectset; om->end = om->begin; obj = om->begin; for(o=0;o<MAX_OBJECTS; ++o, ++obj) *obj = NULL; om->level = l; #ifdef VERBOSE log_printf ("Started ObjectManager ..."); #endif //VERBOSE return om; } void om_end (objectmanager * om) { if (NULL == om) return; #ifdef VERBOSE log_printf ("Ending ObjectManager ..."); #endif //VERBOSE om_reset (om); free (om); } //Create an instance of a sprite spriteinstance * om_create_sprite_instance (objectmanager * om, const char *spritename) { spriteinstance *sprinstance = NULL; spritemap *sprmap = NULL; if(NULL == om) return sprinstance; if (NULL == om->level) return sprinstance; sprmap = om->level->sprm; if (NULL != sprmap) { sprite *whichsprite = NULL; int s; //Lookup sprite with matching name for (s = 0; s < sprmap->nsprites; ++s) { if (!strcasecmp (sprmap->spritenames[s], spritename)) { whichsprite = sprmap->sprites[s]; break; } } if (NULL != whichsprite) { //Create a sprite instance int curspriteinstance = sprmap->nspriteinstances; sprmap->spriteinstances[curspriteinstance].curframe = 0; sprmap->spriteinstances[curspriteinstance].cursst = DEFAULT_FORM; sprmap->spriteinstances[curspriteinstance].prevsst = DEFAULT_FORM; sprmap->spriteinstances[curspriteinstance].sprite = whichsprite; sprinstance = &sprmap->spriteinstances[curspriteinstance]; sprite_set_state (sprinstance, DEFAULT_FORM); #ifdef VERBOSE log_printf ("[OBJECT] Sprite instance #%d.",sprmap->nspriteinstances); #endif //VERBOSE sprmap->nspriteinstances++; } else { #ifdef VERBOSE log_printf ("[OBJECT] Sprite name match not found."); #endif //VERBOSE } } else { #ifdef VERBOSE log_printf ("[OBJECT] Suitable LEVEL_SPRITEMAP not found in Level %d.", curlevel); #endif //VERBOSE } return sprinstance; } objectmanager * om_get_active_objectmanager () { #ifdef VERBOSE log_printf ("[OBJECT] Current level query: %d", curlevel); #endif //VERBOSE if (NULL != levels[curlevel]) return (objectmanager *) (levels[curlevel]->objectmanager); return NULL; } static const object_handler HANDLER_NULL = { NULL, NULL, NULL }; object * om_create (objectmanager * om) { object *newobject; objectptr_iterator avail, end; int o = 0; if (NULL == om) { log_printf ("[OBJECT] NULL instance of ObjectManager received. Should abort."); exit (1); } //Find next available slot for object avail = om->begin; end = om->end; while((avail != end) && (*avail) && (!(*avail)->garbage)) { ++avail; ++o; } //No space available if(MAX_OBJECTS == o) return NULL; if(*avail) { //Already allocated, so re-use it newobject = *avail; } else { //Allocate new, update end newobject = (object *) malloc (sizeof(object)); *avail = newobject; om->end = avail+1; } //Pointer to itself used as unique id newobject->id = o; newobject->garbage = 0; newobject->setlocation = o; newobject->x = 0.0f; newobject->y = 0.0f; newobject->angle = 0.0f; newobject->vx = 0.0f; newobject->vy = 0.0f; newobject->vx_desired = 0.0f; newobject->vy_desired = 0.0f; newobject->wt = 1.0f; newobject->sprinstance = NULL; newobject->w = 1.0f; newobject->h = 1.0f; newobject->health = 100.0f; newobject->health_max = newobject->health; newobject->canrotate = 0; newobject->facing = OBJECT_FACING_DEFAULT; newobject->isstatic = 0; newobject->isrogue = 0; newobject->customshapes = 0; newobject->physicsdata = NULL; newobject->handlers = HANDLER_NULL; newobject->type = OBJECT_UNKNOWN; newobject->physicsdata = NULL; newobject->layer=0; newobject->state = 1; newobject->omanager = om; return newobject; } void om_add (objectmanager * om, object * newobject, void * data) { if(!om || !newobject) return; //NOTE: obj->w, obj->h are only used once to calculate body mass if (NULL != newobject->sprinstance) { newobject->w = newobject->sprinstance->sprite->spritewidth; newobject->h = newobject->sprinstance->sprite->spriteheight; } //Only add dynamics for known objects if(!newobject->isrogue) { #ifdef DEBUG log_printf("[OBJECT] Adding bodies of \"%s\" to space...",newobject->name); #endif //DEBUG physics_add_bodies(om->level->physics, newobject); //Everything has a shape for collisions //TODO: possibly condition this on other types if we don't need to check for collisions at all #ifdef DEBUG log_printf("[OBJECT] Adding shapes to space..."); #endif //DEBUG physics_add_shapes (om->level->physics, newobject); } script_add_to_dictionary (lua, newobject->name, newobject); log_printf("[OBJECT] Added %d(%s)",newobject->id,newobject->name); } void om_dump_object (object * ptr) { if (NULL == ptr) log_printf ("[om_dump_object] Invalid pointer (NULL) received. Ignoring, but this could be a problem."); else log_printf ("Object info: {%s @(%.1lf,%.1lf) phy(%x)}", ptr->name, ptr->x, ptr->y, ptr->physicsdata); } void om_center_camera_on (object * ptr) { if (NULL != ptr) { center_camera(ptr); } } object * om_get_object_by_name (const char *name) { object *found = NULL; //stack: [] lua_pushstring (lua, name); //stack: [string] l_FindObjectByName (lua); //stack: [void *] found = (object *) lua_touserdata (lua, -1); lua_pop (lua, -1); //stack: [] return found; } void om_set_handler (object * ptr, int handler_type, void *(*handler) (object * obj, void *data)) { if(!ptr || !handler || (handler_type < 0) || (handler_type >= OBJECT_HANDLER_TYPES)) return; { typedef void *(*HANDLER) (object * obj, void *data); HANDLER *h = (HANDLER *) & ptr->handlers; h[handler_type] = handler; } } //Number of objects int om_get_number_of_objects(objectmanager * om) { return (om->end - om->begin); } int om_update (void *omgr, float dt) { objectmanager *om = (objectmanager *) omgr; float posvec[3]; object *objptr = NULL; objectptr_iterator objit; int updated = 0; physics_update (om->level->physics, dt); //Retrieve new non-static object poses and speeds for consistency for (objit=om->begin; objit!=om->end; ++objit) { int objupdated = 0; objptr = *objit; if((NULL == objptr) || objptr->garbage) continue; if (!objptr->isrogue) { if(!objptr->isstatic) { physics_getpose (om->level->physics, objptr->physicsdata, posvec); objptr->x = posvec[0]; objptr->y = posvec[1]; objptr->angle = posvec[2]; physics_getvel (om->level->physics, objptr->physicsdata, posvec); objptr->vx = posvec[0]; objptr->vy = posvec[1]; if ((objptr->vx != 0) || (objptr->vy != 0)) objupdated = 1; } } //Per-object update if defined if (NULL != objptr->handlers._func[OBJECT_HANDLER_UPDATE]) { objptr->handlers._func[OBJECT_HANDLER_UPDATE] (objptr, NULL); objupdated = 1; } if(objptr->health <= 0.0) { if(om_get_object_state(objptr) == SPRITESET_DYING) { if(objptr->sprinstance->sprite->spritesets[SPRITESET_DYING] == NULL) { om_remove_object(om, objptr); } else if(objptr->sprinstance->curframe == objptr->sprinstance->sprite->spritesets[SPRITESET_DYING]->nframes - 1) { om_remove_object(om, objptr); } } else om_set_object_state(objptr,SPRITESET_DYING); } updated += objupdated; } return updated; } //Mark the object as garbage, so it can be re-used void om_dispose (objectmanager * om, object * object) { objectptr_iterator marker; if(!om || !object) return; marker = om->objectset + object->setlocation; (*marker)->garbage = 1; } const char* OBJECT_HANDLER_NAMES[OBJECT_HANDLER_TYPES] = { "init", "destroy", "update", "interact" }; //Removed checking because this function is called many times per frame CINLINE static int om_get_sequential_id(object *obj) { return obj->id; } void om_interact(object *obja, object *objb, void *data) { int idA, idB, ida, idb; object *a, *b; object_pair_handler_func_ptr interact; idA = om_get_sequential_id(obja); idB = om_get_sequential_id(objb); //Lex order ida = (idA<idB)?idA:idB; idb = (idA<idB)?idB:idA; a = (idA<idB)?obja:objb; b = (idA<idB)?objb:obja; interact = interaction_handlers[ida][idb].func; if(interact != NULL) { log_printf("[OBJECT] Interact Exists for %s, %s.", obja->name, objb->name); interact(a,b,data); } else { log_printf("[OBJECT] No Interaction Exists for %s, %s.", obja->name, objb->name); } } void om_set_interaction(object *obja, object *objb, object_pair_handler_func_ptr func) { int ida, idb; ida = om_get_sequential_id(obja); idb = om_get_sequential_id(objb); log_printf("[OBJECT] Adding Interaction for: %s, %s.", obja->name, objb->name); interaction_handlers[ida][idb].func = func; interaction_handlers[idb][ida].func = func; } int om_get_object_state(object *obj) { if(!obj) return 0; if(!obj->sprinstance) return obj->state; return sprite_get_state(obj->sprinstance); } void om_set_object_state(object *obj, int state) { if(!obj) return; if(!obj->sprinstance) obj->state = state; else sprite_set_state(obj->sprinstance, state); log_printf("[SET_OBJ_STATE] %s => %d",obj->name,sprite_get_state(obj->sprinstance)); } void om_remove_object(objectmanager *om, object *obj) { if(NULL == obj) return; if(NULL == obj->physicsdata) return; //Call the destroy_object callback if it was defined if (NULL != obj->handlers._func[OBJECT_HANDLER_DESTROY]) obj->handlers._func[OBJECT_HANDLER_DESTROY] (obj, NULL); script_remove_from_dictionary(obj->name); physics_cleanup_object(om->level->physics, obj->physicsdata); obj->physicsdata = NULL; om_dispose(om, obj); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <sys/stat.h> #include "varsFile.h" #define TRUE 1 #define FALSE 0 char **retValueListPtr; int retValueListCnt; int retValueListAllocated = FALSE; void freeValueList() { int i; if (retValueListAllocated) { for (i = 0; i < retValueListCnt; i++) { free(retValueListPtr[i]); } free(retValueListPtr); retValueListAllocated = FALSE; } } int readVarsFile(char *filename, char **inputVarList, int inputVarListCnt, char ***retValueList) { int i, j, c; int fileLineCnt; FILE *filePtr; int ignoreTxt; int readValue; int *valueSz; int readVar; int *varSz; int retValueListInc; int valueCharInc; int varCharInc; char **valueList; char **varList; filePtr = fopen(filename, "r"); if (filePtr == NULL) return TRUE; // find how many lines are in the file fileLineCnt = 0; while ((c = fgetc(filePtr)) != EOF) { if (c == 10) fileLineCnt++; } fileLineCnt++; // allocate memory to get the size of each value valueSz = (int *)malloc(fileLineCnt * sizeof(int)); // allocate memory to get the size of each variable varSz = (int *)malloc(fileLineCnt * sizeof(int)); rewind(filePtr); // get the character length of each variable label and value i = 0; valueSz[0] = 0; varSz[0] = 0; ignoreTxt = FALSE; readValue = FALSE; readVar = TRUE; while ((c = fgetc(filePtr)) != EOF) { if (c == '#') ignoreTxt = TRUE; if (c == 13) continue; if (c == 10) { if (readVar)// if '=' was not found varSz[i] = 0; i++; valueSz[i] = 0; varSz[i] = 0; ignoreTxt = FALSE; readValue = FALSE; readVar = TRUE; continue; } if (ignoreTxt) continue; // count the length of each variable value if (readValue) valueSz[i]++; if (c == '=') { readValue = TRUE; readVar = FALSE; continue; } if (isspace(c)) continue; // count the length of each variable label if (readVar) varSz[i]++; } // allocate memory for the variable list varList = (char **)malloc(fileLineCnt * sizeof(char *)); for (i = 0; i < fileLineCnt; i++) { varList[i] = (char *)malloc((varSz[i]+1) * sizeof(char)); } // allocate memory for the value list valueList = (char **)malloc(fileLineCnt * sizeof(char *)); for (i = 0; i < fileLineCnt; i++) { valueList[i] = (char *)malloc((valueSz[i]+1) * sizeof(char)); } rewind(filePtr); // read the label and value of each variable i = 0; valueCharInc = 0; varCharInc = 0; ignoreTxt = FALSE; readValue = FALSE; readVar = TRUE; while ((c = fgetc(filePtr)) != EOF) { if (c == '#') ignoreTxt = TRUE; if (c == 13) continue; if (c == 10) { valueList[i][valueCharInc] = 0; valueCharInc = 0; varList[i][varCharInc] = 0; varCharInc = 0; i++; ignoreTxt = FALSE; readValue = FALSE; readVar = TRUE; continue; } if (ignoreTxt) continue; // read the value of each variable if (readValue) if (valueSz[i]) { valueList[i][valueCharInc] = c; valueCharInc++; } if (c == '=') { readValue = TRUE; readVar = FALSE; continue; } if (isspace(c)) continue; // read the label of each variable if (readVar) if (varSz[i]) { varList[i][varCharInc] = c; varCharInc++; } } valueList[i][valueCharInc] = 0; varList[i][varCharInc] = 0; freeValueList(); // allocate memory for the returning value list retValueListCnt = inputVarListCnt; retValueListPtr = (char **)malloc(retValueListCnt * sizeof(char *)); retValueListAllocated = TRUE; retValueListInc = 0; for (i=0; i < inputVarListCnt; i++) { for (j=0; j < fileLineCnt; j++) { if (varSz[j]) if (!strcmp(inputVarList[i], varList[j])) { retValueListPtr[retValueListInc] = (char *)malloc((valueSz[j]+1) * sizeof(char)); strcpy(retValueListPtr[retValueListInc], valueList[j]); retValueListInc++; break; } } } // link to allocated memory of the variable values *retValueList = (char **)retValueListPtr; for (i = 0; i < fileLineCnt; i++) { free(varList[i]); } free(varList); for (i = 0; i < fileLineCnt; i++) { free(valueList[i]); } free(valueList); free(valueSz); free(varSz); fclose(filePtr); return FALSE; } int writeToVarsFile(char *filename, char **inputVarList, int inputVarListCnt, char **inputValueList) { struct stat stat_p; int i, j; FILE *filePtr; char *fileData; int fileLineCnt; int ignoreTxt; int readValue; int *valueSz; int readVar; int *varSz; int valueCharInc; int varCharInc; char **valueList; char **varList; int varsNotFoundCnt; int *varsNotFound; int varFound; int charInc; // if the file does not exist if (-1 == stat(filename, &stat_p)) { // open file for write filePtr = fopen(filename,"w"); if (!filePtr) return TRUE; // write the variables to file for (i=0; i < inputVarListCnt; i++) { fprintf(filePtr, "%s=%s\n", inputVarList[i], inputValueList[i]);// change \n to \n\r for windows } fclose(filePtr); return FALSE; } // allocate memory for bmp file fileData = (char *)malloc(stat_p.st_size); // open file for read filePtr = fopen(filename,"r"); if (!filePtr) return TRUE; // read file data to buffer fread(fileData, sizeof(char), stat_p.st_size, filePtr); fclose(filePtr); // find how many lines are in the file fileLineCnt = 1; for (i=0; i < stat_p.st_size; i++) { if (fileData[i] == 10) // new line fileLineCnt++; } // allocate memory to get the size of each variable varSz = (int *)malloc(fileLineCnt * sizeof(int)); // allocate memory to get the size of each value valueSz = (int *)malloc(fileLineCnt * sizeof(int)); // get the character length of each variable label and value i = 0; valueSz[0] = 0; varSz[0] = 0; ignoreTxt = FALSE; readValue = FALSE; readVar = TRUE; for (j=0; j < stat_p.st_size; j++) { if (fileData[j] == '#') ignoreTxt = TRUE; if (fileData[j] == 13) continue; if (fileData[j] == 10) { if (readVar)// if '=' was not found varSz[i] = 0; i++; valueSz[i] = 0; varSz[i] = 0; ignoreTxt = FALSE; readValue = FALSE; readVar = TRUE; continue; } if (ignoreTxt) continue; // count the length of each variable value if (readValue) valueSz[i]++; if (fileData[j] == '=') { readValue = TRUE; readVar = FALSE; continue; } if (isspace(fileData[j])) continue; // count the length of each variable label if (readVar) varSz[i]++; } // allocate memory for the variable list varList = (char **)malloc(fileLineCnt * sizeof(char *)); for (i = 0; i < fileLineCnt; i++) { varList[i] = (char *)malloc((varSz[i]+1) * sizeof(char)); } // allocate memory for the value list valueList = (char **)malloc(fileLineCnt * sizeof(char *)); for (i = 0; i < fileLineCnt; i++) { valueList[i] = (char *)malloc((valueSz[i]+1) * sizeof(char)); } // read the label and value of each variable i = 0; valueCharInc = 0; varCharInc = 0; ignoreTxt = FALSE; readValue = FALSE; readVar = TRUE; for (j=0; j < stat_p.st_size; j++) { if (fileData[j] == '#') ignoreTxt = TRUE; if (fileData[j] == 13) continue; if (fileData[j] == 10) { valueList[i][valueCharInc] = 0; valueCharInc = 0; varList[i][varCharInc] = 0; varCharInc = 0; i++; ignoreTxt = FALSE; readValue = FALSE; readVar = TRUE; continue; } if (ignoreTxt) continue; // read the value of each variable if (readValue) if (valueSz[i]) { valueList[i][valueCharInc] = fileData[j]; valueCharInc++; } if (fileData[j] == '=') { readValue = TRUE; readVar = FALSE; continue; } if (isspace(fileData[j])) continue; // read the label of each variable if (readVar) if (varSz[i]) { varList[i][varCharInc] = fileData[j]; varCharInc++; } } valueList[i][valueCharInc] = 0; varList[i][varCharInc] = 0; // allocate memory to note the variables that are not found varsNotFound = (int *)malloc(inputVarListCnt * sizeof(int)); // find the variables the are not found in the file varsNotFoundCnt = 0; for (i=0; i < inputVarListCnt; i++) { varFound = FALSE; for (j=0; j < fileLineCnt; j++) { if ((varSz[j]) && (!strcmp(inputVarList[i], varList[j]))) { varFound = TRUE; break; } } if (varFound == FALSE) { varsNotFound[i] = TRUE; varsNotFoundCnt++; } else varsNotFound[i] = FALSE; } // open file for write filePtr = fopen(filename,"w"); if (!filePtr) return TRUE; // write the new file charInc = 0; varFound = FALSE; for (j=0; j < fileLineCnt; j++) { varFound = FALSE; for (i=0; i < inputVarListCnt; i++) { if ((varSz[j]) && (!strcmp(inputVarList[i], varList[j]))) { varFound = TRUE; break; } } if (varFound) { fprintf(filePtr, "%s=%s\n", inputVarList[i], inputValueList[i]);// change \n to \n\r for windows while (charInc < stat_p.st_size) { if (fileData[charInc] == 10) { charInc++; break; } charInc++; } } else { while (charInc < stat_p.st_size) { if (fileData[charInc] == 13) { charInc++; continue; } putc(fileData[charInc], filePtr); if (fileData[charInc] == 10) { //putc(10, filePtr); // for windows charInc++; break; } charInc++; } } } // write the missing variables to file for (i=0; i < inputVarListCnt; i++) { if (varsNotFound[i]) fprintf(filePtr, "\n%s=%s", inputVarList[i], inputValueList[i]);// change \n to \n\r for windows } fclose(filePtr); free(varsNotFound); for (i = 0; i < fileLineCnt; i++) { free(valueList[i]); } free(valueList); for (i = 0; i < fileLineCnt; i++) { free(varList[i]); } free(varList); free(valueSz); free(varSz); free(fileData); return FALSE; }
C
#include <stdio.h> #include <stdlib.h> #include "heap.h" void heapSort(Heap **heap) { int i, n = (*heap)->size, tmp; for(i = (n - 2) / 2; i >= 0; i--) { descer(heap, i); } for(i = n - 1; i > 0; i--) { tmp = (*heap)->h[0]; (*heap)->h[0] = (*heap)->h[i]; (*heap)->h[i] = tmp; (*heap)->size -= 1; descer(heap, 0); } (*heap)->size = n; } void removerHeap(Heap **heap) { (*heap)->h[0] = (*heap)->h[(*heap)->size - 1]; (*heap)->size -= 1; (*heap)->h = realocarVetor((*heap)->h, (*heap)->size); descer(heap, 0); } void mostrarInformacoes(Heap *heap, int i) { if(heap == NULL || i < 0) { printf("O no %d nao existe!\n", i); return; } printf("Indice %d\n", i); printf("Pai do no %d: %d\n", heap->h[i], mostrarPai(heap, i)); printf("Filho esquerdo %d: %d\n", heap->h[i], mostrarFilhoEsquerdo(heap, i)); printf("Filho direito %d: %d\n", heap->h[i], mostrarFilhoDireito(heap, i)); } int mostrarPai(Heap *heap, int i) { if(heap == NULL || i < 0 || i > heap->size) { return -1; } return heap->h[(i - 1) / 2]; } int mostrarFilhoEsquerdo(Heap *heap, int i) { if(heap == NULL || i < 0 || i > heap->size) { return -1; } return heap->h[(2 * i + 1)]; } int mostrarFilhoDireito(Heap *heap, int i) { if(heap == NULL || i < 0 || i > heap->size) { return -1; } return heap->h[(2 * i + 2)]; } void inserirHeap(Heap **heap, int k) { if(*heap == NULL) { inicializarHeap(heap); } if((*heap)->size == 0) { (*heap)->size = 1; (*heap)->h = inicializarVetor(1); (*heap)->h[0] = k; } else { (*heap)->size += 1; (*heap)->h = realocarVetor((*heap)->h, (*heap)->size); (*heap)->h[(*heap)->size - 1] = k; subir(heap, (*heap)->size - 1); } } /* recebe um vetor e corrige ele de forma a transforma-lo em um max-heap */ void corrigirMaxHeap(Heap **heap) { if(*heap == NULL) { return; } int i; for(i = 0; i < (*heap)->size; i++) { subir(heap, i); } } /* recebe um vetor e corrige ele de forma a transforma-lo em um min-heap */ void corrigirMinHeap(Heap **heap) { if(*heap == NULL) { return; } int i; for(i = ((*heap)->size - 2) / 2; i >= 0; i--) { descer(heap, i); } } void descer(Heap **heap, int i) { if(i < 0 || i > (*heap)->size || *heap == NULL) { return; } int k = 2 * i + 1; int x = (*heap)->h[i]; while(k < (*heap)->size) { if((k < ((*heap)->size - 1)) && ((*heap)->h[k] < (*heap)->h[k + 1])) { k++; } if(x < (*heap)->h[k]) { (*heap)->h[i] = (*heap)->h[k]; i = k; k = 2 * k + 1; } else { break; } } (*heap)->h[i] = x; } void subir(Heap **heap, int i) { if(i < 0 || i > (*heap)->size || *heap == NULL) { return; } int j = (i - 1) / 2; int x = (*heap)->h[i]; while(i > 0 && (*heap)->h[j] < x) { (*heap)->h[i] = (*heap)->h[j]; i = j; j = (j - 1) / 2; } (*heap)->h[i] = x; } void destruirHeap(Heap **heap) { if(*heap != NULL) { free(*heap); *heap = NULL; } } int *realocarVetor(int *v, int n) { if(v == NULL || n < 0) { return v; } int *tmp; tmp = (int*)realloc(v, n * sizeof(int)); if(tmp == NULL) { return v; } return tmp; } int *inicializarVetor(int n) { int *novoVetor, i; novoVetor = (int*)malloc(n * sizeof(int)); if(novoVetor == NULL) { return NULL; } return novoVetor; } void percorrerVetor(int *v, int n) { if(v == NULL || n < 0) { return; } int i; for(i = 0; i < n; i++) { printf("%d ", *(v + i)); } printf("\n"); } void inicializarHeap(Heap **heap) { Heap *novoHeap; novoHeap = (Heap*)malloc(sizeof(Heap)); if(novoHeap == NULL) { *heap = NULL; } novoHeap->h = NULL; novoHeap->size = 0; *heap = novoHeap; }