file
stringlengths 18
26
| data
stringlengths 4
1.03M
|
---|---|
the_stack_data/232956078.c | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
/*
* 移动字符串内容
* 把倒数几个字符进行移位,如
* abcdefghijk 移位M=3 即ijkabcdefgh
* m = 3, i = 0, len = 11, s[11] = s[0] = a,s[0] = s[1] = b,s[0] - abcdefgh(8)
* s[8] = s[9] = i j k * three(m) rounds
* */
void move_nstr(char *s, int m)
{
unsigned int i = 0;
unsigned int j = 0;
unsigned int len;
len = strlen(s);
if (len == 0)
return;
if (m > len)/*超过原大小,直接赋值len*/
m = len;
/*逐一移位*/
for (i = 0; i < len - m; i++)
for (j = 0,s[len] = s[0]; j < len; j++)
s[j] = s[j+1];
if (len != strlen(s))/*判断是否变长字符串*/
s[len] = '\0';/*结束符*/
}
/*new function memcpy*/
void *self_memcpy(void *dst, const char *src, int count)
{
char *dt = dst;
const char *sc = src;
while(count--)
*dt++ = *sc++;
return dst;/*返回void指定类型数据*/
}
/*
* new function memcpy
* void *dst to char *dst which avoids warnings
*/
void *self_memmove(char *dst, const char *src, int count)
{
char *dt = dst;
const char *sc = src;
/*
* overlapping area
* one way dst =< src: H |src|dst| L --> H |src|dst|xxxxx-count-xxxxx L
* the other way dst > src: H |dst|src| L --> H |dst|src|xxxxx-count-xxxxx L 该处出现内存重叠,
* 则在 H |dst|xxxx-count-xxxxx|src|xxxxx-count-xxxxx L
* 对比内存位置
* H |xxxxxxx|hello|11111 L
* H |xxxxxxx|11111|hello|11111| L
* 不覆盖源串,新串可以被填入。
*/
if (src >= dst)
while(count--)
*dt++ = *sc++;
else{
dt += count;
sc += count;
while(count--)
*--dt = *--sc;
}
return dst;
}
/*valid digit*/
int valid_digit(const char c)
{
if (c >= '0' && c <= '9')
return 0;
return 1;
}
/*get digit*/
void self_get_digits(const char *str)
{
assert(str);
int num = 0;
int len = strlen(str);
/*
* 123de1234jlads1
* 123 1234 1(1可以打印)xxx
* 作为结果
*/
while (len--){
if (!valid_digit(*str)){
num = 10*num + *str - '0';/*字符转数字*/
if (!num)
printf("The num is %d\n",num);
}else{
if (num != 0){
printf("The num is %d\n",num);
num = 0;
}
}
str++;
if (*str == '\0')/*结束符判断*/
printf("The num is %d\n",num);
}
}
/*new function strcmp*/
int self_strcmp(const char *src, char *dst)
{
assert(src);
assert(dst);
unsigned char sc;
unsigned char dt;
while(1){
sc = *src++;
dt = *dst++;
if (sc != dt)/*比较大小,不想等则肯定大小*/
return sc < dt ? -1 : 1;
if (!sc)/*相等情况下,若sc存在则break,返回0*/
break;
}
return 0;
}
/*new function strncmp*/
int self_strncmp(const char *src, char *dst, unsigned int count)
{
assert(src);
assert(dst);
unsigned char sc;
unsigned char dt;
if (count == 0)
return 0;
while(--count){
sc = *src++;
dt = *dst++;
if (sc != dt)
return sc < dt ? -1 : 1;
if (!sc)
break;
}
return 0;
}
/*new function strcpy*/
void self_strcpy(char *dst, const char *src)
{
int len = 0;
assert(dst);
assert(src);
while(*src != '\0'){
*dst++ = *src++;
}
*dst = '\0';
}
/*new function strncpy*/
char *self_strncpy(char *dst, const char *src, int size)
{
if (0 == size){
return dst;
}
while(size--){
*dst = *src;
if (*dst == '\0'){
//return dst;
break;
}
dst++;
src++;
}
*dst = '\0';
return dst;
}
/*new function strlen*/
int self_strlen1(const char *s) {
int len = 0;
while(*s++ != '\0')
len++;
return len;
}
int self_strlen2(const char *s)
{
const char *sc = s;
/*from linux kernel tree source
for(sc = s;*sc != '\0';sc++)
;
*/
while(*++sc != '\0');/*提前判断到结束符*/
return (sc - s);/*get the len*/
}
/*memset*/
void *self_memset(void *s, int c, int count)
{
char *sc = s;
/*copied from*/
if (0 >= count)
return NULL;
if (0 != c)
return NULL;
while(count--)
*sc++ = c;
return s;
}
/**copy_string*/
char *copy_string(const char *src)
{
assert(src);
int len = 0;
char *new_str = NULL;
new_str = (char*)malloc(strlen(src) + 1);
if (NULL == new_str){
goto failure;/*goto free*/
}
self_strcpy(new_str,src);
free(new_str);
return new_str;
failure:
free(new_str);
new_str = NULL;
return new_str;
}
|
the_stack_data/107951994.c | #include <stdio.h>
int main(void)
{
float money;
printf("Enter an amount: ");
scanf("%f", &money);
printf("With tax added: $%.2f\n", money + (money * .05));
return 0;
}
|
the_stack_data/190768042.c | int main(){int a; int b; a=29;b=5*(9-6);a+b;}
|
the_stack_data/126796.c | /* $OpenBSD: inet_net_ntop.c,v 1.8 2015/05/14 11:52:43 jsg Exp $ */
/*
* Copyright (c) 2012 by Gilles Chehade <[email protected]>
* Copyright (c) 1996 by Internet Software Consortium.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
* ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
* CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static char *inet_net_ntop_ipv4(const u_char *, int, char *, size_t);
static char *inet_net_ntop_ipv6(const u_char *, int, char *, size_t);
/*
* char *
* inet_net_ntop(af, src, bits, dst, size)
* convert network number from network to presentation format.
* generates CIDR style result always.
* return:
* pointer to dst, or NULL if an error occurred (check errno).
* author:
* Paul Vixie (ISC), July 1996
*/
char *
inet_net_ntop(int af, const void *src, int bits, char *dst, size_t size)
{
switch (af) {
case AF_INET:
return (inet_net_ntop_ipv4(src, bits, dst, size));
case AF_INET6:
return (inet_net_ntop_ipv6(src, bits, dst, size));
default:
errno = EAFNOSUPPORT;
return (NULL);
}
}
/*
* static char *
* inet_net_ntop_ipv4(src, bits, dst, size)
* convert IPv4 network number from network to presentation format.
* generates CIDR style result always.
* return:
* pointer to dst, or NULL if an error occurred (check errno).
* note:
* network byte order assumed. this means 192.5.5.240/28 has
* 0x11110000 in its fourth octet.
* author:
* Paul Vixie (ISC), July 1996
*/
static char *
inet_net_ntop_ipv4(const u_char *src, int bits, char *dst, size_t size)
{
char *odst = dst;
u_int m;
int b;
char *ep;
int advance;
ep = dst + size;
if (ep <= dst)
goto emsgsize;
if (bits < 0 || bits > 32) {
errno = EINVAL;
return (NULL);
}
if (bits == 0) {
if (ep - dst < sizeof "0")
goto emsgsize;
*dst++ = '0';
*dst = '\0';
}
/* Format whole octets. */
for (b = bits / 8; b > 0; b--) {
if (ep - dst < sizeof "255.")
goto emsgsize;
advance = snprintf(dst, ep - dst, "%u", *src++);
if (advance <= 0 || advance >= ep - dst)
goto emsgsize;
dst += advance;
if (b > 1) {
if (dst + 1 >= ep)
goto emsgsize;
*dst++ = '.';
*dst = '\0';
}
}
/* Format partial octet. */
b = bits % 8;
if (b > 0) {
if (ep - dst < sizeof ".255")
goto emsgsize;
if (dst != odst)
*dst++ = '.';
m = ((1 << b) - 1) << (8 - b);
advance = snprintf(dst, ep - dst, "%u", *src & m);
if (advance <= 0 || advance >= ep - dst)
goto emsgsize;
dst += advance;
}
/* Format CIDR /width. */
if (ep - dst < sizeof "/32")
goto emsgsize;
advance = snprintf(dst, ep - dst, "/%u", bits);
if (advance <= 0 || advance >= ep - dst)
goto emsgsize;
dst += advance;
return (odst);
emsgsize:
errno = EMSGSIZE;
return (NULL);
}
static char *
inet_net_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size)
{
int ret;
char buf[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255:255:255:255/128")];
if (bits < 0 || bits > 128) {
errno = EINVAL;
return (NULL);
}
if (inet_ntop(AF_INET6, src, buf, size) == NULL)
return (NULL);
ret = snprintf(dst, size, "%s/%d", buf, bits);
if (ret == -1 || ret >= size) {
errno = EMSGSIZE;
return (NULL);
}
return (dst);
}
|
the_stack_data/242329606.c | /*
The following code uses an array of pointers to take as input a list of strings from the user.
It then sorts the strings in alphabetical order and displays the list.
*/
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
int i = 0, j = 0, size = 0;
printf("How many names would you like to add to your list?\n");
scanf("%d", &size);
setbuf(stdin, NULL); // removes pending newline left from pressing the return key
char *list[size], tmp[20]; // declares an array of character pointers and a temporary character array for swapping
printf("Please enter the names.\n");
for(i = 0; i < size; i++)
{
list[i] = (char *)malloc(20 * sizeof(char)); // dynamically allocates memory for each string
fgets(list[i], 20, stdin); // takes user input
strtok(list[i], "\n"); // removes pending newline
}
printf("\n");
printf("The list of names is:\n");
for(i = 0; i < size; i++)
{
printf("%s\n", *(list + i));
}
printf("\n");
for(i = 0; i < size - 1; i++)
{
for(j = i + 1; j < size; j++)
{
if(strcmp(list[i], list[j]) > 0) // compares the strings lexicographically
{
strcpy(tmp, list[i]);
strcpy(list[i], list[j]);
strcpy(list[j], tmp);
}
else
continue;
}
}
printf("\n");
printf("The list sorted in alphabetical order is:\n");
for(i = 0; i < size; i++)
{
printf("%s\n", *(list + i)); // displays the sorted list
}
return 0;
}
|
the_stack_data/341282.c | #include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXRECVMSG (255)
int main(int argc, char *argv[]) {
char *mcastIP;
unsigned int mcastPort;
int sock;
int optVal;
struct sockaddr_in mcastAddr;
struct ip_mreq mcastReq;
int msgCount;
struct sockaddr_in fromAddr;
unsigned int fromAddrLen;
char msgBuffer[MAXRECVMSG + 1];
int recvMsgLen;
if(argc != 3) {
fprintf(stderr, "Usage: %s <Multicast IP Address> <Multicast Port>\n", argv[0]);
exit(1);
}
mcastIP = argv[1];
mcastPort = atoi(argv[2]);
sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(sock < 0) {
fprintf(stderr, "socket() failed\n");
exit(1);
}
memset(&mcastAddr, 0, sizeof(mcastAddr));
mcastAddr.sin_family = AF_INET;
mcastAddr.sin_addr.s_addr = htonl(INADDR_ANY);
mcastAddr.sin_port = htons(mcastPort);
optVal = 1;
if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&optVal, sizeof(optVal)) < 0) {
fprintf(stderr, "setsockopt() failed\n");
exit(1);
}
if(bind(sock, (struct sockaddr *)&mcastAddr, sizeof(mcastAddr)) < 0) {
fprintf(stderr, "bind() failed\n");
exit(1);
}
mcastReq.imr_multiaddr.s_addr = inet_addr(mcastIP);
mcastReq.imr_interface.s_addr = htonl(INADDR_ANY);
if(setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, (void*)&mcastReq, sizeof(mcastReq)) < 0) {
fprintf(stderr, "setsockopt() failed\n");
exit(1);
}
for(msgCount = 0; msgCount < 4; msgCount++) {
fromAddrLen = sizeof(fromAddr);
recvMsgLen = recvfrom(sock, msgBuffer, MAXRECVMSG, 0,
(struct sockaddr*)&fromAddr, &fromAddrLen);
if(recvMsgLen < 0) {
fprintf(stderr, "recvfrom() failed\n");
exit(1);
}
msgBuffer[recvMsgLen] = '\0';
printf("Received: %s from %s\n", msgBuffer, inet_ntoa(fromAddr.sin_addr));
}
close(sock);
exit(0);
}
|
the_stack_data/46865.c | int main(int argc, char** argv) {
if (1 == 0) return 1;
return 0;
}
|
the_stack_data/100140796.c | #include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
void pickMRand (int* original, int* subset, int n, int m);
int Rand (int lower, int higher);
void pickMRand_2 (int* original, int* subset, int n, int m);
int size = 10;
int main(){
int org[20] = {10,13,22,23,4,51,6,5,81,9,10,1,4,11,14,15,6,37,18,20};
int sub1[size];
int sub2[size];
pickMRand(org,sub1,20,size);
pickMRand_2(org,sub2,20,size);
printf("課題 2 | 4\n");
for(int i=0;i<size;i++){
printf("%2d: %2d || %2d\n",i,sub1[i],sub2[i]);
}
}
void pickMRand (int* original, int* subset, int n, int m) {
for (int i = 0; i < m; i++) {
int index = (int)(rand() % n);
subset[i] = original[index];
}
}
int Rand (int lower, int higher) {
return lower + (int)(rand() % (higher-lower +1));
}
void pickMRand_2 (int* original, int* subset, int n, int m) {
int array[n];
memcpy(array, original, sizeof(int)*n);
for (int i=0; i<m; i++) {
int index = Rand (i, n-1);
subset[i] = array[index];
array[index] = array[i];
}
}
|
the_stack_data/100358.c | #include<stdio.h>
#include<stdbool.h>
#include<math.h>
#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
#define nl printf("\n")
#define INT_MAX 100000
void swap(int *a,int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp; //xor swapping isn't working in this case. why?
}
int minHeap[INT_MAX]; int minHeapSize=0;
int maxHeap[INT_MAX]; int maxHeapSize=0;
void heapifyDown(int i,int heap[],int condition,int size) {
int leftIndex = 2*i+1;
int rightIndex = 2*i+2;
if(leftIndex < size) {
//left index exists
if(condition == 0) {
//min Heap
int smallerIndex = leftIndex;
if(rightIndex < size) {
//right index exists
if(heap[leftIndex] > heap[rightIndex])
smallerIndex = rightIndex;
}
if(heap[smallerIndex] < heap[i]) {
swap(&heap[i],&heap[smallerIndex]);
heapifyDown(smallerIndex,heap,condition,size);
}
}
else {
//max Heap
int largestIndex = leftIndex;
if(rightIndex < size) {
//right index exists
if(heap[leftIndex] < heap[rightIndex])
largestIndex = rightIndex;
}
if(heap[largestIndex] > heap[i]) {
swap(&heap[i],&heap[largestIndex]);
heapifyDown(largestIndex,heap,condition,size);
}
}
}
}
void pop(int heap[],int *size,int condition) {
heap[0] = heap[*size-1];
(*size)--;
heapifyDown(0,heap,condition,*size);
}
int top(int heap[],int size) {
return heap[0];
}
void heapifyUp(int i,int heap[],int condition) {
int parentIndex = floor((i-1)/2);
if(parentIndex < 0)
return;
if(condition == 0) {
//min Heap
if(heap[i] < heap[parentIndex]) {
swap(&heap[i],&heap[parentIndex]);
heapifyUp(parentIndex,heap,condition);
}
}
else {
//max Heap
if(heap[i] > heap[parentIndex]) {
swap(&heap[i],&heap[parentIndex]);
heapifyUp(parentIndex,heap,condition);
}
}
}
void push(int heap[],int *size,int x,int condition) {
heap[*size] = x;
(*size)++;
heapifyUp(*size-1,heap,condition);
}
void insert(int x) {
if(maxHeapSize && x>=top(maxHeap,maxHeapSize))
push(minHeap,&minHeapSize,x,0);
else
push(maxHeap,&maxHeapSize,x,1);
}
void balance() {
if((minHeapSize-maxHeapSize)>1 || (minHeapSize-maxHeapSize)<-1) {
if(minHeapSize > maxHeapSize) {
push(maxHeap,&maxHeapSize,top(minHeap,minHeapSize),1);
pop(minHeap,&minHeapSize,0);
}
else {
push(minHeap,&minHeapSize,top(maxHeap,maxHeapSize),0);
pop(maxHeap,&maxHeapSize,1);
}
}
}
double getMedian() {
if(minHeapSize == maxHeapSize) {
return (double)(top(maxHeap,maxHeapSize)+top(minHeap,minHeapSize))/2;
}
else {
if(minHeapSize > maxHeapSize)
return top(minHeap,minHeapSize);
else
return top(maxHeap,maxHeapSize);
}
}
int main() {
#ifndef ONLINE_JUDGE
//for getting input from input.txt
freopen("input.txt","r",stdin);
//for writing output to output.txt
freopen("output.txt","w",stdout);
#endif
int n; scanf("%d",&n);
while(n--) {
int x; scanf("%d",&x);
insert(x);
//printf("top min %d\n",top(minHeap,minHeapSize));
//printf("top max %d\n",top(maxHeap,maxHeapSize));
balance();
//printf("top min %d\n",top(minHeap,minHeapSize));
//printf("top max %d\n",top(maxHeap,maxHeapSize));
printf("%lf\n",getMedian());
}
return 0;
}
|
the_stack_data/82949415.c | #include <stdio.h>
#include <math.h>
int main(void) {
float a, b, c, delta, x1, x2;
printf("ax² + bx + c = 0\nInforme o 'a': ");
scanf("%f", &a);
printf("Informe o 'b': ");
scanf("%f", &b);
printf("Informe o 'c': ");
scanf("%f", &c);
printf("\n%.2fx² + %.2fx + %.2f = 0", a, b, c);
delta = (b*b) - (4*a*c);
printf("\nDelta é: %.2f\n\n", delta);
if (delta < 0) {
printf("Menor que zero, não possui raízes reais");
} else if (delta == 0) {
printf("Igual a zero, uma raíz real: %.2f", -b/(2*a));
} else if (delta > 0) {
x1 = ((-b) + sqrt(delta))/(2*(a));
x2 = ((-b) - sqrt(delta))/(2*(a));
printf("Maior que zero, duas raízes reais\nX1 (delta positivo): %.2f\nX2 (delta negativo): %.2f", x1, x2);
}
return 0;
} |
the_stack_data/32950329.c | // Generated file. DO NOT EDIT!
// aom_av1_encoder_ssse3 needs a c file to force link language,
// or to silence a harmless CMake warning: Ignore me.
void aom_av1_encoder_ssse3_dummy_function(void) {}
|
the_stack_data/291233.c | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* This program is used to test the QEMUD fast pipes.
* See external/qemu/docs/ANDROID-QEMUD-PIPES.TXT for details.
*
* The program acts as a simple TCP server that accepts data and sends
* them back to the client as is.
*/
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
/* Default port number */
#define DEFAULT_PORT 8012
#define DEFAULT_PATH "/tmp/libqemu-socket"
/* Try to execute x, looping around EINTR errors. */
#undef TEMP_FAILURE_RETRY
#define TEMP_FAILURE_RETRY(exp) ({ \
typeof (exp) _rc; \
do { \
_rc = (exp); \
} while (_rc == -1 && errno == EINTR); \
_rc; })
#define TFR TEMP_FAILURE_RETRY
/* Close a socket, preserving the value of errno */
static void
socket_close(int sock)
{
int old_errno = errno;
close(sock);
errno = old_errno;
}
/* Create a server socket bound to a loopback port */
static int
socket_loopback_server( int port, int type )
{
struct sockaddr_in addr;
int sock = socket(AF_INET, type, 0);
if (sock < 0) {
return -1;
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
int n = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n));
if (TFR(bind(sock, (struct sockaddr*)&addr, sizeof(addr))) < 0) {
socket_close(sock);
return -1;
}
if (type == SOCK_STREAM) {
if (TFR(listen(sock, 4)) < 0) {
socket_close(sock);
return -1;
}
}
return sock;
}
static int
socket_unix_server( const char* path, int type )
{
struct sockaddr_un addr;
int sock = socket(AF_UNIX, type, 0);
if (sock < 0) {
return -1;
}
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", path);
unlink(addr.sun_path);
printf("Unix path: '%s'\n", addr.sun_path);
int n = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n));
if (TFR(bind(sock, (struct sockaddr*)&addr, sizeof(addr))) < 0) {
socket_close(sock);
return -1;
}
if (type == SOCK_STREAM) {
if (TFR(listen(sock, 4)) < 0) {
socket_close(sock);
return -1;
}
}
return sock;
}
char* progname;
static void usage(int code)
{
printf("Usage: %s [options]\n\n", progname);
printf(
"Valid options are:\n\n"
" -? -h --help Print this message\n"
" -unix <path> Use unix server socket\n"
" -tcp <port> Use local tcp port (default %d)\n"
"\n", DEFAULT_PORT
);
exit(code);
}
/* Main program */
int main(int argc, char** argv)
{
int sock, client;
int port = DEFAULT_PORT;
const char* path = NULL;
const char* tcpPort = NULL;
/* Extract program name */
{
char* p = strrchr(argv[0], '/');
if (p == NULL)
progname = argv[0];
else
progname = p+1;
}
/* Parse options */
while (argc > 1 && argv[1][0] == '-') {
char* arg = argv[1];
if (!strcmp(arg, "-?") || !strcmp(arg, "-h") || !strcmp(arg, "--help")) {
usage(0);
} else if (!strcmp(arg, "-unix")) {
if (argc < 3) {
fprintf(stderr, "-unix option needs an argument! See --help for details.\n");
exit(1);
}
argc--;
argv++;
path = argv[1];
} else if (!strcmp(arg, "-tcp")) {
if (argc < 3) {
fprintf(stderr, "-tcp option needs an argument! See --help for details.\n");
exit(1);
}
argc--;
argv++;
tcpPort = argv[1];
} else {
fprintf(stderr, "UNKNOWN OPTION: %s\n\n", arg);
usage(1);
}
argc--;
argv++;
}
if (path != NULL) {
printf("Starting pipe test server on unix path: %s\n", path);
sock = socket_unix_server( path, SOCK_STREAM );
} else {
printf("Starting pipe test server on local port %d\n", port);
sock = socket_loopback_server( port, SOCK_STREAM );
}
if (sock < 0) {
fprintf(stderr, "Could not start server: %s\n", strerror(errno));
return 1;
}
printf("Server ready!\n");
RESTART:
client = TFR(accept(sock, NULL, NULL));
if (client < 0) {
fprintf(stderr, "Server error: %s\n", strerror(errno));
return 2;
}
printf("Client connected!\n");
/* Now, accept any incoming data, and send it back */
for (;;) {
char buff[32768], *p;
int ret, count;
ret = TFR(read(client, buff, sizeof(buff)));
if (ret < 0) {
fprintf(stderr, "Client read error: %s\n", strerror(errno));
socket_close(client);
return 3;
}
if (ret == 0) {
break;
}
count = ret;
p = buff;
//printf(" received: %d bytes\n", count);
while (count > 0) {
ret = TFR(write(client, p, count));
if (ret < 0) {
fprintf(stderr, "Client write error: %s\n", strerror(errno));
socket_close(client);
return 4;
}
//printf(" sent: %d bytes\n", ret);
p += ret;
count -= ret;
}
}
printf("Client closed connection\n");
socket_close(client);
goto RESTART;
return 0;
}
|
the_stack_data/611697.c | #include <stdio.h>
int snprintf(char *s, size_t n,const char * fmt, ...)
{
va_list ap;
int rv;
va_start(ap, fmt);
rv = vsnprintf(s, n, fmt, ap);
va_end(ap);
return rv;
}
|
the_stack_data/97014026.c | int main(void)
{
foo();
foo(1);
foo(1, 2);
return 0;
}
|
the_stack_data/379488.c | extern const unsigned char Pods_ParseChatVersionString[];
extern const double Pods_ParseChatVersionNumber;
const unsigned char Pods_ParseChatVersionString[] __attribute__ ((used)) = "@(#)PROGRAM:Pods_ParseChat PROJECT:Pods-1" "\n";
const double Pods_ParseChatVersionNumber __attribute__ ((used)) = (double)1.;
|
the_stack_data/476383.c | #include <stdio.h>
#include <math.h>
int main()
{
long long int a,num,b,t,i,mod,sum,l;
scanf("%lld", &t);
for(i=1; i<=t; i++)
{
scanf("%lld", &num);
b = num;
sum = 0;
l = 0;
while(num!=1 && l<256)
{
sum = 0;
while(num!=0)
{
mod = num%10;
sum+= mod*mod;
num/=10;
}
num = sum;
l++;
}
if(num==1)
printf("Case #%lld: %lld is a Happy number.\n",i,b);
else
printf("Case #%lld: %lld is an Unhappy number.\n",i,b);
}
return 0;
}
|
the_stack_data/59929.c | /* pizza.c -- 在比萨饼程序中使用已定义的常量 */
#include <stdio.h>
#define PI 3.14159
int main(void)
{
float area, circum, radius;
printf("What is the radius of your pizza?\n");
scanf("%f", &radius);
area = PI * radius * radius;
circum = 2.0 * PI * radius;
printf("Your basic pizza parameters are as follows:\n");
printf("circumference = %1.2f, area = %1.2f\n", circum, area);
return 0;
} |
the_stack_data/138552.c | /*
* Copyright 2007-2012 Niels Provos and Nick Mathewson
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 4. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "event2/event-config.h"
#include <sys/types.h>
#include <sys/stat.h>
#ifdef _EVENT_HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <sys/socket.h>
#include <sys/resource.h>
#endif
#include <signal.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifdef _EVENT_HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <errno.h>
#include <event.h>
#include <evutil.h>
/*
* This benchmark tests how quickly we can propagate a write down a chain
* of socket pairs. We start by writing to the first socket pair and all
* events will fire subsequently until the last socket pair has been reached
* and the benchmark terminates.
*/
static int fired;
static int *pipes;
static struct event *events;
static void
read_cb(evutil_socket_t fd, short which, void *arg)
{
char ch;
long idx = (long) arg;
recv(fd, &ch, sizeof(ch), 0);
if (idx >= 0)
send(idx, "e", 1, 0);
fired++;
}
static struct timeval *
run_once(int num_pipes)
{
int *cp, i;
static struct timeval ts, te, tv_timeout;
events = calloc(num_pipes, sizeof(struct event));
pipes = calloc(num_pipes * 2, sizeof(int));
if (events == NULL || pipes == NULL) {
perror("malloc");
exit(1);
}
for (cp = pipes, i = 0; i < num_pipes; i++, cp += 2) {
if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, cp) == -1) {
perror("socketpair");
exit(1);
}
}
/* measurements includes event setup */
evutil_gettimeofday(&ts, NULL);
/* provide a default timeout for events */
evutil_timerclear(&tv_timeout);
tv_timeout.tv_sec = 60;
for (cp = pipes, i = 0; i < num_pipes; i++, cp += 2) {
long fd = i < num_pipes - 1 ? cp[3] : -1;
event_set(&events[i], cp[0], EV_READ, read_cb, (void *) fd);
event_add(&events[i], &tv_timeout);
}
fired = 0;
/* kick everything off with a single write */
send(pipes[1], "e", 1, 0);
event_dispatch();
evutil_gettimeofday(&te, NULL);
evutil_timersub(&te, &ts, &te);
for (cp = pipes, i = 0; i < num_pipes; i++, cp += 2) {
event_del(&events[i]);
close(cp[0]);
close(cp[1]);
}
free(pipes);
free(events);
return (&te);
}
int
main(int argc, char **argv)
{
#ifndef WIN32
struct rlimit rl;
#endif
int i, c;
struct timeval *tv;
int num_pipes = 100;
while ((c = getopt(argc, argv, "n:")) != -1) {
switch (c) {
case 'n':
num_pipes = atoi(optarg);
break;
default:
fprintf(stderr, "Illegal argument \"%c\"\n", c);
exit(1);
}
}
#ifndef WIN32
rl.rlim_cur = rl.rlim_max = num_pipes * 2 + 50;
if (setrlimit(RLIMIT_NOFILE, &rl) == -1) {
perror("setrlimit");
exit(1);
}
#endif
event_init();
for (i = 0; i < 25; i++) {
tv = run_once(num_pipes);
if (tv == NULL)
exit(1);
fprintf(stdout, "%ld\n",
tv->tv_sec * 1000000L + tv->tv_usec);
}
exit(0);
}
|
the_stack_data/34511498.c | /*
Copyright 2021 Lo Mele Vittorio / Loris Lurdo
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
ESERCIZIO n.16 - Letti due interi n/k>0 stampa il risultato della
sommatoria k + k^2 + k^n...
15/03/2022 (Esercitazione in laboratorio)
*/
#include <stdio.h>
int main(void)
{
int n = 0, k = 0, mult = 1, pot;
do
{
printf("Inserisci n: ");
scanf("%d", &n);
} while (n <= 0);
do
{
printf("Inserisci k: ");
scanf("%d", &k);
} while (k <= 0);
pot = 0;
for (int i = 1; i < (n + 1); i++)
{
mult = mult * k;
pot = pot + mult;
}
printf("Il risultato è %d \n", pot);
} |
the_stack_data/57951519.c | /* mbino - basic mbed APIs for the Arduino platform
* Copyright (c) 2017, 2018 Thomas Kemmer
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifdef ARDUINO_ARCH_AVR
#include <Arduino.h>
#include "hal/gpio_api.h"
#include "avr_timers.h"
static void gpio_dir_in(gpio_t *obj)
{
volatile uint8_t *mode = portModeRegister(obj->port);
volatile uint8_t *input = portInputRegister(obj->port);
volatile uint8_t *output = portOutputRegister(obj->port);
obj->dir = PIN_INPUT;
// save value if currently set as output
if (*mode & obj->mask) {
obj->value = (*output & obj->mask) ? 1 : 0;
}
obj->reg = input;
uint8_t sreg = SREG;
cli();
*mode &= ~obj->mask;
if (obj->mode == PullUp) {
*output |= obj->mask;
} else {
*output &= obj->mask;
}
SREG = sreg;
}
static void gpio_dir_out(gpio_t *obj)
{
volatile uint8_t *mode = portModeRegister(obj->port);
volatile uint8_t *output = portOutputRegister(obj->port);
obj->dir = PIN_OUTPUT;
// save mode if currently set as input
if (!(*mode & obj->mask)) {
obj->mode = (*output & obj->mask) ? PullUp : PullNone;
}
obj->reg = output;
uint8_t sreg = SREG;
cli();
if (obj->value) {
*output |= obj->mask;
} else {
*output &= ~obj->mask;
}
*mode |= obj->mask;
SREG = sreg;
}
uint32_t gpio_set(PinName pin)
{
// disable PWM for this pin
uint8_t timer = digitalPinToTimer(pin);
if (timer != NOT_ON_TIMER) {
volatile uint8_t *tccr = timerToControlRegister(timer);
uint8_t com = timerToCompareOutputModeMask(timer);
uint8_t sreg = SREG;
cli();
*tccr &= ~com;
SREG = sreg;
}
return digitalPinToBitMask(pin);
}
void gpio_init(gpio_t *obj, PinName pin)
{
static uint8_t ncreg = 0; // dummy register
if (pin != NC) {
obj->port = digitalPinToPort(pin);
obj->mask = gpio_set(pin);
if (*portModeRegister(obj->port) & obj->mask) {
obj->reg = portOutputRegister(obj->port);
obj->dir = PIN_OUTPUT;
} else {
obj->reg = portInputRegister(obj->port);
obj->dir = PIN_INPUT;
}
obj->mode = PullDefault;
obj->value = 0;
} else {
obj->reg = &ncreg;
obj->port = 0;
obj->mask = 0;
}
}
void gpio_mode(gpio_t *obj, PinMode mode)
{
// driver code locks this
if (gpio_is_connected(obj)) {
if (obj->dir == PIN_INPUT) {
volatile uint8_t *output = portOutputRegister(obj->port);
uint8_t sreg = SREG;
cli();
if (mode == PullUp) {
*output |= obj->mask;
} else {
*output &= obj->mask;
}
SREG = sreg;
} else {
obj->mode = mode;
}
}
}
void gpio_dir(gpio_t *obj, PinDirection direction)
{
// driver code locks this
if (gpio_is_connected(obj)) {
if (direction == PIN_INPUT) {
gpio_dir_in(obj);
} else {
gpio_dir_out(obj);
}
}
}
void gpio_write(gpio_t *obj, int value)
{
// driver code assumes gpio_write() is thread- and interrupt-safe
uint8_t sreg = SREG;
cli();
if (obj->dir == PIN_OUTPUT) {
if (value) {
*obj->reg |= obj->mask;
} else {
*obj->reg &= ~obj->mask;
}
} else {
obj->value = value ? 1 : 0;
}
SREG = sreg;
}
#endif
|
the_stack_data/29824163.c | /*
* Copyright (C) 2017 The LineageOS Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
static const char* process_name = "unknown";
const char* get_process_name(void) {
return process_name;
}
|
the_stack_data/3436.c | # include <unistd.h>
# include <stdlib.h>
int main() {
while(1) fork();
exit(0);
}
|
the_stack_data/34513880.c | /* Example code for Exercises in C.
Based on an example from http://www.learn-c.org/en/Linked_lists
Copyright 2016 Allen Downey
License: Creative Commons Attribution-ShareAlike 3.0
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int val;
struct node *next;
} Node;
/* Makes a new node structure.
*
* val: value to store in the node.
* next: pointer to the next node
*
* returns: pointer to a new node
*/
Node *make_node(int val, Node *next) {
Node *node = malloc(sizeof(Node));
node->val = val;
node->next = next;
return node;
}
/* Prints the values in a list.
*
* list: pointer to pointer to Node
*/
void print_list(Node **list) {
Node *current = *list;
printf("[ ");
while (current != NULL) {
printf("%d ", current->val);
current = current->next;
}
printf("]\n");
}
/* Removes and returns the first element of a list.
*
* list: pointer to pointer to Node
*
* returns: int or -1 if the list is empty
*/
int pop(Node **list) {
// FILL THIS IN!
return 0;
}
/* Adds a new element to the beginning of the list.
*
* list: pointer to pointer to Node
* val: value to add
*/
void push(Node** list, int val) {
struct node* new_el = (struct Node*) malloc(sizeof(struct node));
new_el->val = val;
new_el->next = (*list);
(*list) = new_el;
}
/* Removes the first element with the given value
*
* Frees the removed node.
*
* list: pointer to pointer to Node
* val: value to remove
*
* returns: number of nodes removed
*/
int remove_by_value(Node **list, int val) {
Node *current = *list;
Node *previous = current;
while (current != NULL){
current = previous ->next;
if (previous -> val == val){
if (previous==*list){
*list = current;
return 1;
}
}
if (current !=NULL && current->val ==val){
previous ->next = current->next;
return 1;
}
previous = current;
}
return 0;
}
/* Reverses the elements of the list.
*
* Does not allocate or free nodes.
*
* list: pointer to pointer to Node
*/
void reverse(Node **list) {
Node* previous = NULL;
Node* current = *list;
Node* next = NULL;
while (current != NULL)
{
next = current->next;
current->next =previous;// reverse the current node's pointer
previous = current; //move pointer position
current = next;
}
*list = previous;
}
int main() {
Node *head = make_node(1, NULL);
head->next = make_node(2, NULL);
head->next->next = make_node(3, NULL);
head->next->next->next = make_node(4, NULL);
Node **list = &head;
print_list(list);
int retval = pop(list);
print_list(list);
push(list, retval+10);
print_list(list);
remove_by_value(list, 3);
print_list(list);
remove_by_value(list, 7);
print_list(list);
reverse(list);
print_list(list);
}
|
the_stack_data/12638189.c | #include <stdio.h>
#include <stdlib.h>
main()
{
int r,c,j;
printf("Give Row and Column Values\n");
scanf("%d%d",&r,&c);
int *a = (int *)malloc(r*c*(sizeof(int)));
int i;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",(a+i*c+j));
}
}
printf("\n\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d ",*(a+i*c+j));
}
printf("\n");
}
}
|
the_stack_data/153080.c | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifdef ENABLE_AVX
#include <x86intrin.h>
#include "nnacl/fp32/conv_depthwise_fp32.h"
void ConvDwFp32Avx5x5(float *output, float **input, const float *weights, const float *bias, size_t channels,
size_t output_width, size_t input_stride, size_t relu, size_t relu6) {
input_stride /= sizeof(float *);
size_t c8 = UP_DIV(channels, C8NUM) * C8NUM;
size_t c8_mod = channels % C8NUM;
int kernel = 25;
for (int i = 0; i < output_width; ++i) {
float *in[kernel];
for (int k = 0; k < kernel; k++) {
in[k] = input[k];
}
input += input_stride;
size_t c = c8;
const float *w = weights;
const float *bias1 = bias;
for (; c >= C8NUM; c -= C8NUM) {
__m256 out1 = _mm256_loadu_ps(bias1);
bias1 += 8;
for (int k = 0; k < kernel; k += 5) {
__m256 in1 = _mm256_loadu_ps(in[k]);
__m256 w1 = _mm256_loadu_ps(w);
__m256 in2 = _mm256_loadu_ps(in[k + 1]);
__m256 w2 = _mm256_loadu_ps(w + 8);
out1 = _mm256_fmadd_ps(in1, w1, out1);
__m256 in3 = _mm256_loadu_ps(in[k + 2]);
__m256 w3 = _mm256_loadu_ps(w + 16);
out1 = _mm256_fmadd_ps(in2, w2, out1);
__m256 in4 = _mm256_loadu_ps(in[k + 3]);
__m256 w4 = _mm256_loadu_ps(w + 24);
out1 = _mm256_fmadd_ps(in3, w3, out1);
__m256 in5 = _mm256_loadu_ps(in[k + 4]);
__m256 w5 = _mm256_loadu_ps(w + 32);
out1 = _mm256_fmadd_ps(in4, w4, out1);
w += 40;
in[k] += C8NUM;
in[k + 1] += C8NUM;
in[k + 2] += C8NUM;
in[k + 3] += C8NUM;
in[k + 4] += C8NUM;
out1 = _mm256_fmadd_ps(in5, w5, out1);
}
if (relu6 != 0) {
__m256 relu6_data = _mm256_set1_ps(6.0);
out1 = _mm256_min_ps(out1, relu6_data);
}
if (relu != 0 || relu6 != 0) {
__m256 zero = _mm256_setzero_ps();
out1 = _mm256_max_ps(out1, zero);
}
if (c > C8NUM || c8_mod == 0) {
_mm256_storeu_ps(output, out1);
output += C8NUM;
} else {
__m128 tmp;
switch (c8_mod) {
case 1:
_mm_store_ss(output, _mm256_castps256_ps128(out1));
break;
case 2:
_mm_storel_pi((__m64 *)output, _mm256_castps256_ps128(out1));
break;
case 3:
tmp = _mm256_castps256_ps128(out1);
_mm_storel_pi((__m64 *)output, tmp);
tmp = _mm_unpackhi_ps(tmp, tmp);
_mm_store_ss(output + 2, tmp);
break;
case 4:
_mm_storeu_ps(output, _mm256_castps256_ps128(out1));
break;
case 5:
_mm_storeu_ps(output, _mm256_castps256_ps128(out1));
_mm_store_ss(output + 4, _mm256_extractf128_ps(out1, 1));
break;
case 6:
_mm_storeu_ps(output, _mm256_castps256_ps128(out1));
_mm_storel_pi((__m64 *)(output + 4), _mm256_extractf128_ps(out1, 1));
break;
case 7:
_mm_storeu_ps(output, _mm256_castps256_ps128(out1));
tmp = _mm256_extractf128_ps(out1, 1);
_mm_storel_pi((__m64 *)(output + 4), tmp);
tmp = _mm_unpackhi_ps(tmp, tmp);
_mm_store_ss(output + 6, tmp);
break;
default:
_mm256_storeu_ps(output, out1);
break;
}
output += c8_mod;
}
}
}
}
#endif
|
the_stack_data/1003462.c | #include<stdio.h>
int main()
{
float val, ans;
char temp;
scanf("%c", &temp);
scanf("%f", &val);
fflush(stdin);
if(temp == 'F' || temp == 'f')
{
ans=(val-32)*5/9;
printf("%f \n", ans);
}
else if(temp == 'C' || temp == 'c')
{
ans=(val*9/5) + 32;
printf("%f \n", ans);
}
else
printf("wrong input\n");
return 0;
}
|
the_stack_data/54824069.c | /*1.1. Write a program to input a floating number and show that number with two decimal points*/
#include<stdio.h>
int main(){
float a;
printf("Enter a float number : ");
scanf("%f",&a);
printf("Float number with two decimal points is =%.2f",a);
}
/*
OUTPUT
Enter a float number : 45.567576
Float number with two decimal points is =45.57*/
|
the_stack_data/57950691.c | // BFS algorithm in C
#include <stdio.h>
#include <stdlib.h>
#define SIZE 40
struct queue {
int items[SIZE];
int front;
int rear;
};
struct queue* createQueue();
void enqueue(struct queue* q, int);
int dequeue(struct queue* q);
void display(struct queue* q);
int isEmpty(struct queue* q);
void printQueue(struct queue* q);
struct node {
int vertex;
struct node* next;
};
struct node* createNode(int);
struct Graph {
int numVertices;
struct node** adjLists;
int* visited;
};
// BFS algorithm
void bfs(struct Graph* graph, int startVertex) {
struct queue* q = createQueue();
graph->visited[startVertex] = 1;
enqueue(q, startVertex);
while (!isEmpty(q)) {
printQueue(q);
int currentVertex = dequeue(q);
printf("Visited %d\n", currentVertex);
struct node* temp = graph->adjLists[currentVertex];
while (temp) {
int adjVertex = temp->vertex;
if (graph->visited[adjVertex] == 0) {
graph->visited[adjVertex] = 1;
enqueue(q, adjVertex);
}
temp = temp->next;
}
}
}
// Creating a node
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
// Creating a graph
struct Graph* createGraph(int vertices) {
struct Graph* graph = malloc(sizeof(struct Graph));
graph->numVertices = vertices;
graph->adjLists = malloc(vertices * sizeof(struct node*));
graph->visited = malloc(vertices * sizeof(int));
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
// Add edge
void addEdge(struct Graph* graph, int src, int dest) {
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
// Add edge from dest to src
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
// Create a queue
struct queue* createQueue() {
struct queue* q = malloc(sizeof(struct queue));
q->front = -1;
q->rear = -1;
return q;
}
// Check if the queue is empty
int isEmpty(struct queue* q) {
if (q->rear == -1)
return 1;
else
return 0;
}
// Adding elements into queue
void enqueue(struct queue* q, int value) {
if (q->rear == SIZE - 1)
printf("\nQueue is Full!!");
else {
if (q->front == -1)
q->front = 0;
q->rear++;
q->items[q->rear] = value;
}
}
// Removing elements from queue
int dequeue(struct queue* q) {
int item;
if (isEmpty(q)) {
printf("Queue is empty");
item = -1;
} else {
item = q->items[q->front];
q->front++;
if (q->front > q->rear) {
printf("Resetting queue ");
q->front = q->rear = -1;
}
}
return item;
}
// Print the queue
void printQueue(struct queue* q) {
int i = q->front;
if (isEmpty(q)) {
printf("Queue is empty");
} else {
printf("\nQueue contains \n");
for (i = q->front; i < q->rear + 1; i++) {
printf("%d ", q->items[i]);
}
}
}
int main() {
struct Graph* graph = createGraph(6);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 1, 4);
addEdge(graph, 1, 3);
addEdge(graph, 2, 4);
addEdge(graph, 3, 4);
bfs(graph, 0);
return 0;
} |
the_stack_data/1264176.c | /***
* This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License.
* When used, please cite the following article(s): V. Mrazek, R. Hrbacek, Z. Vasicek and L. Sekanina, "EvoApprox8b: Library of approximate adders and multipliers for circuit design and benchmarking of approximation methods". Design, Automation & Test in Europe Conference & Exhibition (DATE), 2017, Lausanne, 2017, pp. 258-261. doi: 10.23919/DATE.2017.7926993
* This file contains a circuit from evoapprox8b dataset. Note that a new version of library was already published.
***/
#include <stdint.h>
#include <stdlib.h>
/// Approximate function mul8_151
/// Library = EvoApprox8b
/// Circuit = mul8_151
/// Area (180) = 4890
/// Delay (180) = 2.300
/// Power (180) = 1636.20
/// Area (45) = 365
/// Delay (45) = 0.880
/// Power (45) = 138.80
/// Nodes = 100
/// HD = 383030
/// MAE = 618.04355
/// MSE = 665184.27148
/// MRE = 9.82 %
/// WCE = 2811
/// WCRE = 606 %
/// EP = 99.1 %
uint16_t mul8_151(uint8_t a, uint8_t b)
{
uint16_t c = 0;
uint8_t n2 = (a >> 1) & 0x1;
uint8_t n4 = (a >> 2) & 0x1;
uint8_t n6 = (a >> 3) & 0x1;
uint8_t n8 = (a >> 4) & 0x1;
uint8_t n10 = (a >> 5) & 0x1;
uint8_t n12 = (a >> 6) & 0x1;
uint8_t n14 = (a >> 7) & 0x1;
uint8_t n16 = (b >> 0) & 0x1;
uint8_t n18 = (b >> 1) & 0x1;
uint8_t n20 = (b >> 2) & 0x1;
uint8_t n22 = (b >> 3) & 0x1;
uint8_t n24 = (b >> 4) & 0x1;
uint8_t n26 = (b >> 5) & 0x1;
uint8_t n28 = (b >> 6) & 0x1;
uint8_t n30 = (b >> 7) & 0x1;
uint8_t n32;
uint8_t n35;
uint8_t n41;
uint8_t n42;
uint8_t n49;
uint8_t n51;
uint8_t n53;
uint8_t n61;
uint8_t n65;
uint8_t n67;
uint8_t n68;
uint8_t n69;
uint8_t n70;
uint8_t n76;
uint8_t n78;
uint8_t n82;
uint8_t n87;
uint8_t n91;
uint8_t n118;
uint8_t n120;
uint8_t n121;
uint8_t n157;
uint8_t n190;
uint8_t n258;
uint8_t n261;
uint8_t n301;
uint8_t n306;
uint8_t n325;
uint8_t n386;
uint8_t n420;
uint8_t n433;
uint8_t n460;
uint8_t n476;
uint8_t n481;
uint8_t n482;
uint8_t n484;
uint8_t n491;
uint8_t n532;
uint8_t n580;
uint8_t n595;
uint8_t n608;
uint8_t n665;
uint8_t n698;
uint8_t n712;
uint8_t n728;
uint8_t n802;
uint8_t n816;
uint8_t n817;
uint8_t n832;
uint8_t n846;
uint8_t n854;
uint8_t n891;
uint8_t n906;
uint8_t n920;
uint8_t n921;
uint8_t n934;
uint8_t n950;
uint8_t n965;
uint8_t n1054;
uint8_t n1069;
uint8_t n1107;
uint8_t n1142;
uint8_t n1143;
uint8_t n1172;
uint8_t n1186;
uint8_t n1187;
uint8_t n1202;
uint8_t n1203;
uint8_t n1216;
uint8_t n1232;
uint8_t n1307;
uint8_t n1334;
uint8_t n1335;
uint8_t n1350;
uint8_t n1351;
uint8_t n1424;
uint8_t n1425;
uint8_t n1438;
uint8_t n1439;
uint8_t n1454;
uint8_t n1455;
uint8_t n1468;
uint8_t n1482;
uint8_t n1483;
uint8_t n1572;
uint8_t n1586;
uint8_t n1587;
uint8_t n1602;
uint8_t n1603;
uint8_t n1616;
uint8_t n1632;
uint8_t n1646;
uint8_t n1660;
uint8_t n1678;
uint8_t n1706;
uint8_t n1712;
uint8_t n1720;
uint8_t n1734;
uint8_t n1750;
uint8_t n1764;
uint8_t n1765;
uint8_t n1780;
uint8_t n1781;
uint8_t n1794;
uint8_t n1795;
uint8_t n1808;
uint8_t n1809;
uint8_t n1824;
uint8_t n1838;
uint8_t n1869;
uint8_t n1882;
uint8_t n1898;
uint8_t n1912;
uint8_t n1928;
uint8_t n1942;
uint8_t n1943;
uint8_t n1956;
uint8_t n1957;
uint8_t n1972;
uint8_t n1973;
uint8_t n1986;
uint8_t n1987;
uint8_t n2016;
n32 = n18 & n12;
n35 = (n14 & n16) | (n16 & n30) | (n14 & n30);
n41 = ~(n12 ^ n12);
n42 = ~(n6 & n28);
n49 = ~((n18 & n14) | n32);
n51 = (n41 & n4) | (n4 & n2) | (n41 & n2);
n53 = ~((n12 | n51) & n30);
n61 = ~(n12 & n28 & n14);
n65 = n41;
n67 = n65;
n68 = ~(n65 | n4 | n67);
n69 = ~(n65 | n4 | n67);
n70 = ~n69;
n76 = ~(n65 & n70);
n78 = n69;
n82 = ~(n6 | n4 | n14);
n87 = n22 | n24;
n91 = ~(n87 | n28 | n35);
n118 = n91 & n20;
n120 = n12 & n118;
n121 = n12 & n118;
n157 = ~((n53 & n82) | n91);
n190 = ~((n69 | n76) & n30);
n258 = n51 & n28;
n261 = ~n61;
n301 = n69;
n306 = n22 | n20;
n325 = n301 | n42;
n386 = n6 | n8;
n420 = n26 & n386;
n433 = ~n41;
n460 = n10 & n306;
n476 = n12 & n22;
n481 = n41;
n482 = ~n53;
n484 = ~n49;
n491 = n14 & n22;
n532 = ~n325;
n580 = n10 & n24;
n595 = n12 & n24;
n608 = n14 & n24;
n665 = n433 ^ n78;
n698 = n10 & n26;
n712 = n12 & n26;
n728 = n14 & n26;
n802 = n8 & n28;
n816 = n10 & n28;
n817 = n10 & n28;
n832 = n12 & n28;
n846 = n14 & n28;
n854 = n595;
n891 = n4 & n30;
n906 = n6 & n30;
n920 = n8 & n30;
n921 = n8 & n30;
n934 = n10 & n30;
n950 = n12 & n30;
n965 = n14 & n30;
n1054 = n120;
n1069 = ~n481;
n1107 = n491;
n1142 = n157;
n1143 = n157;
n1172 = n460;
n1186 = n476 ^ n580;
n1187 = n476 & n580;
n1202 = (n1107 ^ n854) ^ n698;
n1203 = (n1107 & n854) | (n854 & n698) | (n1107 & n698);
n1216 = n608 & n712;
n1232 = n608 ^ n712;
n1307 = n157 | n1054;
n1334 = (n817 ^ n1069) ^ n1172;
n1335 = (n817 & n1069) | (n1069 & n1172) | (n817 & n1172);
n1350 = (n891 ^ n420) ^ n1186;
n1351 = (n891 & n420) | (n420 & n1186) | (n891 & n1186);
n1424 = (n1187 ^ n802) ^ n906;
n1425 = (n1187 & n802) | (n802 & n906) | (n1187 & n906);
n1438 = (n1203 ^ n816) ^ n920;
n1439 = (n1203 & n816) | (n816 & n920) | (n1203 & n920);
n1454 = (n1216 ^ n832) ^ n934;
n1455 = (n1216 & n832) | (n832 & n934) | (n1216 & n934);
n1468 = n261 & n482;
n1482 = n846 ^ n950;
n1483 = n846 & n950;
n1572 = n1334;
n1586 = n1350 ^ n1335;
n1587 = n1350 & n1335;
n1602 = (n1202 ^ n1216) ^ n1424;
n1603 = (n1202 & n1216) | (n1216 & n1424) | (n1202 & n1424);
n1616 = n1232 & n1438;
n1632 = n1232 | n1438;
n1646 = n728 & n1454;
n1660 = n728 ^ n1454;
n1678 = n1483;
n1706 = (n921 ^ n68) ^ n665;
n1712 = n921;
n1720 = (n1307 & n190) | (~n1307 & n1425);
n1734 = n1572 | n484;
n1750 = n1586 | n532;
n1764 = (n1602 ^ n1587) ^ n1351;
n1765 = (n1602 & n1587) | (n1587 & n1351) | (n1602 & n1351);
n1780 = (n1632 ^ n1603) ^ n1425;
n1781 = (n1632 & n1603) | (n1603 & n1425) | (n1632 & n1425);
n1794 = (n1660 ^ n1616) ^ n1439;
n1795 = (n1660 & n1616) | (n1616 & n1439) | (n1660 & n1439);
n1808 = (n1482 ^ n1646) ^ n1455;
n1809 = (n1482 & n1646) | (n1646 & n1455) | (n1482 & n1455);
n1824 = n41 & n1468;
n1838 = n965 ^ n1678;
n1869 = n1706;
n1882 = n1720;
n1898 = n1734 | n258;
n1912 = n1750;
n1928 = n1764;
n1942 = n1780 ^ n1765;
n1943 = n1780 & n1765;
n1956 = (n1794 ^ n1781) ^ n1943;
n1957 = (n1794 & n1781) | (n1781 & n1943) | (n1794 & n1943);
n1972 = (n1808 ^ n1795) ^ n1957;
n1973 = (n1808 & n1795) | (n1795 & n1957) | (n1808 & n1957);
n1986 = (n1838 ^ n1809) ^ n1973;
n1987 = (n1838 & n1809) | (n1809 & n1973) | (n1838 & n1973);
n2016 = n1824 | n1987;
c |= (n121 & 0x1) << 0;
c |= (n1142 & 0x1) << 1;
c |= (n1603 & 0x1) << 2;
c |= (n1712 & 0x1) << 3;
c |= (n1869 & 0x1) << 4;
c |= (n1882 & 0x1) << 5;
c |= (n1143 & 0x1) << 6;
c |= (n1882 & 0x1) << 7;
c |= (n1898 & 0x1) << 8;
c |= (n1912 & 0x1) << 9;
c |= (n1928 & 0x1) << 10;
c |= (n1942 & 0x1) << 11;
c |= (n1956 & 0x1) << 12;
c |= (n1972 & 0x1) << 13;
c |= (n1986 & 0x1) << 14;
c |= (n2016 & 0x1) << 15;
return c;
}
|
the_stack_data/152308.c | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_swap.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ebouvier <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/03 13:39:27 by ebouvier #+# #+# */
/* Updated: 2018/04/04 12:28:04 by ebouvier ### ########.fr */
/* */
/* ************************************************************************** */
void ft_swap(int *a, int *b)
{
int tmp;
tmp = *b;
*b = *a;
*a = tmp;
}
|
the_stack_data/70450396.c | #include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <netdb.h>
#include <string.h>
void print_addrinfo(struct addrinfo* addr) {
if (addr->ai_family == AF_INET6) {
struct sockaddr_in6* saddr = (struct sockaddr_in6*)addr->ai_addr;
char ip_s[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &(saddr->sin6_addr), ip_s, INET6_ADDRSTRLEN);
printf("%s ", ip_s);
printf("%hu\n", ntohs(saddr->sin6_port));
} else if (addr->ai_family == AF_INET) {
struct sockaddr_in* saddr = (struct sockaddr_in*)addr->ai_addr;
char ip_s[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(saddr->sin_addr), ip_s, INET_ADDRSTRLEN);
printf("%s ", ip_s);
printf("%hu\n", ntohs(saddr->sin_port));
}
}
// print ipv6 from in6_addr
void print_in6_addr(struct in6_addr addr6){
char str[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &(addr6), str, INET6_ADDRSTRLEN);
if (strcmp(str,"::")){
printf("%s\n", str);
}
}
// print ipv4 from in_addr
void print_in_addr(struct in_addr addr){
char str[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(addr), str, INET_ADDRSTRLEN);
if (strcmp(str,"0.0.0.0")){
printf("%s\n", str);
}
} |
the_stack_data/14835.c | #include <stdio.h>
//resolver com crivo de aristofanes
int main()
{
int num;
scanf("%d",&num);
int primo = 0;
if (num < 2)
{
puts("Composto!");
primo = -1;
}
else if (num == 2) puts("Primo!");
else if ((num % 2) == 0) puts("Composto!");
else
{
int i;
for (i = 3; i <= (num / 2) + 1; i += 2)
{
if (num % i == 0)
{
puts("Composto!");
break;
}
}
if (i >= num / 2)
{
puts("Primo!");
primo = 1;
}
}
return 0;
}
|
the_stack_data/495955.c | // RUN: %clang_cc1 -fsyntax-only -verify -fms-compatibility -triple=i386-pc-win32 -Wformat-non-iso %s
int printf(const char *format, ...) __attribute__((format(printf, 1, 2)));
void signed_test() {
short val = 30;
printf("val = %I64d\n", val); // expected-warning{{'I64' length modifier is not supported by ISO C}} \
// expected-warning{{format specifies type '__int64' (aka 'long long') but the argument has type 'short'}}
long long bigval = 30;
printf("val = %I32d\n", bigval); // expected-warning{{'I32' length modifier is not supported by ISO C}} \
// expected-warning{{format specifies type '__int32' (aka 'int') but the argument has type 'long long'}}
printf("val = %Id\n", bigval); // expected-warning{{'I' length modifier is not supported by ISO C}} \
// expected-warning{{format specifies type '__int32' (aka 'int') but the argument has type 'long long'}}
}
void unsigned_test() {
unsigned short val = 30;
printf("val = %I64u\n", val); // expected-warning{{'I64' length modifier is not supported by ISO C}} \
// expected-warning{{format specifies type 'unsigned __int64' (aka 'unsigned long long') but the argument has type 'unsigned short'}}
unsigned long long bigval = 30;
printf("val = %I32u\n", bigval); // expected-warning{{'I32' length modifier is not supported by ISO C}} \
// expected-warning{{format specifies type 'unsigned __int32' (aka 'unsigned int') but the argument has type 'unsigned long long'}}
printf("val = %Iu\n", bigval); // expected-warning{{'I' length modifier is not supported by ISO C}} \
// expected-warning{{format specifies type 'unsigned __int32' (aka 'unsigned int') but the argument has type 'unsigned long long'}}
}
|
the_stack_data/50137015.c | #include <stdio.h>
int a[10001]={0,};
int n, n1,i, j, temp, min,k,cnt=0,sum1=0,sum2=0;
int main() {
scanf("%d", &n );
for(i=1 ; i<=n*n ; i++){
printf("%d ", i);
if(0 == i%n) puts("");
}
return 0;
}
|
the_stack_data/107952604.c | #include <stdio.h>
int main(){
int stateCode;
int chargeCode;
int pricePerKg;
int porcentTax;
float totalChargePrice;
float totalTaxValue;
float totalPrice;
float chargeWeightTon;
float chargeWeightKg;
printf("Please, insert the state code: ");
scanf("%d", &stateCode);
printf("\nPlease, insert the charge wight value (value in ton): ");
scanf("%f", &chargeWeightTon);
printf("\nPlease, insert the charge code: ");
scanf("%d", &chargeCode);
chargeWeightKg = (chargeWeightTon*1000);
if((chargeCode >= 10) && (chargeCode <= 20)){
pricePerKg = 100;
}else if((chargeCode >= 21) && (chargeCode <= 30)){
pricePerKg = 250;
}else if((chargeCode >= 31) && (chargeCode <= 40)){
pricePerKg = 340;
}else{
return 0;
}
switch (stateCode){
case 1:
porcentTax = 35;
break;
case 2:
porcentTax = 25;
break;
case 3:
porcentTax = 15;
break;
case 4:
porcentTax = 5;
break;
case 5:
porcentTax = 0;
break;
}
totalChargePrice = (pricePerKg*chargeWeightKg);
totalTaxValue = ((chargeWeightKg/100)*porcentTax);
totalPrice = totalChargePrice+totalTaxValue;
printf("\n ------------------------------- \n");
printf("The charge wieght in kg is: %.2f \n", chargeWeightKg);
printf("The charge price is: %.2f \n", totalChargePrice);
printf("The value tax is: %.2f \n", totalTaxValue);
printf("The total price of weight is: %.2f", totalPrice);
printf("\n ------------------------------- \n \n ");
}
|
the_stack_data/162643806.c | // Taken from the Polyhedral benchmark: https://web.cse.ohio-state.edu/~pouchet.2/software/polybench/
#pragma ACCEL kernel
void kernel_mvt(double x1[120], double x2[120], double y_1[120], double y_2[120], double A[120][120])
{
int i;
int j;
for (i = 0; i < 120; i++) {
for (j = 0; j < 120; j++) {
x1[i] += A[i][j] * y_1[j];
}
}
for (i = 0; i < 120; i++) {
for (j = 0; j < 120; j++) {
x2[i] += A[j][i] * y_2[j];
}
}
}
|
the_stack_data/125806.c | #include <stdio.h>
#include<stdlib.h>
#include <omp.h>
#define NUM_VALUES 20
int NUM_BUCKETS = 0;
int take_a_number(){
return rand()%NUM_BUCKETS;
}
int main() {
int i;
omp_set_dynamic(0);
NUM_BUCKETS = omp_get_num_procs();
omp_set_num_threads(NUM_BUCKETS);
printf("Buckets number = %d\n", NUM_BUCKETS);
omp_lock_t hist_locks[NUM_BUCKETS];
int hist[NUM_BUCKETS];
#pragma omp parallel for
for (i=0; i<NUM_BUCKETS; i++){
omp_init_lock(&hist_locks[i]);
hist[i] = 0;
}
#pragma omp parallel for
for (i=0; i<NUM_VALUES; i++){
int id = omp_get_thread_num();
printf("Thread %d\n", id);
int val = take_a_number();
omp_set_lock(&hist_locks[id]);
hist[val]++;
omp_unset_lock(&hist_locks[id]);
}
for (i=0; i<NUM_BUCKETS; i++){
printf("hist[%d] = %d\n", i, hist[i]);
omp_destroy_lock(&hist_locks[i]);
}
}
|
the_stack_data/73574926.c | #include <stdio.h>
int main(void)
{
int i; // signed integer
i = 2;
printf("Hello, World!\n");
return 0;
}
|
the_stack_data/858298.c | #include <stdio.h>
int main(void)
{
int radius;
float volume;
printf("Provide the radius of the sphere in meters: ");
scanf("%d", &radius);
volume = (4.0f / 3.0f) * 3.141592 * (radius * radius * radius);
printf("The volume of a shpere with a %d-meter radius is: %f", radius, volume);
return 0;
} |
the_stack_data/104827374.c | #ifdef STM32F4xx
#include "stm32f4xx_hal_qspi.c"
#endif
#ifdef STM32F7xx
#include "stm32f7xx_hal_qspi.c"
#endif
#ifdef STM32L4xx
#include "stm32l4xx_hal_qspi.c"
#endif
|
the_stack_data/92327864.c | #include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
if ((strcmp(argv[1], "-h") == 0) || (strcmp(argv[1], "--help") == 0)) {
printf("cat [FILE]...\n- to read stdin\n");
} else if (strcmp(argv[1],"-") == 0) {
char ch;
while ((ch = getc(stdin)) != EOF) {
putc(ch, stdout);
}
} else {
int i;
for (i = 1; i < argc; i++) {
FILE *fp;
char ch;
fp = fopen(argv[i], "r");
if (fp) {
while ((ch = getc(fp)) != EOF) {
putc(ch, stdout);
}
fclose(fp);
}
}
}
}
|
the_stack_data/73576475.c | #include <stddef.h>
#include <stdarg.h>
#define SIGN 1
typedef unsigned long long int uint64;
typedef unsigned int uint32;
typedef unsigned short uint16;
typedef unsigned char uint8;
typedef long long int int64;
typedef int int32;
typedef short int16;
typedef char int8;
#define SYS_GETPID 0
#define SYS_UART_RECV 1
#define SYS_UART_WRITE 2
#define SYS_EXEC 3
#define SYS_FORK 4
#define SYS_EXIT 5
#define SYS_MBOX_CALL 6
#define SYS_KILL_PID 7
int start(void) __attribute__((section(".start")));
uint64 syscall(uint64 syscall_num,
void *x0,
void *x1,
void *x2,
void *x3,
void *x4,
void *x5)
{
uint64 result;
asm volatile (
"ldr x8, %0\n"
"ldr x0, %1\n"
"ldr x1, %2\n"
"ldr x2, %3\n"
"ldr x3, %4\n"
"ldr x4, %5\n"
"ldr x5, %6\n"
"svc 0\n"
:: "m" (syscall_num), "m" (x0), "m" (x1),
"m" (x2), "m" (x3), "m" (x4), "m" (x5)
);
asm volatile (
"str x0, %0\n"
: "=m" (result)
);
return result;
}
int getpid()
{
return (int)syscall(SYS_GETPID, 0, 0, 0, 0, 0, 0);
}
void uart_recv(const char buf[], size_t size)
{
syscall(SYS_UART_RECV, (void *)buf, (void *)size, 0, 0, 0, 0);
}
void uart_write(const char buf[], size_t size)
{
syscall(SYS_UART_WRITE, (void *)buf, (void *)size, 0, 0, 0, 0);
}
static void uart_send_char(char c)
{
uart_write(&c, 1);
}
static void uart_send_string(const char *str)
{
for (int i = 0; str[i] != '\0'; i++) {
uart_send_char(str[i]);
}
}
static void uart_send_num(int64 num, int base, int type)
{
static const char digits[16] = "0123456789ABCDEF";
char tmp[66];
int i;
if (type | SIGN) {
if (num < 0) {
uart_send_char('-');
}
}
i = 0;
if (num == 0) {
tmp[i++] = '0';
} else {
while (num != 0) {
uint8 r = (uint32)num % base;
num = (uint32)num / base;
tmp[i++] = digits[r];
}
}
while (--i >= 0) {
uart_send_char(tmp[i]);
}
}
static void _uart_printf(const char *fmt, va_list args)
{
const char *s;
char c;
uint64 num;
char width;
for (; *fmt; ++fmt) {
if (*fmt != '%') {
uart_send_char(*fmt);
continue;
}
++fmt;
// Get width
width = 0;
if (fmt[0] == 'l' && fmt[1] == 'l') {
width = 1;
fmt += 2;
}
switch (*fmt) {
case 'c':
c = va_arg(args, uint32) & 0xff;
uart_send_char(c);
continue;
case 'd':
if (width) {
num = va_arg(args, int64);
} else {
num = va_arg(args, int32);
}
uart_send_num(num, 10, SIGN);
continue;
case 's':
s = va_arg(args, char *);
uart_send_string(s);
continue;
case 'x':
if (width) {
num = va_arg(args, uint64);
} else {
num = va_arg(args, uint32);
}
uart_send_num(num, 16, 0);
continue;
}
}
}
void uart_printf(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
_uart_printf(fmt, args);
va_end(args);
}
void exec(const char *name, char *const argv[])
{
syscall(SYS_EXEC, (void *)name, (void *)argv, 0, 0, 0, 0);
}
int fork(void)
{
return (int)syscall(SYS_FORK, 0, 0, 0, 0, 0, 0);
}
void exit(void)
{
syscall(SYS_EXIT, 0, 0, 0, 0, 0, 0);
}
void mbox_call(unsigned char ch, unsigned int *mbox)
{
syscall(SYS_MBOX_CALL, (void *)(uint64)ch, mbox, 0, 0, 0, 0);
}
void kill_pid(int pid)
{
syscall(SYS_KILL_PID, (void *)(uint64)pid, 0, 0, 0, 0, 0);
}
/* Channels */
#define MAILBOX_CH_PROP 8
/* Tags */
#define TAG_REQUEST_CODE 0x00000000
#define END_TAG 0x00000000
/* Tag identifier */
#define GET_BOARD_REVISION 0x00010002
/* Others */
#define REQUEST_CODE 0x00000000
static unsigned int __attribute__((aligned(0x10))) mailbox[16];
// It should be 0xa020d3 for rpi3 b+
unsigned int get_board_revision(void)
{
mailbox[0] = 7 * 4; // Buffer size in bytes
mailbox[1] = REQUEST_CODE;
// Tags begin
mailbox[2] = GET_BOARD_REVISION; // Tag identifier
mailbox[3] = 4; // Value buffer size in bytes
mailbox[4] = TAG_REQUEST_CODE; // Request/response codes
mailbox[5] = 0; // Optional value buffer
// Tags end
mailbox[6] = END_TAG;
mbox_call(MAILBOX_CH_PROP, mailbox); // Message passing procedure call
return mailbox[5];
}
void show_stack(void)
{
uint64 sp;
asm volatile (
"mov x9, sp\n"
"str x9, %0\n"
: "=m" (sp)
);
uart_printf("[User] Stack: %llx\r\n", sp);
}
int start(void)
{
char buf1[0x10] = { 0 };
int pid, revision;
pid = getpid();
uart_printf("[User] pid: %d\r\n", pid);
uart_printf("[User] kill_pid(2)\r\n");
kill_pid(2);
uart_printf("[User] Input:\r\n");
uart_recv(buf1, 8);
uart_printf("[User] Output: %s\r\n", buf1);
revision = get_board_revision();
uart_printf("[User] Revision: %x\r\n", revision);
pid = fork();
if (pid == 0) {
uart_printf("[User] Child: exec userprog1\r\n");
show_stack();
exec("userprog1", NULL);
} else {
uart_printf("[User] Parent: child pid: %d\r\n", pid);
show_stack();
}
uart_printf("[User] Exit\r\n");
exit();
return 0;
} |
the_stack_data/148579182.c | #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <time.h>
#include <sys/wait.h>
int run = 1;
pid_t cpid;
int signal_to_handle;
void child_signal_handler(int sig) {
printf("[child] Signal[%d] recieved to pid: [%d]\n", sig, getpid());
run = 0;
}
void parent_signal_handler(int sig) {
kill(cpid, signal_to_handle);
printf("[parent] Signal[%d] recieved to pid: [%d]\n", sig, getpid());
}
int main(int argc, char** argv) {
if( argc != 2 ){
fprintf(stderr, "I need args!\n");
return EXIT_FAILURE;
}
signal_to_handle = atoi(argv[1]);
cpid = fork();
if(cpid < 0) {
perror("error");
exit(EXIT_FAILURE);
}
if(cpid == 0){
signal(signal_to_handle, child_signal_handler);
while(run) {
printf("Epoch time: %lu\n", (unsigned long) time(NULL));
sleep(1);
}
for(int i = 0 ; i < 50 ; i++) {
printf("ppid: %d\n", getppid());
sleep(1);
}
printf("Child exits!\n");
exit(EXIT_SUCCESS);
}
signal(SIGINT, parent_signal_handler);
wait(NULL);
printf("Parent exits!\n");
return 0;
}
|
the_stack_data/100213.c | //You just DO WHAT THE FUCK YOU WANT TO.
#include<X11/Xlib.h>
#define V e.xbutton
int main(){Display*d;XEvent e;Window w,p=GrabModeAsync;if(d=XOpenDisplay(0)){XGrabButton(d,1,Mod1Mask,XRootWindow(d,0),1,ButtonPressMask,p,p,0,0);for(;;){XNextEvent(d,&e);if(w=V.subwindow){XWindowAttributes a;XGetWindowAttributes(d,w,&a);XMoveWindow(d,w,V.x-a.width/2,V.y-a.height/2);}}}} |
the_stack_data/190769281.c | #include"stdio.h"
#include"unistd.h"
void main()
{
printf("PID : %d\n",(long)getpid());
printf("PPID : %d\n",(long)getppid());
while(1){};
}
|
the_stack_data/127555.c | #include <stdio.h>
int main()
{
char str = getchar();
while ( str != '\n' )
{
if ( str >= 'A' && str <= 'Z' )
printf( "%02d", str-'A'+1 );
else if ( str >= 'a' && str <= 'z' )
printf( "%02d", 'a'-str+52 );
else if ( str >= '0' && str <= '9' )
printf( "%02d", str-'0'+90 );
else if ( str == ' ' )
printf( "#" );
else
printf( "*" );
str = getchar();
}
return 0;
}
|
the_stack_data/234517682.c |
//Reference: https://www.bbsmax.com/A/D854VAPvzE/
//Reference: https:www.binarytides.com/hostname-to-ip-address-c-sockets-linux/
#include <stdio.h> //printf
#include <stdlib.h> //exit
#include <string.h> //memset
#include <signal.h> //gettimeofday
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <netdb.h>
#include <setjmp.h>
#include <errno.h>
#include <pthread.h>
#define PACKET_SIZE 4096
#define MAX_WAIT_TIME 5
#define MAX_NO_PACKETS 20
char sendpacket[PACKET_SIZE];
char recvpacket[PACKET_SIZE];
int sockfd,datalen=56;
int nsend=0,nreceived=0;
struct sockaddr_in dest_addr;
pid_t pid;
struct sockaddr_in from;
struct timeval tvrecv;
void statistics(int signo);
unsigned short cal_chksum(unsigned short *addr,int len);
int pack(int pack_no);
void *send_packet(void *args);
void *recv_packet(void *args);
int unpack(char *buf,int len);
void tv_sub(struct timeval *out,struct timeval *in);
void statistics(int signo){
printf("\n--------------------PING statistics-------------------\n");
printf("%d packets transmitted, %d received , %%%d lost\n",nsend,nreceived, (nsend-nreceived)/nsend*100);
close(sockfd);
exit(1);
}
/* this function generates header checksums */
unsigned short cal_chksum(unsigned short *addr,int len){
int nleft=len;
int sum=0;
unsigned short *w=addr;
unsigned short answer=0;
while(nleft>1) {
sum+=*w++;
nleft-=2;
}
if( nleft==1) {
*(unsigned char *)(&answer)=*(unsigned char *)w;
sum+=answer;
}
sum=(sum>>16)+(sum&0xffff);
sum+=(sum>>16);
answer=~sum;
return answer;
}
/*set ICMP header*/
int pack(int pack_no){
int packsize;
struct icmp *icmp;
struct timeval *tval;
icmp=(struct icmp*)sendpacket;
icmp->icmp_type=ICMP_ECHO;
icmp->icmp_code=0;
icmp->icmp_cksum=0;
icmp->icmp_seq=pack_no;
icmp->icmp_id=pid;
packsize=8+datalen;
tval= (struct timeval *)icmp->icmp_data;
gettimeofday(tval,NULL);
/*record sending time*/
icmp->icmp_cksum=cal_chksum( (unsigned short *)icmp,packsize);
/*call check sum algorithm*/
return packsize;
}
/*send 3 ICMP packets*/
void *send_packet(void *args){
int packetsize;
pid=getpid();
/*get process id to set ICMP id*/
while( nsend<MAX_NO_PACKETS) {
nsend++;
packetsize=pack(nsend);
/*set ICMP header*/
if( sendto(sockfd,sendpacket,packetsize,0, (struct sockaddr *)&dest_addr,sizeof(dest_addr) )<0 ) {
perror("sendto error");
continue;
}
sleep(1);
/*emit requests with a periodic delay*/
}
return 0;
}
/*receive all ICMP packet*/
void *recv_packet(void *args){
int n;
unsigned int fromlen;
extern int errno;
signal(SIGALRM,statistics);
fromlen=sizeof(from);
while( nreceived<MAX_NO_PACKETS) {
alarm(MAX_WAIT_TIME);
if( (n=recvfrom(sockfd,recvpacket,sizeof(recvpacket),0, (struct sockaddr *)&from,&fromlen)) <0){
if(errno==EINTR)continue;
perror("recvfrom error");
continue;
}
gettimeofday(&tvrecv,NULL);
/*record receiving time*/
if(unpack(recvpacket,n)==-1)continue;
nreceived++;
}
return 0;
}
/*unpack ICMP header*/
int unpack(char *buf,int len){
int iphdrlen;
struct ip *ip;
struct icmp *icmp;
struct timeval *tvsend;
double rtt;
ip=(struct ip *)buf;
iphdrlen=ip->ip_hl<<2;
/* get length of ip header -> 4 times the header length in the header*/
icmp=(struct icmp *)(buf+iphdrlen);
/*point to ICMP header*/
len-=iphdrlen;
/* length of ICMP header and ICMP datagram*/
if( len<8) /* invalid length*/
{
printf("ICMP packets\'s length is less than 8\n");
return -1;
}
/* make sure that we receive the ICMP_ECHOREPLY with our pid*/
if( (icmp->icmp_type==ICMP_ECHOREPLY) && (icmp->icmp_id==pid) ) {
tvsend=(struct timeval *)icmp->icmp_data;
tv_sub(&tvrecv,tvsend);
/*time of receiving the reply*/
rtt=tvrecv.tv_sec*1000+tvrecv.tv_usec/1000;
/*calculate rtt in milliseconds*/
/*show the information*/
printf("%d byte from %s: icmp_seq=%u ttl=%d rtt=%.3f ms\n", len, inet_ntoa(from.sin_addr), icmp->icmp_seq, ip->ip_ttl, rtt);
return 0;
}
else
return -1;
}
int main(int argc,char *argv[]){
struct hostent *host;
struct protoent *protocol;
unsigned long inaddr=0l;
//int waittime=MAX_WAIT_TIME;
int size=50*1024;
if(argc<2) {
printf("usage:%s hostname/IP address\n",argv[0]);
exit(1);
}
protocol=getprotobyname("icmp");
if( protocol == NULL) {
perror("getprotobyname");
exit(1);
}
/*generate raw socket*/
if( (sockfd=socket(AF_INET,SOCK_RAW,protocol->p_proto) )<0) {
perror("socket error");
exit(1);
}
setuid(getuid());
setsockopt(sockfd,SOL_SOCKET,SO_RCVBUF,&size,sizeof(size) );
bzero(&dest_addr,sizeof(dest_addr));
dest_addr.sin_family=AF_INET;
inaddr=inet_addr(argv[1]);
host=gethostbyname(argv[1]);
if( inaddr==INADDR_NONE) { /*hostname*/
if(host==NULL)
{
perror("gethostbyname error");
exit(1);
}
memcpy( (char *)&dest_addr.sin_addr,host->h_addr,host->h_length);
}
else /*ip address*/
memcpy( (char *)&dest_addr,(char *)&inaddr,host->h_length);
// pid=getpid();
printf("PING %s(%s): %d bytes data in ICMP packets.\n",argv[1], inet_ntoa(dest_addr.sin_addr),datalen);
pthread_t tids_send, tids_recv;
int ret = pthread_create(&tids_send, NULL, send_packet, NULL);
if (ret != 0) {
printf("pthread_create error: error_code = %d\n", ret);
}
ret = pthread_create(&tids_recv, NULL, recv_packet, NULL);
if (ret != 0) {
printf("pthread_create error: error_code = %d\n", ret);
}
pthread_join(tids_send, NULL);
pthread_join(tids_recv, NULL);
statistics(SIGALRM);
/**/
return 0;
}
/*sub of two timeval structure */
void tv_sub(struct timeval *out,struct timeval *in){
if( (out->tv_usec-=in->tv_usec)<0) {
--out->tv_sec;
out->tv_usec+=1000000;
} out->tv_sec-=in->tv_sec;
}
|
the_stack_data/190768109.c | #include <alloca.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#define LLEN 16
unsigned int getfile(const char *fname,char **h);
void write_array(const char *name,char *bp,int cfd,unsigned int len);
int main(int argc,char *argv[])
{
DIR *d;
struct dirent *e;
char *s_file;
char *h_file;
int dlen;
int sfd,hfd;
char fnames[2018];
char buf[1024];
char hname[512];
char *hbp,*bp,*bpn;
int i;
unsigned int len;
if (argc != 2) {
printf("Please specify directory containing the html files\n");
return 0;
}
d=opendir(argv[1]);
if (d == NULL) {
printf("could not open directory %s\n",argv[1]);
return 0;
}
dlen=strlen(argv[1]);
s_file=alloca(dlen+16);
strcpy(s_file,argv[1]);
strcat(s_file,"/html_files.s");
unlink(s_file);
h_file=alloca(dlen+16);
strcpy(h_file,argv[1]);
strcat(h_file,"/html_files.h");
unlink(h_file);
bp=fnames;
while (NULL != (e=readdir(d))){
if (e->d_name[0] == '.') continue;
if (strchr(e->d_name,'.') == 0) continue; //count on . extension
i=strlen(e->d_name);
if (bp + i > &fnames[2000]) {
printf("Too many files ???\n");
abort();
}
strcpy(bp,e->d_name);
bp=bp+i+1;
}
*bp='\0';
sfd=creat(s_file,0666);
hfd=creat(h_file,0666);
strcpy(buf,"/* created by loadhtml */\n\n");
write(sfd,buf,strlen(buf));
write(hfd,buf,strlen(buf));
strcpy(buf,"#ifdef __cplusplus\n");
write(hfd,buf,strlen(buf));
strcpy(buf,"#extern \"C\" {\n");
write(hfd,buf,strlen(buf));
strcpy(buf,"#endif\n");
write(hfd,buf,strlen(buf));
bpn=fnames;
while (*bpn != '\0'){
i=strlen(bpn);
strcpy(hname,bpn);
bp=strchr(hname,'.');
*bp='_';
strcpy(buf,"\t.globl\t");
strcat(buf,hname);
strcat(buf,"_len\n");
write(sfd,buf,strlen(buf));
strcpy(buf,"\t.globl\t");
strcat(buf,hname);
strcat(buf,"_start\n");
write(sfd,buf,strlen(buf));
strcpy(buf,"extern unsigned int ");
strcat(buf,hname);
strcat(buf,"_len;\n");
write(hfd,buf,strlen(buf));
strcpy(buf,"extern char ");
strcat(buf,hname);
strcat(buf,"_start;\n");
write(hfd,buf,strlen(buf));
bpn=bpn+i+1;
}
strcpy(buf,"#ifdef __cplusplus\n");
write(hfd,buf,strlen(buf));
strcpy(buf,"}\n");
write(hfd,buf,strlen(buf));
strcpy(buf,"#endif\n");
write(hfd,buf,strlen(buf));
strcpy(buf,"\t.data\n\n");
write(sfd,buf,strlen(buf));
close(hfd);
bpn=fnames;
while (*bpn != '\0'){
strcpy(hname,argv[1]);
strcat(hname,"/");
strcat(hname,bpn);
i=strlen(bpn);
len=getfile(hname,&hbp);
if (hbp == NULL) {
printf("Could not load %s\n",bpn);
abort(); //image load failed
}
strcpy(buf,"\t.align 4\n");
write(sfd,buf,strlen(buf));
strcpy(hname,bpn);
bp=strchr(hname,'.');
*bp='_';
strcpy(buf,hname);
strcat(buf,"_len:\n");
write(sfd,buf,strlen(buf));
sprintf(buf,"\t.long\t%u\n\n",len);
write(sfd,buf,strlen(buf));
strcat(hname,"_start");
write_array(hname,hbp,sfd,len);
free(hbp);
bpn=bpn+i+1;
}
close(sfd);
return 0;
}
void write_array(const char *name,char *bpx,int cfd,unsigned int len)
{
int i;
char buf[1024];
unsigned char *bp;
bp=(unsigned char *)bpx;
strcpy(buf,"\t.align 1\n");
write(cfd,buf,strlen(buf));
sprintf(buf,"%s:\n",name);
write(cfd,buf,strlen(buf));
i=0;
strcpy(buf,"\t.byte\t");
write(cfd,buf,strlen(buf));
while (len != 0) {
sprintf(buf,"%u",(unsigned int)*bp);
if (i == LLEN-1) {
strcat(buf,"\n");
write(cfd,buf,strlen(buf));
strcpy(buf,"\t.byte\t");
write(cfd,buf,strlen(buf));
i=0;++bp;--len;
}
else {
strcat(buf,",");
write(cfd,buf,strlen(buf));
++bp;++i;--len;
}
}
while (i < LLEN) {
strcpy(buf,"0");
if (i == LLEN-1) {
strcat(buf,"\n\n\n");
write(cfd,buf,strlen(buf));
}
else {
strcat(buf,",");
write(cfd,buf,strlen(buf));
}
++i;
}
}
unsigned int getfile(const char *fname,char **h)
{
int fdx;
struct stat stx;
*h=NULL;
fdx=open(fname,O_RDONLY);
if (fdx == -1) {
return 0;
}
if ( 0 != fstat(fdx,&stx)) {
return 0;
}
*h=(char *)malloc(stx.st_size+1);
if (stx.st_size != read(fdx,*h,stx.st_size)) {
free((void *)*h);
*h=NULL;
close(fdx);
return 0;
}
close(fdx);
*(*h+stx.st_size)='\0';
return stx.st_size;
} |
the_stack_data/92325537.c |
struct t63 {
int n;
};
struct bar_t62 {
struct t63 m;
};
struct bar_t62 a;
struct bar_t62 b;
struct bar_t62 c;
int main ()
{
struct t65 {
int n;
};
struct foo_t64 {
struct t65 m;
};
typedef struct foo_t64 baz_t66;
struct foo_t64 *p_p486;
struct foo_t64 pp_p487;
}
|
the_stack_data/232956133.c | /*
* libc/time/__tm_to_time.c
*/
#include <time.h>
/*
* C defines the rounding for division in a nonsensical way
*/
#define Q(a,b) ((a)>0 ? (a)/(b) : -(((b)-(a)-1)/(b)))
time_t __tm_to_time(struct tm * tm)
{
time_t year = tm->tm_year + -100;
int month = tm->tm_mon;
int day = tm->tm_mday;
int z4, z100, z400;
if (month >= 12)
{
year += month / 12;
month %= 12;
}
else if (month < 0)
{
year += month / 12;
month %= 12;
if (month)
{
month += 12;
year--;
}
}
z4 = Q(year - (month < 2), 4);
z100 = Q(z4, 25);
z400 = Q(z100, 4);
day += year * 365 + z4 - z100 + z400 + month[(int[]){ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 335 }];
return (long long) day * 86400 + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec - -946684800;
}
|
the_stack_data/100141555.c | #include<stdio.h>
#define LEN 12
//计算日期是一年中的第几天
int sum_day(int month,int day);
//是否是闰年
int leap(int year);
int main()
{
int year,month,day;
int days;
printf("请输入日期(year,month,day):\n");
scanf("%d,%d,%d",&year,&month,&day);
printf("%d/%d/%d\n",year,month,day);
days = sum_day(month,day);
if(leap(year) && month > 2)
{
days += 1;
}
printf("days=%d\n",days);
return 0;
}
//计算日期是一年中的第几天
int sum_day(int month,int day)
{
int day_tab[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
int i;
for(i = 0; i < month; i++)
{
day = day + day_tab[i];
}
return day;
}
//是否是闰年
int leap(int year)
{
int leap;
leap == (year % 4 == 0) && (year % 100 != 0) || year % 400 == 0;
return leap;
}
|
the_stack_data/145453478.c | #include<stdio.h>
void factorize(int ,int );
int main(){
int num;
printf("Enetr a number : ");
scanf("%d",&num);
printf("Prime factor are:");
factorize(num,2);
return 0;
}
void factorize(int n,int i)
{
if(i<=n)
{
if (n%i==0)
{
printf("%d",i);
n=n/i;
}
else
i++;
factorize(n,i);
}
} |
the_stack_data/59862.c | /* hello.c */
#include <stdio.h>
int main(void)
{
puts("Hello World!");
return 0;
}
|
the_stack_data/1965.c | /*
* Uncompress a raster3d input file into a temporary file
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __hpux
#define ungz_ ungz
#endif
int ungz_( origname, tempname )
char *origname, *tempname;
{
char command[128];
char *t;
int ierr;
#ifdef GUNZIP
t = tempnam( NULL, "R3D%%" );
sprintf( command, "gunzip -c %s > %s", origname, t );
ierr = system( command );
strcpy( tempname, t );
#else
fprintf(stderr," >> sorry, no decompression support\n");
ierr = -1;
#endif
return(ierr);
}
|
the_stack_data/95451411.c | //*****************************************************************************
//
// startup_ccs.c - Startup code for use with TI's Code Composer Studio.
//
// Copyright (c) 2009-2012 Texas Instruments Incorporated. All rights reserved.
// Software License Agreement
//
// Texas Instruments (TI) is supplying this software for use solely and
// exclusively on TI's microcontroller products. The software is owned by
// TI and/or its suppliers, and is protected under applicable copyright
// laws. You may not combine this software with "viral" open-source
// software in order to form a larger program.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
// DAMAGES, FOR ANY REASON WHATSOEVER.
//
// This is part of revision 8555 of the EK-LM3S9B90 Firmware Package.
//
//*****************************************************************************
//*****************************************************************************
//
// Forward declaration of the default fault handlers.
//
//*****************************************************************************
void ResetISR(void);
static void NmiSR(void);
static void FaultISR(void);
static void IntDefaultHandler(void);
//*****************************************************************************
//
// External declaration for the reset handler that is to be called when the
// processor is started
//
//*****************************************************************************
extern void _c_int00(void);
//*****************************************************************************
//
// Linker variable that marks the top of the stack.
//
//*****************************************************************************
extern unsigned long __STACK_TOP;
//*****************************************************************************
//
// External declarations for the interrupt handlers used by the application.
//
//*****************************************************************************
extern void lwIPEthernetIntHandler(void);
extern void SysTickIntHandler(void);
extern void USB0DeviceIntHandler(void);
//*****************************************************************************
//
// The vector table. Note that the proper constructs must be placed on this to
// ensure that it ends up at physical address 0x0000.0000 or at the start of
// the program if located at a start address other than 0.
//
//*****************************************************************************
#pragma DATA_SECTION(g_pfnVectors, ".intvecs")
void (* const g_pfnVectors[])(void) =
{
(void (*)(void))((unsigned long)&__STACK_TOP),
// The initial stack pointer
ResetISR, // The reset handler
NmiSR, // The NMI handler
FaultISR, // The hard fault handler
IntDefaultHandler, // The MPU fault handler
IntDefaultHandler, // The bus fault handler
IntDefaultHandler, // The usage fault handler
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
IntDefaultHandler, // SVCall handler
IntDefaultHandler, // Debug monitor handler
0, // Reserved
IntDefaultHandler, // The PendSV handler
SysTickIntHandler, // The SysTick handler
IntDefaultHandler, // GPIO Port A
IntDefaultHandler, // GPIO Port B
IntDefaultHandler, // GPIO Port C
IntDefaultHandler, // GPIO Port D
IntDefaultHandler, // GPIO Port E
IntDefaultHandler, // UART0 Rx and Tx
IntDefaultHandler, // UART1 Rx and Tx
IntDefaultHandler, // SSI0 Rx and Tx
IntDefaultHandler, // I2C0 Master and Slave
IntDefaultHandler, // PWM Fault
IntDefaultHandler, // PWM Generator 0
IntDefaultHandler, // PWM Generator 1
IntDefaultHandler, // PWM Generator 2
IntDefaultHandler, // Quadrature Encoder 0
IntDefaultHandler, // ADC Sequence 0
IntDefaultHandler, // ADC Sequence 1
IntDefaultHandler, // ADC Sequence 2
IntDefaultHandler, // ADC Sequence 3
IntDefaultHandler, // Watchdog timer
IntDefaultHandler, // Timer 0 subtimer A
IntDefaultHandler, // Timer 0 subtimer B
IntDefaultHandler, // Timer 1 subtimer A
IntDefaultHandler, // Timer 1 subtimer B
IntDefaultHandler, // Timer 2 subtimer A
IntDefaultHandler, // Timer 2 subtimer B
IntDefaultHandler, // Analog Comparator 0
IntDefaultHandler, // Analog Comparator 1
IntDefaultHandler, // Analog Comparator 2
IntDefaultHandler, // System Control (PLL, OSC, BO)
IntDefaultHandler, // FLASH Control
IntDefaultHandler, // GPIO Port F
IntDefaultHandler, // GPIO Port G
IntDefaultHandler, // GPIO Port H
IntDefaultHandler, // UART2 Rx and Tx
IntDefaultHandler, // SSI1 Rx and Tx
IntDefaultHandler, // Timer 3 subtimer A
IntDefaultHandler, // Timer 3 subtimer B
IntDefaultHandler, // I2C1 Master and Slave
IntDefaultHandler, // Quadrature Encoder 1
IntDefaultHandler, // CAN0
IntDefaultHandler, // CAN1
IntDefaultHandler, // CAN2
lwIPEthernetIntHandler, // Ethernet
IntDefaultHandler, // Hibernate
USB0DeviceIntHandler, // USB0
IntDefaultHandler, // PWM Generator 3
IntDefaultHandler, // uDMA Software Transfer
IntDefaultHandler, // uDMA Error
IntDefaultHandler, // ADC1 Sequence 0
IntDefaultHandler, // ADC1 Sequence 1
IntDefaultHandler, // ADC1 Sequence 2
IntDefaultHandler, // ADC1 Sequence 3
IntDefaultHandler, // I2S0
IntDefaultHandler, // External Bus Interface 0
IntDefaultHandler // GPIO Port J
};
//*****************************************************************************
//
// This is the code that gets called when the processor first starts execution
// following a reset event. Only the absolutely necessary set is performed,
// after which the application supplied entry() routine is called. Any fancy
// actions (such as making decisions based on the reset cause register, and
// resetting the bits in that register) are left solely in the hands of the
// application.
//
//*****************************************************************************
void
ResetISR(void)
{
//
// Jump to the CCS C initialization routine.
//
__asm(" .global _c_int00\n"
" b.w _c_int00");
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives a NMI. This
// simply enters an infinite loop, preserving the system state for examination
// by a debugger.
//
//*****************************************************************************
static void
NmiSR(void)
{
//
// Enter an infinite loop.
//
while(1)
{
}
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives a fault
// interrupt. This simply enters an infinite loop, preserving the system state
// for examination by a debugger.
//
//*****************************************************************************
static void
FaultISR(void)
{
//
// Enter an infinite loop.
//
while(1)
{
}
}
//*****************************************************************************
//
// This is the code that gets called when the processor receives an unexpected
// interrupt. This simply enters an infinite loop, preserving the system state
// for examination by a debugger.
//
//*****************************************************************************
static void
IntDefaultHandler(void)
{
//
// Go into an infinite loop.
//
while(1)
{
}
}
|
the_stack_data/138419.c | /*
* Sample solution for HP CodeWars 2012
* Problem 1
* "X Litres of Ginger Soda"
*/
#include <stdio.h>
#include <stdlib.h>
#define LITER_IN_GALLON 3.785 // Given
int main(void)
{
char input[255];
double litres;
double gallons_with_fraction;
int gallons_whole;
double fraction;
// Read one line at a time, until there is no more input
while(fgets(input, sizeof(input), stdin) != NULL)
{
litres = atof(input);
gallons_with_fraction = litres/LITER_IN_GALLON;
gallons_whole = (int) gallons_with_fraction; // This truncates
fraction = gallons_with_fraction - gallons_whole;
if(fraction >= 0.5)
{
// Add one to round up
gallons_whole += 1;
}
printf("%d\n", gallons_whole);
}
return 0;
}
|
the_stack_data/16566.c | #include <stdio.h>
int main()
{
int numofx,x,i;
float avg,sum;
sum=0;
i=0;
scanf("%d", &numofx);
do{
scanf("%d", &x);
sum=sum+x;
i++;
}while(i<numofx);
avg=sum/numofx;
printf("Sum: %.0f\n", sum);
printf("Avg: %.2f", avg);
}
|
the_stack_data/139791.c | #include <stdio.h>
int main() {
int arr[20];
int count, in;
for (count = 0; count < 20; ++count) {
arr[count] = count * 2;
}
printf("要素番号は? ");
scanf("%d", &in);
if (in < 20) {
printf("指定要素 (%d) の数は %d \n", in, arr[in]);
}
else {
printf("入力値が範囲オーバ \n");
}
return 0;
}
|
the_stack_data/95450799.c | //
// Created by forgot on 2019-08-02.
//
/*1009 说反话 (20 point(s))*/
/*给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。
输入格式:
测试输入包含一个测试用例,在一行内给出总长度不超过 80 的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,
单词之间用 1 个空格分开,输入保证句子末尾没有多余的空格。
输出格式:
每个测试用例的输出占一行,输出倒序后的句子。
输入样例:
Hello World Here I Come
输出样例:
Come I Here World Hello*/
//麻烦
#include <stdio.h>
#include <string.h>
//直接输出
//int main() {
// char str[81];
// gets(str);
// for (int i = strlen(str); i > 0; i--) {
// if (str[i] == ' ') {
// printf("%s ", &str[i + 1]);
// str[i] = '\0'; //\0表示结束符,后续字符串将在次中断
// }
// }
// printf("%s", &str[0]);
// return 0;
//}
//保存为数组,再输出
//int main() {
// char *p[81];
// int index = 0;
// char c[81];
// gets(c);
//
// for (int j = strlen(c); j >= 0; j--) {
// if (c[j] == ' ') {
// p[index] = &c[j + 1];
// index++;
// c[j] = '\0';
// }
// }
// p[index] = &c[0];
//
// for (int i = 0; i < index; ++i) {
// printf("%s ", p[i]);
// }
// printf("%s", p[index]);
//
// return 0;
//}
|
the_stack_data/31220.c | /*Exercise 2 - Selection
Write a program to calculate the amount to be paid for a rented vehicle.
• Input the distance the van has travelled
• The first 30 km is at a rate of 50/= per km.
• The remaining distance is calculated at the rate of 40/= per km.
e.g.
Distance -> 20
Amount = 20 x 50 = 1000
Distance -> 50
Amount = 30 x 50 + (50-30) x 40 = 2300*/
#include <stdio.h>
int main() {
float distance, amount ;
printf("enter the distance that van has travalled :");
scanf("%f" , &distance);
if(distance <=30 )
{
amount = distance * 50;
}
else if (distance > 30 )
{
amount = 30*50 + (distance- 30)*40;
}
printf("amount to be paid = %.2f\n" , amount );
return 0;
}
|
the_stack_data/247018317.c | #include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct link{
int val;
struct link *next;
}LINK;
void createLink(LINK* link, int* nums, int numsSize);
void insertLink(LINK* link, int site, int data);
void deletLink(LINK* link, int site);
void reverseLink(LINK* link);
void printLink(LINK*);
int main(void){
srand(time(NULL));
LINK* link=(LINK*)malloc(sizeof(LINK));
int list[7]={0};
//initialize
printf("templet:\t");
link->val=0; link->next=NULL;
for(int i=0;i<7;i++) { list[i]=rand()%10+1; printf("%d,", list[i]); }
printf("\n");
//run function and output
printf("linked list:\t");
createLink(link, list, 7);
printLink(link);
printf("after insert:\t");
insertLink(link,1,9);
printLink(link);
printf("after delete:\t");
deletLink(link,3);
printLink(link);
printf("after reverse:\t");
reverseLink(link);
printLink(link);
return 0;
}
void reverseLink(LINK* link){
LINK *ptr, *end=NULL;
while(link->next){
ptr=link->next->next;
link->next->next=end;
end=link->next;
link->next=ptr;
}
link->next=end;
}
void createLink(LINK* link, int* nums, int numsSize){
LINK* ptr=link;
for(int i=0;i<numsSize;i++){
LINK *newnode=(LINK*)malloc(sizeof(LINK));
newnode->val=nums[i]; newnode->next=NULL;
ptr->next=newnode;
ptr=newnode;
}
}
void insertLink(LINK* link, int site, int data){
LINK *ptr=link, *newnode=(LINK*)malloc(sizeof(LINK));
int tmp=0;
newnode->val=data;
while(tmp!=site) { ptr=ptr->next; tmp++; if(!ptr) break; }
if(ptr){
newnode->next=ptr->next;
ptr->next=newnode;
}
}
void deletLink(LINK* link, int site){
LINK *ptr=link;
int tmp=0;
while(tmp!=site) { ptr=ptr->next; tmp++; if(!ptr) break; }
if(ptr) ptr->next=ptr->next->next;
}
void printLink(LINK* link){
LINK* ptr=link->next;
while(ptr){
printf("%d,",ptr->val);
ptr=ptr->next;
}printf("\n");
}
|
the_stack_data/32950262.c | int titleToNumber(char* s) {
int len = strlen(s);
if(len <= 0){
return 0;
}
int i = 0;
int multip = 1;
int result = 0;
for(i=len-1;i>=0;i--){
result += (s[i] - 'A' + 1)*multip;
multip *= 26;
}
return result;
} |
the_stack_data/247017301.c | /*
* Copyright (c) Regents of The University of Michigan
* See COPYING.
*/
#include <sys/types.h>
#include <grp.h>
#include <pwd.h>
#include <stdio.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>
/* #include "config.h" */
#ifndef SIMTA_PROCMAIL
#define SIMTA_PROCMAIL "/usr/bin/procmail"
#endif
#ifndef SIMTA_MAIL_LOCAL
#define SIMTA_MAIL_LOCAL ""
#endif
int
main(int argc, char **argv) {
struct passwd *simta_pw;
if (argc < 3) {
fprintf(stderr, "Usage: %s <user> <program> [args]\n", argv[ 0 ]);
return (EX_TEMPFAIL);
}
if ((simta_pw = getpwnam(argv[ 1 ])) == NULL) {
fprintf(stderr, "%s: user not found\n", argv[ 1 ]);
return (1);
}
if ((strcmp(argv[ 2 ], SIMTA_PROCMAIL) == 0) ||
(strcmp(argv[ 2 ], SIMTA_MAIL_LOCAL) == 0)) {
/* The program is allowed, drop root privileges. */
if (initgroups(simta_pw->pw_name, 0) != 0) {
perror("initgroups");
return (EX_TEMPFAIL);
}
if (setgid(simta_pw->pw_gid) != 0) {
perror("setgid");
return (EX_TEMPFAIL);
}
if (setuid(simta_pw->pw_uid) != 0) {
perror("setuid");
return (EX_TEMPFAIL);
}
/* Execute the program as the requested user. */
argc -= 2;
argv += 2;
execv(argv[ 0 ], argv);
perror("execv");
} else {
fprintf(stderr, "%s is not an allowed MDA\n", argv[ 2 ]);
}
/* Either execv failed or someone tried to call an unauthorized program */
return (EX_TEMPFAIL);
}
|
the_stack_data/136787.c | #define NULL ((void*)0)
typedef unsigned long size_t; // Customize by platform.
typedef long intptr_t; typedef unsigned long uintptr_t;
typedef long scalar_t__; // Either arithmetic or pointer type.
/* By default, we understand bool (as a convenience). */
typedef int bool;
#define false 0
#define true 1
/* Forward declarations */
/* Type definitions */
/* Variables and functions */
int /*<<< orphan*/ fts5Porter_MGt0 (char*,int) ;
int /*<<< orphan*/ memcmp (char*,char*,int) ;
int /*<<< orphan*/ memcpy (char*,char*,int) ;
__attribute__((used)) static int fts5PorterStep2(char *aBuf, int *pnBuf){
int ret = 0;
int nBuf = *pnBuf;
switch( aBuf[nBuf-2] ){
case 'a':
if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
if( fts5Porter_MGt0(aBuf, nBuf-7) ){
memcpy(&aBuf[nBuf-7], "ate", 3);
*pnBuf = nBuf - 7 + 3;
}
}else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
if( fts5Porter_MGt0(aBuf, nBuf-6) ){
memcpy(&aBuf[nBuf-6], "tion", 4);
*pnBuf = nBuf - 6 + 4;
}
}
break;
case 'c':
if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
if( fts5Porter_MGt0(aBuf, nBuf-4) ){
memcpy(&aBuf[nBuf-4], "ence", 4);
*pnBuf = nBuf - 4 + 4;
}
}else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
if( fts5Porter_MGt0(aBuf, nBuf-4) ){
memcpy(&aBuf[nBuf-4], "ance", 4);
*pnBuf = nBuf - 4 + 4;
}
}
break;
case 'e':
if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
if( fts5Porter_MGt0(aBuf, nBuf-4) ){
memcpy(&aBuf[nBuf-4], "ize", 3);
*pnBuf = nBuf - 4 + 3;
}
}
break;
case 'g':
if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
if( fts5Porter_MGt0(aBuf, nBuf-4) ){
memcpy(&aBuf[nBuf-4], "log", 3);
*pnBuf = nBuf - 4 + 3;
}
}
break;
case 'l':
if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
if( fts5Porter_MGt0(aBuf, nBuf-3) ){
memcpy(&aBuf[nBuf-3], "ble", 3);
*pnBuf = nBuf - 3 + 3;
}
}else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
if( fts5Porter_MGt0(aBuf, nBuf-4) ){
memcpy(&aBuf[nBuf-4], "al", 2);
*pnBuf = nBuf - 4 + 2;
}
}else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
if( fts5Porter_MGt0(aBuf, nBuf-5) ){
memcpy(&aBuf[nBuf-5], "ent", 3);
*pnBuf = nBuf - 5 + 3;
}
}else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
if( fts5Porter_MGt0(aBuf, nBuf-3) ){
memcpy(&aBuf[nBuf-3], "e", 1);
*pnBuf = nBuf - 3 + 1;
}
}else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
if( fts5Porter_MGt0(aBuf, nBuf-5) ){
memcpy(&aBuf[nBuf-5], "ous", 3);
*pnBuf = nBuf - 5 + 3;
}
}
break;
case 'o':
if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
if( fts5Porter_MGt0(aBuf, nBuf-7) ){
memcpy(&aBuf[nBuf-7], "ize", 3);
*pnBuf = nBuf - 7 + 3;
}
}else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
if( fts5Porter_MGt0(aBuf, nBuf-5) ){
memcpy(&aBuf[nBuf-5], "ate", 3);
*pnBuf = nBuf - 5 + 3;
}
}else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
if( fts5Porter_MGt0(aBuf, nBuf-4) ){
memcpy(&aBuf[nBuf-4], "ate", 3);
*pnBuf = nBuf - 4 + 3;
}
}
break;
case 's':
if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
if( fts5Porter_MGt0(aBuf, nBuf-5) ){
memcpy(&aBuf[nBuf-5], "al", 2);
*pnBuf = nBuf - 5 + 2;
}
}else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
if( fts5Porter_MGt0(aBuf, nBuf-7) ){
memcpy(&aBuf[nBuf-7], "ive", 3);
*pnBuf = nBuf - 7 + 3;
}
}else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
if( fts5Porter_MGt0(aBuf, nBuf-7) ){
memcpy(&aBuf[nBuf-7], "ful", 3);
*pnBuf = nBuf - 7 + 3;
}
}else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
if( fts5Porter_MGt0(aBuf, nBuf-7) ){
memcpy(&aBuf[nBuf-7], "ous", 3);
*pnBuf = nBuf - 7 + 3;
}
}
break;
case 't':
if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
if( fts5Porter_MGt0(aBuf, nBuf-5) ){
memcpy(&aBuf[nBuf-5], "al", 2);
*pnBuf = nBuf - 5 + 2;
}
}else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
if( fts5Porter_MGt0(aBuf, nBuf-5) ){
memcpy(&aBuf[nBuf-5], "ive", 3);
*pnBuf = nBuf - 5 + 3;
}
}else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
if( fts5Porter_MGt0(aBuf, nBuf-6) ){
memcpy(&aBuf[nBuf-6], "ble", 3);
*pnBuf = nBuf - 6 + 3;
}
}
break;
}
return ret;
} |
the_stack_data/19570.c | #include <stdlib.h>
void main(){
system("/bin/sh");
}
|
the_stack_data/150144494.c | /* Check use of condition in points-to analysis
*
* Note that simplify_control could use points-to information here to
* simplify the test. The returned value would then be known.
*/
int test02()
{
int i, j;
int *p = &i;
int *q = &j;
if(p==q)
i = 1;
else
i = 2;
return i;
}
|
the_stack_data/212644493.c | #include<stdio.h>
int main()
{
double N[12][12],sum=0.0;
char O[2];
scanf("%s",&O);
int n=10,i,j;
for(i = 0;i < 12;i++){
for(j = 0;j < 12;j++){
scanf("%lf",&N[i][j]);
}
}
for(i = 1;i < 12;i++){
for(j = 11;j > n;j--){
sum += N[i][j];
}
n--;
}
if (O[0]=='S')printf("%.1lf\n",sum);
else printf("%.1lf\n",sum/66.0);
return 0;
} |
the_stack_data/206393832.c | #include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#define PI 3.1416
double m = 3;
double a = 20 * PI / 180;
double z = 12;
double x = 0.6;
double H = 32;
double aw = 20 * PI / 180;
int main(int argc, char *argv[])
{
char *eptr;
int i;
for (i = 1; i < argc; i += 2)
{
if (strcmp(argv[i], "-m") == 0)
{
m = strtod(argv[i + 1], &eptr);
if (m < 0)
{
printf("arg m must be a positive number.\n");
}
}
else if (strcmp(argv[i], "-a") == 0)
{
a = strtod(argv[i + 1], &eptr) * PI / 180;
if (a < 0)
{
printf("arg a must be a positive number.\n");
}
}
else if (strcmp(argv[i], "-z") == 0)
{
z = strtod(argv[i + 1], &eptr);
if (z < 0)
{
printf("arg z must be a positive number.\n");
}
}
else if (strcmp(argv[i], "-x") == 0)
{
x = strtod(argv[i + 1], &eptr);
if (x < 0)
{
printf("arg x must be a positive number.\n");
}
}
else if (strcmp(argv[i], "-H") == 0)
{
H = strtod(argv[i + 1], &eptr);
if (H < 0)
{
printf("arg H must be a positive number.\n");
}
}
else if (strcmp(argv[i], "-aw") == 0)
{
aw = strtod(argv[i + 1], &eptr) * PI / 180;
if (aw < 0)
{
printf("arg aw must be a positive number.\n");
}
}
}
printf("Usage: ./rack -m %f -a %f -z %f -x %f -H %f -aw %f \n", m, a, z, x, H, aw);
printf("\t-m \tModule\n");
printf("\t-a \tPressure Angle\n");
printf("\t-z \tNumber of teeth\n");
printf("\t-H \tHeight of Pitch Line\n");
printf("\t-x \tCoefficient of Profile Shift\n");
printf("\t-aw \tWorking Pressure Angle\n\n");
double ax = (z * m / 2) + H + x * m;
double d = z * m;
double db = d * cos(a);
double dw = db / cos(aw);
double hag = m * (1 + x);
double har = m;
double h = 2.25 * m;
double da = d + 2 * hag;
double df = da - 2 * h;
double mp = (sqrt(pow(da / 2, 2) - pow(df / 2, 2)) + ((har - x * m / sin(a))) - ((d / 2) * sin(a))) / (PI * m * cos(a));
printf("\n--------------------- \t\t\tSpur Gear\tRack\n");
printf("Module: \t\t\t\t%f\n", m);
printf("Pressure Angle: \t\t\t%f\n", a);
printf("Number of Teeth: \t\t\t%f\n", z);
printf("Coefficient of Profile Shift: \t\t%f\n", x);
printf("Height of Pitch Line: \t\t\t%f\n", H);
printf("Working Pressure Angle: \t\t%f\n", aw);
printf("Center Distance: \t\t\t%f\n", ax);
printf("Pitch Diameter: \t\t\t%f\n", d);
printf("Base Diameter: \t\t\t\t%f\n", db);
printf("Working Pitch Diameter: \t\t%f\n", dw);
printf("Addendum: \t\t\t\t%f\t%f\n", hag, har);
printf("Whole Depth: \t\t\t\t%f\n", h);
printf("Outside Diameter: \t\t\t%f\n", da);
printf("Root Diameter: \t\t\t\t%f\n", df);
printf("Contact Ratio: \t\t\t\t%f\n", mp);
}
|
the_stack_data/759933.c | extern void exit (int);
f (unsigned char *a)
{
int i, j;
int x, y;
j = a[1];
i = a[0] - j;
if (i < 0)
{
x = 1;
y = -i;
}
else
{
x = 0;
y = i;
}
return x + y;
}
main ()
{
unsigned char a[2];
a[0] = 8;
a[1] = 9;
if (f (a) != 2)
abort ();
exit (0);
}
|
the_stack_data/110349.c | extern void __VERIFIER_error() __attribute__ ((__noreturn__));
extern int __VERIFIER_nondet_int(void);
extern int printf (__const char *__restrict __format, ...);
/* Generated by CIL v. 1.3.7 */
/* print_CIL_Input is true */
struct JoinPoint {
void **(*fp)(struct JoinPoint * ) ;
void **args ;
int argsCount ;
char const **argsType ;
void *(*arg)(int , struct JoinPoint * ) ;
char const *(*argType)(int , struct JoinPoint * ) ;
void **retValue ;
char const *retType ;
char const *funcName ;
char const *targetName ;
char const *fileName ;
char const *kind ;
void *excep_return ;
};
struct __UTAC__CFLOW_FUNC {
int (*func)(int , int ) ;
int val ;
struct __UTAC__CFLOW_FUNC *next ;
};
struct __UTAC__EXCEPTION {
void *jumpbuf ;
unsigned long long prtValue ;
int pops ;
struct __UTAC__CFLOW_FUNC *cflowfuncs ;
};
typedef unsigned int size_t;
struct __ACC__ERR {
void *v ;
struct __ACC__ERR *next ;
};
#pragma merger(0,"wsllib_check.i","")
void __automaton_fail(void)
{
{
ERROR: __VERIFIER_error();
return;
}
}
#pragma merger(0,"libacc.i","")
extern __attribute__((__nothrow__, __noreturn__)) void __assert_fail(char const *__assertion ,
char const *__file ,
unsigned int __line ,
char const *__function ) ;
extern __attribute__((__nothrow__)) void *malloc(size_t __size ) __attribute__((__malloc__)) ;
extern __attribute__((__nothrow__)) void free(void *__ptr ) ;
void __utac__exception__cf_handler_set(void *exception , int (*cflow_func)(int ,
int ) ,
int val )
{ struct __UTAC__EXCEPTION *excep ;
struct __UTAC__CFLOW_FUNC *cf ;
void *tmp ;
unsigned long __cil_tmp7 ;
unsigned long __cil_tmp8 ;
unsigned long __cil_tmp9 ;
unsigned long __cil_tmp10 ;
unsigned long __cil_tmp11 ;
unsigned long __cil_tmp12 ;
unsigned long __cil_tmp13 ;
unsigned long __cil_tmp14 ;
int (**mem_15)(int , int ) ;
int *mem_16 ;
struct __UTAC__CFLOW_FUNC **mem_17 ;
struct __UTAC__CFLOW_FUNC **mem_18 ;
struct __UTAC__CFLOW_FUNC **mem_19 ;
{
{
excep = (struct __UTAC__EXCEPTION *)exception;
tmp = malloc(24UL);
cf = (struct __UTAC__CFLOW_FUNC *)tmp;
mem_15 = (int (**)(int , int ))cf;
*mem_15 = cflow_func;
__cil_tmp7 = (unsigned long )cf;
__cil_tmp8 = __cil_tmp7 + 8;
mem_16 = (int *)__cil_tmp8;
*mem_16 = val;
__cil_tmp9 = (unsigned long )cf;
__cil_tmp10 = __cil_tmp9 + 16;
__cil_tmp11 = (unsigned long )excep;
__cil_tmp12 = __cil_tmp11 + 24;
mem_17 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp10;
mem_18 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp12;
*mem_17 = *mem_18;
__cil_tmp13 = (unsigned long )excep;
__cil_tmp14 = __cil_tmp13 + 24;
mem_19 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp14;
*mem_19 = cf;
}
return;
}
}
void __utac__exception__cf_handler_free(void *exception )
{ struct __UTAC__EXCEPTION *excep ;
struct __UTAC__CFLOW_FUNC *cf ;
struct __UTAC__CFLOW_FUNC *tmp ;
unsigned long __cil_tmp5 ;
unsigned long __cil_tmp6 ;
struct __UTAC__CFLOW_FUNC *__cil_tmp7 ;
unsigned long __cil_tmp8 ;
unsigned long __cil_tmp9 ;
unsigned long __cil_tmp10 ;
unsigned long __cil_tmp11 ;
void *__cil_tmp12 ;
unsigned long __cil_tmp13 ;
unsigned long __cil_tmp14 ;
struct __UTAC__CFLOW_FUNC **mem_15 ;
struct __UTAC__CFLOW_FUNC **mem_16 ;
struct __UTAC__CFLOW_FUNC **mem_17 ;
{
excep = (struct __UTAC__EXCEPTION *)exception;
__cil_tmp5 = (unsigned long )excep;
__cil_tmp6 = __cil_tmp5 + 24;
mem_15 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp6;
cf = *mem_15;
{
while (1) {
while_0_continue: /* CIL Label */ ;
{
__cil_tmp7 = (struct __UTAC__CFLOW_FUNC *)0;
__cil_tmp8 = (unsigned long )__cil_tmp7;
__cil_tmp9 = (unsigned long )cf;
if (__cil_tmp9 != __cil_tmp8) {
} else {
goto while_0_break;
}
}
{
tmp = cf;
__cil_tmp10 = (unsigned long )cf;
__cil_tmp11 = __cil_tmp10 + 16;
mem_16 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp11;
cf = *mem_16;
__cil_tmp12 = (void *)tmp;
free(__cil_tmp12);
}
}
while_0_break: /* CIL Label */ ;
}
__cil_tmp13 = (unsigned long )excep;
__cil_tmp14 = __cil_tmp13 + 24;
mem_17 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp14;
*mem_17 = (struct __UTAC__CFLOW_FUNC *)0;
return;
}
}
void __utac__exception__cf_handler_reset(void *exception )
{ struct __UTAC__EXCEPTION *excep ;
struct __UTAC__CFLOW_FUNC *cf ;
unsigned long __cil_tmp5 ;
unsigned long __cil_tmp6 ;
struct __UTAC__CFLOW_FUNC *__cil_tmp7 ;
unsigned long __cil_tmp8 ;
unsigned long __cil_tmp9 ;
int (*__cil_tmp10)(int , int ) ;
unsigned long __cil_tmp11 ;
unsigned long __cil_tmp12 ;
int __cil_tmp13 ;
unsigned long __cil_tmp14 ;
unsigned long __cil_tmp15 ;
struct __UTAC__CFLOW_FUNC **mem_16 ;
int (**mem_17)(int , int ) ;
int *mem_18 ;
struct __UTAC__CFLOW_FUNC **mem_19 ;
{
excep = (struct __UTAC__EXCEPTION *)exception;
__cil_tmp5 = (unsigned long )excep;
__cil_tmp6 = __cil_tmp5 + 24;
mem_16 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp6;
cf = *mem_16;
{
while (1) {
while_1_continue: /* CIL Label */ ;
{
__cil_tmp7 = (struct __UTAC__CFLOW_FUNC *)0;
__cil_tmp8 = (unsigned long )__cil_tmp7;
__cil_tmp9 = (unsigned long )cf;
if (__cil_tmp9 != __cil_tmp8) {
} else {
goto while_1_break;
}
}
{
mem_17 = (int (**)(int , int ))cf;
__cil_tmp10 = *mem_17;
__cil_tmp11 = (unsigned long )cf;
__cil_tmp12 = __cil_tmp11 + 8;
mem_18 = (int *)__cil_tmp12;
__cil_tmp13 = *mem_18;
(*__cil_tmp10)(4, __cil_tmp13);
__cil_tmp14 = (unsigned long )cf;
__cil_tmp15 = __cil_tmp14 + 16;
mem_19 = (struct __UTAC__CFLOW_FUNC **)__cil_tmp15;
cf = *mem_19;
}
}
while_1_break: /* CIL Label */ ;
}
{
__utac__exception__cf_handler_free(exception);
}
return;
}
}
void *__utac__error_stack_mgt(void *env , int mode , int count ) ;
static struct __ACC__ERR *head = (struct __ACC__ERR *)0;
void *__utac__error_stack_mgt(void *env , int mode , int count )
{ void *retValue_acc ;
struct __ACC__ERR *new ;
void *tmp ;
struct __ACC__ERR *temp ;
struct __ACC__ERR *next ;
void *excep ;
unsigned long __cil_tmp10 ;
unsigned long __cil_tmp11 ;
unsigned long __cil_tmp12 ;
unsigned long __cil_tmp13 ;
void *__cil_tmp14 ;
unsigned long __cil_tmp15 ;
unsigned long __cil_tmp16 ;
void *__cil_tmp17 ;
void **mem_18 ;
struct __ACC__ERR **mem_19 ;
struct __ACC__ERR **mem_20 ;
void **mem_21 ;
struct __ACC__ERR **mem_22 ;
void **mem_23 ;
void **mem_24 ;
{
if (count == 0) {
return (retValue_acc);
} else {
}
if (mode == 0) {
{
tmp = malloc(16UL);
new = (struct __ACC__ERR *)tmp;
mem_18 = (void **)new;
*mem_18 = env;
__cil_tmp10 = (unsigned long )new;
__cil_tmp11 = __cil_tmp10 + 8;
mem_19 = (struct __ACC__ERR **)__cil_tmp11;
*mem_19 = head;
head = new;
retValue_acc = (void *)new;
}
return (retValue_acc);
} else {
}
if (mode == 1) {
temp = head;
{
while (1) {
while_2_continue: /* CIL Label */ ;
if (count > 1) {
} else {
goto while_2_break;
}
{
__cil_tmp12 = (unsigned long )temp;
__cil_tmp13 = __cil_tmp12 + 8;
mem_20 = (struct __ACC__ERR **)__cil_tmp13;
next = *mem_20;
mem_21 = (void **)temp;
excep = *mem_21;
__cil_tmp14 = (void *)temp;
free(__cil_tmp14);
__utac__exception__cf_handler_reset(excep);
temp = next;
count = count - 1;
}
}
while_2_break: /* CIL Label */ ;
}
{
__cil_tmp15 = (unsigned long )temp;
__cil_tmp16 = __cil_tmp15 + 8;
mem_22 = (struct __ACC__ERR **)__cil_tmp16;
head = *mem_22;
mem_23 = (void **)temp;
excep = *mem_23;
__cil_tmp17 = (void *)temp;
free(__cil_tmp17);
__utac__exception__cf_handler_reset(excep);
retValue_acc = excep;
}
return (retValue_acc);
} else {
}
if (mode == 2) {
if (head) {
mem_24 = (void **)head;
retValue_acc = *mem_24;
return (retValue_acc);
} else {
retValue_acc = (void *)0;
return (retValue_acc);
}
} else {
}
return (retValue_acc);
}
}
void *__utac__get_this_arg(int i , struct JoinPoint *this )
{ void *retValue_acc ;
unsigned long __cil_tmp4 ;
unsigned long __cil_tmp5 ;
int __cil_tmp6 ;
int __cil_tmp7 ;
unsigned long __cil_tmp8 ;
unsigned long __cil_tmp9 ;
void **__cil_tmp10 ;
void **__cil_tmp11 ;
int *mem_12 ;
void ***mem_13 ;
{
if (i > 0) {
{
__cil_tmp4 = (unsigned long )this;
__cil_tmp5 = __cil_tmp4 + 16;
mem_12 = (int *)__cil_tmp5;
__cil_tmp6 = *mem_12;
if (i <= __cil_tmp6) {
} else {
{
__assert_fail("i > 0 && i <= this->argsCount", "libacc.c",
123U, "__utac__get_this_arg");
}
}
}
} else {
{
__assert_fail("i > 0 && i <= this->argsCount", "libacc.c",
123U, "__utac__get_this_arg");
}
}
__cil_tmp7 = i - 1;
__cil_tmp8 = (unsigned long )this;
__cil_tmp9 = __cil_tmp8 + 8;
mem_13 = (void ***)__cil_tmp9;
__cil_tmp10 = *mem_13;
__cil_tmp11 = __cil_tmp10 + __cil_tmp7;
retValue_acc = *__cil_tmp11;
return (retValue_acc);
return (retValue_acc);
}
}
char const *__utac__get_this_argtype(int i , struct JoinPoint *this )
{ char const *retValue_acc ;
unsigned long __cil_tmp4 ;
unsigned long __cil_tmp5 ;
int __cil_tmp6 ;
int __cil_tmp7 ;
unsigned long __cil_tmp8 ;
unsigned long __cil_tmp9 ;
char const **__cil_tmp10 ;
char const **__cil_tmp11 ;
int *mem_12 ;
char const ***mem_13 ;
{
if (i > 0) {
{
__cil_tmp4 = (unsigned long )this;
__cil_tmp5 = __cil_tmp4 + 16;
mem_12 = (int *)__cil_tmp5;
__cil_tmp6 = *mem_12;
if (i <= __cil_tmp6) {
} else {
{
__assert_fail("i > 0 && i <= this->argsCount", "libacc.c",
131U, "__utac__get_this_argtype");
}
}
}
} else {
{
__assert_fail("i > 0 && i <= this->argsCount", "libacc.c",
131U, "__utac__get_this_argtype");
}
}
__cil_tmp7 = i - 1;
__cil_tmp8 = (unsigned long )this;
__cil_tmp9 = __cil_tmp8 + 24;
mem_13 = (char const ***)__cil_tmp9;
__cil_tmp10 = *mem_13;
__cil_tmp11 = __cil_tmp10 + __cil_tmp7;
retValue_acc = *__cil_tmp11;
return (retValue_acc);
return (retValue_acc);
}
}
#pragma merger(0,"featureselect.i","")
int select_one(void) ;
void select_features(void) ;
void select_helpers(void) ;
int valid_product(void) ;
int select_one(void)
{ int retValue_acc ;
int choice = __VERIFIER_nondet_int();
{
retValue_acc = choice;
return (retValue_acc);
return (retValue_acc);
}
}
void select_features(void)
{
{
return;
}
}
void select_helpers(void)
{
{
return;
}
}
int valid_product(void)
{ int retValue_acc ;
{
retValue_acc = 1;
return (retValue_acc);
return (retValue_acc);
}
}
#pragma merger(0,"scenario.i","")
void waterRise(void) ;
void changeMethaneLevel(void) ;
void stopSystem(void) ;
void timeShift(void) ;
void cleanup(void) ;
void test(void)
{ int splverifierCounter ;
int tmp ;
int tmp___0 ;
int tmp___1 ;
int tmp___2 ;
{
splverifierCounter = 0;
{
while (1) {
while_3_continue: /* CIL Label */ ;
if (splverifierCounter < 4) {
} else {
goto while_3_break;
}
{
tmp = __VERIFIER_nondet_int();
}
if (tmp) {
{
waterRise();
}
} else {
}
{
tmp___0 = __VERIFIER_nondet_int();
}
if (tmp___0) {
{
changeMethaneLevel();
}
} else {
}
{
tmp___2 = __VERIFIER_nondet_int();
}
if (tmp___2) {
} else {
{
tmp___1 = __VERIFIER_nondet_int();
}
if (tmp___1) {
{
stopSystem();
}
} else {
}
}
{
timeShift();
}
}
while_3_break: /* CIL Label */ ;
}
{
cleanup();
}
return;
}
}
#pragma merger(0,"MinePump.i","")
void lowerWaterLevel(void) ;
int isMethaneLevelCritical(void) ;
void printEnvironment(void) ;
void activatePump(void) ;
void deactivatePump(void) ;
int isPumpRunning(void) ;
void printPump(void) ;
int pumpRunning = 0;
int systemActive = 1;
void __utac_acc__Specification4_spec__1(void) ;
void processEnvironment(void) ;
void timeShift(void)
{
{
if (pumpRunning) {
{
lowerWaterLevel();
}
} else {
}
if (systemActive) {
{
processEnvironment();
}
} else {
}
{
__utac_acc__Specification4_spec__1();
}
return;
}
}
void processEnvironment(void)
{
{
return;
}
}
void activatePump(void)
{
{
pumpRunning = 1;
return;
}
}
void deactivatePump(void)
{
{
pumpRunning = 0;
return;
}
}
int isMethaneAlarm(void)
{ int retValue_acc ;
{
{
retValue_acc = isMethaneLevelCritical();
}
return (retValue_acc);
return (retValue_acc);
}
}
int isPumpRunning(void)
{ int retValue_acc ;
{
retValue_acc = pumpRunning;
return (retValue_acc);
return (retValue_acc);
}
}
void printPump(void)
{
{
{
printf("Pump(System:");
}
if (systemActive) {
{
printf("On");
}
} else {
{
printf("Off");
}
}
{
printf(",Pump:");
}
if (pumpRunning) {
{
printf("On");
}
} else {
{
printf("Off");
}
}
{
printf(") ");
printEnvironment();
printf("\n");
}
return;
}
}
void stopSystem(void)
{
{
if (pumpRunning) {
{
deactivatePump();
}
} else {
}
systemActive = 0;
return;
}
}
#pragma merger(0,"Environment.i","")
int getWaterLevel(void) ;
int waterLevel = 1;
int methaneLevelCritical = 0;
void lowerWaterLevel(void)
{
{
if (waterLevel > 0) {
waterLevel = waterLevel - 1;
} else {
}
return;
}
}
void waterRise(void)
{
{
if (waterLevel < 2) {
waterLevel = waterLevel + 1;
} else {
}
return;
}
}
void changeMethaneLevel(void)
{
{
if (methaneLevelCritical) {
methaneLevelCritical = 0;
} else {
methaneLevelCritical = 1;
}
return;
}
}
int isMethaneLevelCritical(void)
{ int retValue_acc ;
{
retValue_acc = methaneLevelCritical;
return (retValue_acc);
return (retValue_acc);
}
}
void printEnvironment(void)
{
{
{
printf("Env(Water:%i", waterLevel);
printf(",Meth:");
}
if (methaneLevelCritical) {
{
printf("CRIT");
}
} else {
{
printf("OK");
}
}
{
printf(")");
}
return;
}
}
int getWaterLevel(void)
{ int retValue_acc ;
{
retValue_acc = waterLevel;
return (retValue_acc);
return (retValue_acc);
}
}
#pragma merger(0,"Specification4_spec.i","")
void __utac_acc__Specification4_spec__1(void)
{ int tmp ;
int tmp___0 ;
{
{
tmp = getWaterLevel();
}
if (tmp == 0) {
{
tmp___0 = isPumpRunning();
}
if (tmp___0) {
{
__automaton_fail();
}
} else {
}
} else {
}
return;
}
}
#pragma merger(0,"Test.i","")
int cleanupTimeShifts = 4;
void cleanup(void)
{ int i ;
int __cil_tmp2 ;
{
{
timeShift();
i = 0;
}
{
while (1) {
while_4_continue: /* CIL Label */ ;
{
__cil_tmp2 = cleanupTimeShifts - 1;
if (i < __cil_tmp2) {
} else {
goto while_4_break;
}
}
{
timeShift();
i = i + 1;
}
}
while_4_break: /* CIL Label */ ;
}
return;
}
}
void Specification2(void)
{
{
{
timeShift();
printPump();
timeShift();
printPump();
timeShift();
printPump();
waterRise();
printPump();
timeShift();
printPump();
changeMethaneLevel();
printPump();
timeShift();
printPump();
cleanup();
}
return;
}
}
void setup(void)
{
{
return;
}
}
void runTest(void)
{
{
{
test();
}
return;
}
}
int main(void)
{ int retValue_acc ;
int tmp ;
{
{
select_helpers();
select_features();
tmp = valid_product();
}
if (tmp) {
{
setup();
runTest();
}
} else {
}
retValue_acc = 0;
return (retValue_acc);
return (retValue_acc);
}
}
|
the_stack_data/56874.c | #include <ncurses.h>
/* TODO not echo char and respond only if getch is arrow, or
show 'player missed' if wrong button was pressed.
*/
int main() {
initscr(); // start curses
/* Enables use of arrow keys(important), fn
keys(f1, f2...).
if this is not set, the program would end. */
keypad(stdscr, TRUE);
printw("This is A multiplayer game in which two people can press an arrow key. First to 10 presses wins.\n"); // rules of 'game'
refresh(); // refresh screen to show instructions
int ch; // to-be user input character
int left = 0; // player 1
int right = 0; // player 2
int misses = 0;
int inc; // increment number for time limit
for (inc = 0; inc < 10; inc++) { // increment number for time limit
ch = getch(); // get device input
switch(ch) { // get key presses as 'player turn'
case KEY_LEFT:
left = left + 1; // increase player score
printw("left: %d, right: %d, miss: %d\n", left, right, misses);
break; /* either this(left) or right. either or, should break to return which one happened
(like latch vs momentary). switch will loop again to get next 'turn'.*/
case KEY_RIGHT:
right = right + 1;
printw("left: %d, right: %d, miss: %d\n", left, right, misses);
break;
default:
misses += 1;
printw("miss! remaining tries: %d\n", inc);
break;
}
refresh();
}
// after loop endwin()
endwin();
printf("Game over after 10 tries.\n");
printf("Left: %d Right: %d, Misses: %d\n", left, right, misses);
if (left > right) {
printf("Left Wins!\n");
} else if (right > left) {
printf("Right Wins!\n");
} else {
printf("Tie! Rematch\n");
}
return(0);
}
|
the_stack_data/14200196.c | // 使用C语言处理分数
#include <stdio.h>
typedef struct{
int numerator;
int denominator;
} Fraction;
int main(void){
Fraction myFract;
myFract.numerator = 1;
myFract.denominator = 3;
printf("The fraction is %i/%i\n", myFract.numerator, myFract.denominator);
return 0;
}
|
the_stack_data/98575275.c | #include <stdio.h>
#include <time.h>
#include <omp.h>
int main()
{
int m=4, n =16384;
int i,j;
double a[m][n];
double s[m];
double secs = 0;
clock_t begin = clock();
#pragma omp parallel num_threads (8)
{
#pragma omp for schedule(static, 3)
for (i=0; i<m; i++) // 24 iterations
{
s[i] = 1.0;
for (j=0; j<n; j++) // 16384 iterations
{
s[i] = s[i] + a[i][j];
}
}
}
printf("%f", s[1]);
clock_t end = clock();
secs = (double)(end-begin) / CLOCKS_PER_SEC;
printf("\nTime taken = %f\n", secs);
return 0;
} |
the_stack_data/28263242.c | /* Exercise 1 - Calculations
Write a C program to input marks of two subjects. Calculate and print the average of the two marks. */
#include<stdio.h>
int main ()
{
int x,y;
float tot,avg;
printf("Enter the first number :");
scanf("%d", &x);
printf("Enter the first number :");
scanf("%d", &y);
tot = x + y ;
avg = tot / 2;
printf("Average is : %.2f ", avg);
return 0;
}
|
the_stack_data/36074402.c | /* <MIT License>
Copyright (c) 2013 Marek Majkowski <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
</MIT License>
Original location:
https://github.com/majek/csiphash/
Solution inspired by code from:
Samuel Neves (supercop/crypto_auth/siphash24/little)
djb (supercop/crypto_auth/siphash24/little2)
Jean-Philippe Aumasson (https://131002.net/siphash/siphash24.c)
*/
#include <stdint.h>
#if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \
__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
# define _le64toh(x) ((uint64_t)(x))
#elif defined(_WIN32)
/* Windows is always little endian, unless you're on xbox360
http://msdn.microsoft.com/en-us/library/b0084kay(v=vs.80).aspx */
# define _le64toh(x) ((uint64_t)(x))
#elif defined(__APPLE__)
# include <libkern/OSByteOrder.h>
# define _le64toh(x) OSSwapLittleToHostInt64(x)
#else
/* See: http://sourceforge.net/p/predef/wiki/Endianness/ */
# if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
# include <sys/endian.h>
# else
# include <endian.h>
# endif
# if defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \
__BYTE_ORDER == __LITTLE_ENDIAN
# define _le64toh(x) ((uint64_t)(x))
# else
# define _le64toh(x) le64toh(x)
# endif
#endif
#define ROTATE(x, b) (uint64_t)( ((x) << (b)) | ( (x) >> (64 - (b))) )
#define HALF_ROUND(a,b,c,d,s,t) \
a += b; c += d; \
b = ROTATE(b, s) ^ a; \
d = ROTATE(d, t) ^ c; \
a = ROTATE(a, 32);
#define DOUBLE_ROUND(v0,v1,v2,v3) \
HALF_ROUND(v0,v1,v2,v3,13,16); \
HALF_ROUND(v2,v1,v0,v3,17,21); \
HALF_ROUND(v0,v1,v2,v3,13,16); \
HALF_ROUND(v2,v1,v0,v3,17,21);
#ifdef DRY_RUN
# undef DOUBLE_ROUND
# define DOUBLE_ROUND(a,b,c,d)
#endif
void half_round(const uint64_t in[4], uint64_t out[4]) {
uint64_t a, b, c, d;
a = in[0]; b = in[1]; c = in[2]; d = in[3];
HALF_ROUND(a, b, c, d, 13, 16);
HALF_ROUND(c, b, a, d, 17, 21);
HALF_ROUND(a, b, c, d, 13, 16);
HALF_ROUND(c, b, a, d, 17, 21);
out[0] = a; out[1] = b; out[2] = c; out[3] = d;
}
uint64_t siphash24(const void *src, unsigned long src_sz, const char key[16]) {
const uint64_t *_key = (uint64_t *)key;
uint64_t k0 = _le64toh(_key[0]);
uint64_t k1 = _le64toh(_key[1]);
uint64_t b = (uint64_t)src_sz << 56;
const uint64_t *in = (uint64_t*)src;
uint64_t v0 = k0 ^ 0x736f6d6570736575ULL;
uint64_t v1 = k1 ^ 0x646f72616e646f6dULL;
uint64_t v2 = k0 ^ 0x6c7967656e657261ULL;
uint64_t v3 = k1 ^ 0x7465646279746573ULL;
while (src_sz >= 8) {
uint64_t mi = _le64toh(*in);
in += 1; src_sz -= 8;
v3 ^= mi;
DOUBLE_ROUND(v0,v1,v2,v3);
v0 ^= mi;
}
uint64_t t = 0; uint8_t *pt = (uint8_t *)&t; uint8_t *m = (uint8_t *)in;
switch (src_sz) {
case 7: pt[6] = m[6];
case 6: pt[5] = m[5];
case 5: pt[4] = m[4];
case 4: *((uint32_t*)&pt[0]) = *((uint32_t*)&m[0]); break;
case 3: pt[2] = m[2];
case 2: pt[1] = m[1];
case 1: pt[0] = m[0];
}
b |= _le64toh(t);
v3 ^= b;
DOUBLE_ROUND(v0,v1,v2,v3);
v0 ^= b;
v2 ^= 0xff;
DOUBLE_ROUND(v0,v1,v2,v3);
DOUBLE_ROUND(v0,v1,v2,v3);
return (v0 ^ v1) ^ (v2 ^ v3);
}
|
the_stack_data/466392.c | /* C/C++ program to solve N Queen Problem using
backtracking */
#define N 4
#include <stdbool.h>
#include <stdio.h>
/* A utility function to print solution */
void printSolution(int board[N][N])
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
printf(" %d ", board[i][j]);
printf("\n");
}
}
/* A utility function to check if a queen can
be placed on board[row][col]. Note that this
function is called when "col" queens are
already placed in columns from 0 to col -1.
So we need to check only left side for
attacking queens */
bool isSafe(int board[N][N], int row, int col)
{
int i, j;
/* Check this row on left side */
for (i = 0; i < col; i++)
if (board[row][i])
return false;
/* Check upper diagonal on left side */
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return false;
/* Check lower diagonal on left side */
for (i = row, j = col; j >= 0 && i < N; i++, j--)
if (board[i][j])
return false;
return true;
}
/* A recursive utility function to solve N
Queen problem */
bool solveNQUtil(int board[N][N], int col)
{
/* base case: If all queens are placed
then return true */
if (col >= N)
return true;
/* Consider this column and try placing
this queen in all rows one by one */
for (int i = 0; i < N; i++) {
/* Check if the queen can be placed on
board[i][col] */
if (isSafe(board, i, col)) {
/* Place this queen in board[i][col] */
board[i][col] = 1;
/* recur to place rest of the queens */
if (solveNQUtil(board, col + 1))
return true;
/* If placing queen in board[i][col]
doesn't lead to a solution, then
remove queen from board[i][col] */
board[i][col] = 0; // BACKTRACK
}
}
/* If the queen cannot be placed in any row in
this colum col then return false */
return false;
}
/* This function solves the N Queen problem using
Backtracking. It mainly uses solveNQUtil() to
solve the problem. It returns false if queens
cannot be placed, otherwise, return true and
prints placement of queens in the form of 1s.
Please note that there may be more than one
solutions, this function prints one of the
feasible solutions.*/
bool solveNQ()
{
int board[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };
if (solveNQUtil(board, 0) == false) {
printf("Solution does not exist");
return false;
}
printSolution(board);
return true;
}
// driver program to test above function
int main()
{
solveNQ();
return 0;
}
|
the_stack_data/7950787.c | void crypt() {} ;
void crypt_r() {} ;
void encrypt() {} ;
void encrypt_r() {} ;
void setkey() {} ;
void setkey_r() {} ;
|
the_stack_data/225141837.c | // Scrivere un programma che legga da tastiera un grafo
// indiretto e stampi 1 se il grafo `e bipartito, 0
// altrimenti. Il grafo `e rappresentato nel seguente
// formato: la prima riga contiene il numero n di nodi,
// le successive n righe contengono, per ciascun nodo i,
// con 0≤i<n , il numero ni di archi uscenti da i
// seguito da una lista di ni nodi destinazione.
// Un grafo bipartito `e un grafo tale che l’insieme dei
// suoi vertici si può partizionare in due sottoinsiemi
// in cui ogni vertice `e collegato solo a vertici
// appartenenti alla partizione opposta.
#include <stdio.h>
#include <stdlib.h>
int graph_size=0;
int *colors=NULL;
typedef struct _nodo {
int num;
int *nodo;
} nodo;
//Lettura grafo
nodo *read_graph(){
nodo *E;
int n,i,j;
scanf("%d",&n);
graph_size=n;
E=(nodo*)malloc(sizeof(nodo)*n);
for(i=0;i<n;i++){
scanf("%d",&(E[i].num));
E[i].nodo=(int*)malloc(sizeof(int)*E[i].num);
for(j=0;j<E[i].num;j++)
scanf("%d",E[i].nodo+j);
}
return E;
}
// Visita DFS , "colora" i nodi con 2 colori differenti
void rec_dfs(int src,nodo *E,int found){
int dest;
if(colors[src]==0)
colors[src]=found;
for(int i=0;i<E[src].num;i++){
dest=E[src].nodo[i];
if(!colors[dest])
rec_dfs(dest,E,-found);
}
}
// Verifico se il grafo è bipartito (se i nodi adiacenti
// al vertice hanno un colore diverso)
int biparted(nodo *E,int v,int found){
rec_dfs(v,E,1);
for(int i=0;i<graph_size;i++)
for(int j=0;j<E[i].num;j++)
if(colors[i]==colors[E[i].nodo[j]])
return 0;
return 1;
}
int main() {
nodo *E=NULL;
colors=malloc(graph_size*sizeof(int));
E=read_graph();
for(int i=0;i<graph_size;i++)
colors[i]=0;
printf("%d\n",biparted(E,0,1));
return 0;
}
|
the_stack_data/128543.c | /*Ce fichier, écrit pour montrer les différentes erreurs possibles entre l'écriture et l'exécution d'un programme, est de M. Léry, tous droits réservés*/
#include <stdio.h> /*Si on écrit uniquement 'stdio', cela donne lieu à une erreur de compilation (ou erreur de syntaxe)*/
main()
{
printf("Hello World\n") ; /*l'absence d'éléments syntactiques, comme le ';', donne également lieu à des erreurs syntactiques*/
printf("cosinus = %f\n", cos(0.5)) ;
printf("%d\n", pow(2, 2)) ;
}
|
the_stack_data/49938.c |
#include <string.h>
#include <ctype.h>
int strncasecmp( const char* s1, const char* s2, size_t c ) {
int result = 0;
while ( c ) {
result = toupper( *s1 ) - toupper( *s2++ );
if ( ( result != 0 ) || ( *s1++ == 0 ) ) {
break;
}
c--;
}
return result;
}
|
the_stack_data/234518694.c | #include<stdio.h>
#include<string.h>
#ifdef __i386__
#define ARCH "i686\n"
#endif
#ifdef __x86_64__
#define ARCH "x86_64\n"
#endif
#define pcase(l, str) case l: printf(str); break;
int main(int argc, char** argv) {
if(argc != 2) {
return 1;
}
if(strlen(argv[1]) != 2) {
return 2;
}
if(argv[1][0] != '-') {
return 3;
}
switch(argv[1][1]) {
pcase('m', ARCH)
pcase('s', "Linux\n")
default:
return 4;
}
}
|
the_stack_data/549729.c | int
main() {
int n;
int t;
int c;
int p;
c = 0;
n = 2;
while (n < 5000) {
t = 2;
p = 1;
while (t*t <= n) {
if (n % t == 0)
p = 0;
t++;
}
n++;
if (p)
c++;
}
if (c != 669)
return 1;
return 0;
}
|
the_stack_data/15762081.c | #include <stdio.h>
int main(void)
{
FILE *ifile;
int done,num, message, count,sum;
double average;
ifile = fopen("my_second_file.txt", "r"); /* open file for reading
the "r" stands for reading*/
done = 0;
count = 0;
sum = 0;
while(!done)
{
message = fscanf(ifile, "%d", &num);
if (EOF == message)
{
done = 1;
}
else
{
printf("I read %d form the file.\n", num);
sum += num;
count++;
}
}
average = (double) sum /count;
printf("There are %d numbers in the file.\n", count);
printf("Average of %d numbers in the file is %0.2lf.\n", count, average);
fclose(ifile);
return 0;
} |
the_stack_data/225143564.c | /* { dg-lto-options "-mcpu=v9" { target sparc*-*-* } } */
/* { dg-require-effective-target sync_char_short } */
void
_cairo_clip_path_reference () {
int a;
__sync_fetch_and_add(&a, 1);
}
int main(void) {
return 0;
}
|
the_stack_data/998373.c | static unsigned int crctable[256]=
{
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D,
};
|
the_stack_data/181392925.c | #include<stdio.h>
/* I have done the following
* Transpose Matrix
* Diagonal sum
* Sum of Rows
* Sum of Cols*/
int main()
{
int i,j;
int row,col,sumForRow =0,sumForCols =0,sum1 = 0,sum2 = 0;
scanf("%d",&row);
scanf("%d",&col);
int k = row;
int arr1[row][col];
int arr2[row][col];
printf("-------------------This Program is Assigned for %dX%d Matrix----------------------\n",row,col);
printf("\t\tTaking Input for %dX%d Matrix\n",row,col);
for (i=0; i<row; i++)
{
for (j=0; j<col; j++)
{
printf("For Row %d Column %d = ",i+1,j+1);
scanf("%d",&arr1[i][j]);
}
}
for (i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
arr2[i][j] = arr1[j][i];
}
}
printf("\n----------Transpose Matrix----------\n");
for (i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
printf("%d ",arr2[i][j]);
}
printf("\n");
}
printf("\n----------Matrix Diagonal Sum----------\n");
if(row!=col)
{
printf("Diagonal Matrix is not possible!!(Should be equal mXn Matrix)");
goto repeat;
}
else
{
for (i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
if(i == j)
{
sum1+=arr1[i][j];
sum2+= arr1[i][col-k];
k--;
}
}
}
printf("Sum1 = %d, Sum2 = %d",sum1,sum2);
}
repeat:
printf("\n----------Sum of Rows & Columns----------\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
sumForRow+= arr1[i][j];
arr2[i][j] = arr1[j][i];
sumForCols += arr2[i][j];
}
printf("Sum of Row %d = %d\n",i+1, sumForRow);
printf("Sum of Col %d = %d\n",i+1, sumForCols);
sumForRow =0;
sumForCols = 0;
}
return 0;
}
|
the_stack_data/92328872.c | // itj aug/18/21
#include <stdio.h>
int main(void) {
int dayOfWeek = 1;
char days[8][10] = {
"", // place holder, wastes some space but arrays start at 0.
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
};
// Test for all days in the week
if (0 < dayOfWeek && dayOfWeek <= 7)
printf("The day of the week is: %s\n", days[dayOfWeek]);
return 0;
} |
the_stack_data/104828362.c | /* Getopt for GNU.
NOTE: getopt is now part of the C library, so if you don't know what
"Keep this file name-space clean" means, talk to [email protected]
before changing it!
Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99
Free Software Foundation, Inc.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
The GNU C Library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with the GNU C Library; see the file COPYING.LIB. If not,
write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA. */
/* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>.
Ditto for AIX 3.2 and <stdlib.h>. */
#ifndef _NO_PROTO
# define _NO_PROTO
#endif
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#if !defined __STDC__ || !__STDC__
/* This is a separate conditional since some stdc systems
reject `defined (const)'. */
# ifndef const
# define const
# endif
#endif
#include <stdio.h>
/* Comment out all this code if we are using the GNU C Library, and are not
actually compiling the library itself. This code is part of the GNU C
Library, but also included in many other GNU distributions. Compiling
and linking in this code is a waste when using the GNU C library
(especially if it is a shared library). Rather than having every GNU
program understand `configure --with-gnu-libc' and omit the object files,
it is simpler to just do this in the source for each such file. */
#define GETOPT_INTERFACE_VERSION 2
#if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2
# include <gnu-versions.h>
# if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION
# define ELIDE_CODE
# endif
#endif
#ifndef ELIDE_CODE
/* This needs to come after some library #include
to get __GNU_LIBRARY__ defined. */
#ifdef __GNU_LIBRARY__
/* Don't include stdlib.h for non-GNU C libraries because some of them
contain conflicting prototypes for getopt. */
# include <stdlib.h>
# include <unistd.h>
#endif /* GNU C library. */
#ifdef VMS
# include <unixlib.h>
# if HAVE_STRING_H - 0
# include <string.h>
# endif
#endif
#ifndef _
/* This is for other GNU distributions with internationalized messages.
When compiling libc, the _ macro is predefined. */
# ifdef HAVE_LIBINTL_H
# include <libintl.h>
# define _(msgid) gettext (msgid)
# else
# define _(msgid) (msgid)
# endif
#endif
/* This version of `getopt' appears to the caller like standard Unix `getopt'
but it behaves differently for the user, since it allows the user
to intersperse the options with the other arguments.
As `getopt' works, it permutes the elements of ARGV so that,
when it is done, all the options precede everything else. Thus
all application programs are extended to handle flexible argument order.
Setting the environment variable POSIXLY_CORRECT disables permutation.
Then the behavior is completely standard.
GNU application programs can use a third alternative mode in which
they can distinguish the relative order of options and other arguments. */
#include "getopt.h"
/* For communication from `getopt' to the caller.
When `getopt' finds an option that takes an argument,
the argument value is returned here.
Also, when `ordering' is RETURN_IN_ORDER,
each non-option ARGV-element is returned here. */
char *optarg;
/* Index in ARGV of the next element to be scanned.
This is used for communication to and from the caller
and for communication between successive calls to `getopt'.
On entry to `getopt', zero means this is the first call; initialize.
When `getopt' returns -1, this is the index of the first of the
non-option elements that the caller should itself scan.
Otherwise, `optind' communicates from one call to the next
how much of ARGV has been scanned so far. */
/* 1003.2 says this must be 1 before any call. */
int optind = 1;
/* Formerly, initialization of getopt depended on optind==0, which
causes problems with re-calling getopt as programs generally don't
know that. */
int __getopt_initialized;
/* The next char to be scanned in the option-element
in which the last option character we returned was found.
This allows us to pick up the scan where we left off.
If this is zero, or a null string, it means resume the scan
by advancing to the next ARGV-element. */
static char *nextchar;
/* Callers store zero here to inhibit the error message
for unrecognized options. */
int opterr = 1;
/* Set to an option character which was unrecognized.
This must be initialized on some systems to avoid linking in the
system's own getopt implementation. */
int optopt = '?';
/* Describe how to deal with options that follow non-option ARGV-elements.
If the caller did not specify anything,
the default is REQUIRE_ORDER if the environment variable
POSIXLY_CORRECT is defined, PERMUTE otherwise.
REQUIRE_ORDER means don't recognize them as options;
stop option processing when the first non-option is seen.
This is what Unix does.
This mode of operation is selected by either setting the environment
variable POSIXLY_CORRECT, or using `+' as the first character
of the list of option characters.
PERMUTE is the default. We permute the contents of ARGV as we scan,
so that eventually all the non-options are at the end. This allows options
to be given in any order, even with programs that were not written to
expect this.
RETURN_IN_ORDER is an option available to programs that were written
to expect options and other ARGV-elements in any order and that care about
the ordering of the two. We describe each non-option ARGV-element
as if it were the argument of an option with character code 1.
Using `-' as the first character of the list of option characters
selects this mode of operation.
The special argument `--' forces an end of option-scanning regardless
of the value of `ordering'. In the case of RETURN_IN_ORDER, only
`--' can cause `getopt' to return -1 with `optind' != ARGC. */
static enum
{
REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
} ordering;
/* Value of POSIXLY_CORRECT environment variable. */
static char *posixly_correct;
#ifdef __GNU_LIBRARY__
/* We want to avoid inclusion of string.h with non-GNU libraries
because there are many ways it can cause trouble.
On some systems, it contains special magic macros that don't work
in GCC. */
# include <string.h>
# define my_index strchr
#else
#include <string.h>
#include <stdlib.h>
/* Avoid depending on library functions or files
whose names are inconsistent. */
/*
#ifndef getenv
extern char *getenv ();
#endif
*/
static char *
my_index (str, chr)
const char *str;
int chr;
{
while (*str)
{
if (*str == chr)
return (char *) str;
str++;
}
return 0;
}
/* If using GCC, we can safely declare strlen this way.
If not using GCC, it is ok not to declare it. */
#ifdef __GNUC__
/* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
That was relevant to code that was here before. */
# if (!defined __STDC__ || !__STDC__) && !defined strlen
/* gcc with -traditional declares the built-in strlen to return int,
and has done so at least since version 2.4.5. -- rms. */
extern int strlen (const char *);
# endif /* not __STDC__ */
#endif /* __GNUC__ */
#endif /* not __GNU_LIBRARY__ */
/* Handle permutation of arguments. */
/* Describe the part of ARGV that contains non-options that have
been skipped. `first_nonopt' is the index in ARGV of the first of them;
`last_nonopt' is the index after the last of them. */
static int first_nonopt;
static int last_nonopt;
#ifdef _LIBC
/* Bash 2.0 gives us an environment variable containing flags
indicating ARGV elements that should not be considered arguments. */
/* Defined in getopt_init.c */
extern char *__getopt_nonoption_flags;
static int nonoption_flags_max_len;
static int nonoption_flags_len;
static int original_argc;
static char *const *original_argv;
/* Make sure the environment variable bash 2.0 puts in the environment
is valid for the getopt call we must make sure that the ARGV passed
to getopt is that one passed to the process. */
static void
__attribute__ ((unused))
store_args_and_env (int argc, char *const *argv)
{
/* XXX This is no good solution. We should rather copy the args so
that we can compare them later. But we must not use malloc(3). */
original_argc = argc;
original_argv = argv;
}
# ifdef text_set_element
text_set_element (__libc_subinit, store_args_and_env);
# endif /* text_set_element */
# define SWAP_FLAGS(ch1, ch2) \
if (nonoption_flags_len > 0) \
{ \
char __tmp = __getopt_nonoption_flags[ch1]; \
__getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \
__getopt_nonoption_flags[ch2] = __tmp; \
}
#else /* !_LIBC */
# define SWAP_FLAGS(ch1, ch2)
#endif /* _LIBC */
/* Exchange two adjacent subsequences of ARGV.
One subsequence is elements [first_nonopt,last_nonopt)
which contains all the non-options that have been skipped so far.
The other is elements [last_nonopt,optind), which contains all
the options processed since those non-options were skipped.
`first_nonopt' and `last_nonopt' are relocated so that they describe
the new indices of the non-options in ARGV after they are moved. */
#if defined __STDC__ && __STDC__
static void exchange (char **);
#endif
static void
exchange (argv)
char **argv;
{
int bottom = first_nonopt;
int middle = last_nonopt;
int top = optind;
char *tem;
/* Exchange the shorter segment with the far end of the longer segment.
That puts the shorter segment into the right place.
It leaves the longer segment in the right place overall,
but it consists of two parts that need to be swapped next. */
#ifdef _LIBC
/* First make sure the handling of the `__getopt_nonoption_flags'
string can work normally. Our top argument must be in the range
of the string. */
if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len)
{
/* We must extend the array. The user plays games with us and
presents new arguments. */
char *new_str = malloc (top + 1);
if (new_str == NULL)
nonoption_flags_len = nonoption_flags_max_len = 0;
else
{
memset (__mempcpy (new_str, __getopt_nonoption_flags,
nonoption_flags_max_len),
'\0', top + 1 - nonoption_flags_max_len);
nonoption_flags_max_len = top + 1;
__getopt_nonoption_flags = new_str;
}
}
#endif
while (top > middle && middle > bottom)
{
if (top - middle > middle - bottom)
{
/* Bottom segment is the short one. */
int len = middle - bottom;
register int i;
/* Swap it with the top part of the top segment. */
for (i = 0; i < len; i++)
{
tem = argv[bottom + i];
argv[bottom + i] = argv[top - (middle - bottom) + i];
argv[top - (middle - bottom) + i] = tem;
SWAP_FLAGS (bottom + i, top - (middle - bottom) + i);
}
/* Exclude the moved bottom segment from further swapping. */
top -= len;
}
else
{
/* Top segment is the short one. */
int len = top - middle;
register int i;
/* Swap it with the bottom part of the bottom segment. */
for (i = 0; i < len; i++)
{
tem = argv[bottom + i];
argv[bottom + i] = argv[middle + i];
argv[middle + i] = tem;
SWAP_FLAGS (bottom + i, middle + i);
}
/* Exclude the moved top segment from further swapping. */
bottom += len;
}
}
/* Update records for the slots the non-options now occupy. */
first_nonopt += (optind - last_nonopt);
last_nonopt = optind;
}
/* Initialize the internal data when the first call is made. */
#if defined __STDC__ && __STDC__
static const char *_getopt_initialize (int, char *const *, const char *);
#endif
static const char *
_getopt_initialize (argc, argv, optstring)
int argc;
char *const *argv;
const char *optstring;
{
/* Start processing options with ARGV-element 1 (since ARGV-element 0
is the program name); the sequence of previously skipped
non-option ARGV-elements is empty. */
first_nonopt = last_nonopt = optind;
nextchar = NULL;
posixly_correct = getenv ("POSIXLY_CORRECT");
/* Determine how to handle the ordering of options and nonoptions. */
if (optstring[0] == '-')
{
ordering = RETURN_IN_ORDER;
++optstring;
}
else if (optstring[0] == '+')
{
ordering = REQUIRE_ORDER;
++optstring;
}
else if (posixly_correct != NULL)
ordering = REQUIRE_ORDER;
else
ordering = PERMUTE;
#ifdef _LIBC
if (posixly_correct == NULL
&& argc == original_argc && argv == original_argv)
{
if (nonoption_flags_max_len == 0)
{
if (__getopt_nonoption_flags == NULL
|| __getopt_nonoption_flags[0] == '\0')
nonoption_flags_max_len = -1;
else
{
const char *orig_str = __getopt_nonoption_flags;
int len = nonoption_flags_max_len = strlen (orig_str);
if (nonoption_flags_max_len < argc)
nonoption_flags_max_len = argc;
__getopt_nonoption_flags =
(char *) malloc (nonoption_flags_max_len);
if (__getopt_nonoption_flags == NULL)
nonoption_flags_max_len = -1;
else
memset (__mempcpy (__getopt_nonoption_flags, orig_str, len),
'\0', nonoption_flags_max_len - len);
}
}
nonoption_flags_len = nonoption_flags_max_len;
}
else
nonoption_flags_len = 0;
#endif
return optstring;
}
/* Scan elements of ARGV (whose length is ARGC) for option characters
given in OPTSTRING.
If an element of ARGV starts with '-', and is not exactly "-" or "--",
then it is an option element. The characters of this element
(aside from the initial '-') are option characters. If `getopt'
is called repeatedly, it returns successively each of the option characters
from each of the option elements.
If `getopt' finds another option character, it returns that character,
updating `optind' and `nextchar' so that the next call to `getopt' can
resume the scan with the following option character or ARGV-element.
If there are no more option characters, `getopt' returns -1.
Then `optind' is the index in ARGV of the first ARGV-element
that is not an option. (The ARGV-elements have been permuted
so that those that are not options now come last.)
OPTSTRING is a string containing the legitimate option characters.
If an option character is seen that is not listed in OPTSTRING,
return '?' after printing an error message. If you set `opterr' to
zero, the error message is suppressed but we still return '?'.
If a char in OPTSTRING is followed by a colon, that means it wants an arg,
so the following text in the same ARGV-element, or the text of the following
ARGV-element, is returned in `optarg'. Two colons mean an option that
wants an optional arg; if there is text in the current ARGV-element,
it is returned in `optarg', otherwise `optarg' is set to zero.
If OPTSTRING starts with `-' or `+', it requests different methods of
handling the non-option ARGV-elements.
See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
Long-named options begin with `--' instead of `-'.
Their names may be abbreviated as long as the abbreviation is unique
or is an exact match for some defined option. If they have an
argument, it follows the option name in the same ARGV-element, separated
from the option name by a `=', or else the in next ARGV-element.
When `getopt' finds a long-named option, it returns 0 if that option's
`flag' field is nonzero, the value of the option's `val' field
if the `flag' field is zero.
The elements of ARGV aren't really const, because we permute them.
But we pretend they're const in the prototype to be compatible
with other systems.
LONGOPTS is a vector of `struct option' terminated by an
element containing a name which is zero.
LONGIND returns the index in LONGOPT of the long-named option found.
It is only valid when a long-named option has been found by the most
recent call.
If LONG_ONLY is nonzero, '-' as well as '--' can introduce
long-named options. */
int
_getopt_internal (argc, argv, optstring, longopts, longind, long_only)
int argc;
char *const *argv;
const char *optstring;
const struct option *longopts;
int *longind;
int long_only;
{
optarg = NULL;
if (optind == 0 || !__getopt_initialized)
{
if (optind == 0)
optind = 1; /* Don't scan ARGV[0], the program name. */
optstring = _getopt_initialize (argc, argv, optstring);
__getopt_initialized = 1;
}
/* Test whether ARGV[optind] points to a non-option argument.
Either it does not have option syntax, or there is an environment flag
from the shell indicating it is not an option. The later information
is only used when the used in the GNU libc. */
#ifdef _LIBC
# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \
|| (optind < nonoption_flags_len \
&& __getopt_nonoption_flags[optind] == '1'))
#else
# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')
#endif
if (nextchar == NULL || *nextchar == '\0')
{
/* Advance to the next ARGV-element. */
/* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been
moved back by the user (who may also have changed the arguments). */
if (last_nonopt > optind)
last_nonopt = optind;
if (first_nonopt > optind)
first_nonopt = optind;
if (ordering == PERMUTE)
{
/* If we have just processed some options following some non-options,
exchange them so that the options come first. */
if (first_nonopt != last_nonopt && last_nonopt != optind)
exchange ((char **) argv);
else if (last_nonopt != optind)
first_nonopt = optind;
/* Skip any additional non-options
and extend the range of non-options previously skipped. */
while (optind < argc && NONOPTION_P)
optind++;
last_nonopt = optind;
}
/* The special ARGV-element `--' means premature end of options.
Skip it like a null option,
then exchange with previous non-options as if it were an option,
then skip everything else like a non-option. */
if (optind != argc && !strcmp (argv[optind], "--"))
{
optind++;
if (first_nonopt != last_nonopt && last_nonopt != optind)
exchange ((char **) argv);
else if (first_nonopt == last_nonopt)
first_nonopt = optind;
last_nonopt = argc;
optind = argc;
}
/* If we have done all the ARGV-elements, stop the scan
and back over any non-options that we skipped and permuted. */
if (optind == argc)
{
/* Set the next-arg-index to point at the non-options
that we previously skipped, so the caller will digest them. */
if (first_nonopt != last_nonopt)
optind = first_nonopt;
return -1;
}
/* If we have come to a non-option and did not permute it,
either stop the scan or describe it to the caller and pass it by. */
if (NONOPTION_P)
{
if (ordering == REQUIRE_ORDER)
return -1;
optarg = argv[optind++];
return 1;
}
/* We have found another option-ARGV-element.
Skip the initial punctuation. */
nextchar = (argv[optind] + 1
+ (longopts != NULL && argv[optind][1] == '-'));
}
/* Decode the current option-ARGV-element. */
/* Check whether the ARGV-element is a long option.
If long_only and the ARGV-element has the form "-f", where f is
a valid short option, don't consider it an abbreviated form of
a long option that starts with f. Otherwise there would be no
way to give the -f short option.
On the other hand, if there's a long option "fubar" and
the ARGV-element is "-fu", do consider that an abbreviation of
the long option, just like "--fu", and not "-f" with arg "u".
This distinction seems to be the most useful approach. */
if (longopts != NULL
&& (argv[optind][1] == '-'
|| (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1])))))
{
char *nameend;
const struct option *p;
const struct option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = -1;
int option_index;
for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
/* Do nothing. */ ;
/* Test all long options for either exact match
or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp (p->name, nextchar, nameend - nextchar))
{
if ((unsigned int) (nameend - nextchar)
== (unsigned int) strlen (p->name))
{
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL)
{
/* First nonexact match found. */
pfound = p;
indfound = option_index;
}
else
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact)
{
if (opterr)
fprintf (stderr, _("%s: option `%s' is ambiguous\n"),
argv[0], argv[optind]);
nextchar += strlen (nextchar);
optind++;
optopt = 0;
return '?';
}
if (pfound != NULL)
{
option_index = indfound;
optind++;
if (*nameend)
{
/* Don't test has_arg with >, because some C compilers don't
allow it to be used on enums. */
if (pfound->has_arg)
optarg = nameend + 1;
else
{
if (opterr)
{
if (argv[optind - 1][1] == '-')
/* --option */
fprintf (stderr,
_("%s: option `--%s' doesn't allow an argument\n"),
argv[0], pfound->name);
else
/* +option or -option */
fprintf (stderr,
_("%s: option `%c%s' doesn't allow an argument\n"),
argv[0], argv[optind - 1][0], pfound->name);
}
nextchar += strlen (nextchar);
optopt = pfound->val;
return '?';
}
}
else if (pfound->has_arg == 1)
{
if (optind < argc)
optarg = argv[optind++];
else
{
if (opterr)
fprintf (stderr,
_("%s: option `%s' requires an argument\n"),
argv[0], argv[optind - 1]);
nextchar += strlen (nextchar);
optopt = pfound->val;
return optstring[0] == ':' ? ':' : '?';
}
}
nextchar += strlen (nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag)
{
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
/* Can't find it as a long option. If this is not getopt_long_only,
or the option starts with '--' or is not a valid short
option, then it's an error.
Otherwise interpret it as a short option. */
if (!long_only || argv[optind][1] == '-'
|| my_index (optstring, *nextchar) == NULL)
{
if (opterr)
{
if (argv[optind][1] == '-')
/* --option */
fprintf (stderr, _("%s: unrecognized option `--%s'\n"),
argv[0], nextchar);
else
/* +option or -option */
fprintf (stderr, _("%s: unrecognized option `%c%s'\n"),
argv[0], argv[optind][0], nextchar);
}
nextchar = (char *) "";
optind++;
optopt = 0;
return '?';
}
}
/* Look at and handle the next short option-character. */
{
char c = *nextchar++;
char *temp = my_index (optstring, c);
/* Increment `optind' when we start to process its last character. */
if (*nextchar == '\0')
++optind;
if (temp == NULL || c == ':')
{
if (opterr)
{
if (posixly_correct)
/* 1003.2 specifies the format of this message. */
fprintf (stderr, _("%s: illegal option -- %c\n"),
argv[0], c);
else
fprintf (stderr, _("%s: invalid option -- %c\n"),
argv[0], c);
}
optopt = c;
return '?';
}
/* Convenience. Treat POSIX -W foo same as long option --foo */
if (temp[0] == 'W' && temp[1] == ';')
{
char *nameend;
const struct option *p;
const struct option *pfound = NULL;
int exact = 0;
int ambig = 0;
int indfound = 0;
int option_index;
/* This is an option that requires an argument. */
if (*nextchar != '\0')
{
optarg = nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
optind++;
}
else if (optind == argc)
{
if (opterr)
{
/* 1003.2 specifies the format of this message. */
fprintf (stderr, _("%s: option requires an argument -- %c\n"),
argv[0], c);
}
optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
return c;
}
else
/* We already incremented `optind' once;
increment it again when taking next ARGV-elt as argument. */
optarg = argv[optind++];
/* optarg is now the argument, see if it's in the
table of longopts. */
for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++)
/* Do nothing. */ ;
/* Test all long options for either exact match
or abbreviated matches. */
for (p = longopts, option_index = 0; p->name; p++, option_index++)
if (!strncmp (p->name, nextchar, nameend - nextchar))
{
if ((unsigned int) (nameend - nextchar) == strlen (p->name))
{
/* Exact match found. */
pfound = p;
indfound = option_index;
exact = 1;
break;
}
else if (pfound == NULL)
{
/* First nonexact match found. */
pfound = p;
indfound = option_index;
}
else
/* Second or later nonexact match found. */
ambig = 1;
}
if (ambig && !exact)
{
if (opterr)
fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"),
argv[0], argv[optind]);
nextchar += strlen (nextchar);
optind++;
return '?';
}
if (pfound != NULL)
{
option_index = indfound;
if (*nameend)
{
/* Don't test has_arg with >, because some C compilers don't
allow it to be used on enums. */
if (pfound->has_arg)
optarg = nameend + 1;
else
{
if (opterr)
fprintf (stderr, _("\
%s: option `-W %s' doesn't allow an argument\n"),
argv[0], pfound->name);
nextchar += strlen (nextchar);
return '?';
}
}
else if (pfound->has_arg == 1)
{
if (optind < argc)
optarg = argv[optind++];
else
{
if (opterr)
fprintf (stderr,
_("%s: option `%s' requires an argument\n"),
argv[0], argv[optind - 1]);
nextchar += strlen (nextchar);
return optstring[0] == ':' ? ':' : '?';
}
}
nextchar += strlen (nextchar);
if (longind != NULL)
*longind = option_index;
if (pfound->flag)
{
*(pfound->flag) = pfound->val;
return 0;
}
return pfound->val;
}
nextchar = NULL;
return 'W'; /* Let the application handle it. */
}
if (temp[1] == ':')
{
if (temp[2] == ':')
{
/* This is an option that accepts an argument optionally. */
if (*nextchar != '\0')
{
optarg = nextchar;
optind++;
}
else
optarg = NULL;
nextchar = NULL;
}
else
{
/* This is an option that requires an argument. */
if (*nextchar != '\0')
{
optarg = nextchar;
/* If we end this ARGV-element by taking the rest as an arg,
we must advance to the next element now. */
optind++;
}
else if (optind == argc)
{
if (opterr)
{
/* 1003.2 specifies the format of this message. */
fprintf (stderr,
_("%s: option requires an argument -- %c\n"),
argv[0], c);
}
optopt = c;
if (optstring[0] == ':')
c = ':';
else
c = '?';
}
else
/* We already incremented `optind' once;
increment it again when taking next ARGV-elt as argument. */
optarg = argv[optind++];
nextchar = NULL;
}
}
return c;
}
}
int
getopt (argc, argv, optstring)
int argc;
char *const *argv;
const char *optstring;
{
return _getopt_internal (argc, argv, optstring,
(const struct option *) 0,
(int *) 0,
0);
}
#endif /* Not ELIDE_CODE. */
#ifdef TEST
/* Compile with -DTEST to make an executable for use in testing
the above definition of `getopt'. */
int
main (argc, argv)
int argc;
char **argv;
{
int c;
int digit_optind = 0;
while (1)
{
int this_option_optind = optind ? optind : 1;
c = getopt (argc, argv, "abc:d:0123456789");
if (c == -1)
break;
switch (c)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (digit_optind != 0 && digit_optind != this_option_optind)
printf ("digits occur in two different argv-elements.\n");
digit_optind = this_option_optind;
printf ("option %c\n", c);
break;
case 'a':
printf ("option a\n");
break;
case 'b':
printf ("option b\n");
break;
case 'c':
printf ("option c with value `%s'\n", optarg);
break;
case '?':
break;
default:
printf ("?? getopt returned character code 0%o ??\n", c);
}
}
if (optind < argc)
{
printf ("non-option ARGV-elements: ");
while (optind < argc)
printf ("%s ", argv[optind++]);
printf ("\n");
}
exit (0);
}
#endif /* TEST */
|
the_stack_data/142252.c | // main.c - first among many [C files in this project]
#include <stdio.h>
int main(int argc, char **argv) {
int sum = add(1, 2);
printf("1 + 2 is %i\n", sum);
return 0;
} |
the_stack_data/182953815.c | /**
* CS250 lab 7
*
**/
#include <stdio.h>
extern int multiply(int m, int n);
int main()
{
int m, n;
printf("Enter first integer:\n");
scanf("%d", &m);
printf("Enter second integer:\n");
scanf("%d", &n);
printf("Output:\n");
printf("%d\n", multiply(m, n));
}
|
the_stack_data/15763309.c | #include <stdio.h>
int main() {
// I think this is right...
println("Hello, world!");
return 0;
}
|
the_stack_data/50138003.c | #include "assert.h"
void loop(int x) {
if (x < 10) {
loop(x + 1);
} else {
__VERIFIER_assert(x >= 0); // safe
__VERIFIER_assert(x <= 10); // safe
__VERIFIER_assert(x == 10); // safe
}
}
void main() {
loop(0);
}
|
the_stack_data/185052.c | #include <stdio.h>
void bubble_sort(int array[], int size)
{
for(int i=1;i<size-1;i++)
{
for(int j=size-1;j>=i;j--)
{
if(array[j]<array[j-1])
{
int sementara = array[j];
array[j] = array[j-1];
array[j-1] = sementara;
}
}
}
for (int i = 0; i < size; ++i)
{
printf("%d ", array[i]);
}
printf("\n\n");
}
void exchange_sort(int data[], int size)
{
for (int i=0;i<size-1;i++)
{
for (int j=(i+1);j<size;j++)
{
if (data[i]>data[j])
{
int sementara = data[i];
data[i] = data[j];
data[j] = sementara;
}
}
}
for (int i = 0; i < size; ++i)
{
printf("%d ", data[i]);
}
printf("\n\n");
}
void main()
{
int data[]={23,65,30,8,33,24,76,7};
int size = sizeof(data) / sizeof(data[0]);
printf("Bubble Sorting\n");
bubble_sort(data, size);
printf("Exchange Sorting\n");
exchange_sort(data, size);
}
|
the_stack_data/11074666.c | #ifdef _WINDOWS
#include <time.h>
#else
#include <unistd.h>
#define sleep(x) usleep((x)*1000)
#endif
|
the_stack_data/93727.c | typedef struct Meow_FFT_Complex
{
float r;
float j;
}
Meow_FFT_Complex;
typedef const Meow_FFT_Complex Complex;
typedef struct Meow_Fft_Stages
{
unsigned count;
unsigned* radix;
unsigned* remainder;
unsigned* offsets;
}
Meow_Fft_Stages;
typedef struct Meow_FFT_Workset
{
int N;
Meow_FFT_Complex* wn;
// Non-null only defined if there is a slow-dft as one of the radix stages.
Meow_FFT_Complex* wn_ordered;
// Sequentially ordered per stage, will be duplicates between stages.
Meow_Fft_Stages stages;
}
Meow_FFT_Workset;
inline Meow_FFT_Complex meow_add
(
const Meow_FFT_Complex lhs
, const Meow_FFT_Complex rhs
)
{
Meow_FFT_Complex result =
{
lhs.r + rhs.r
, lhs.j + rhs.j
};
return result;
}
inline Meow_FFT_Complex meow_sub
(
const Meow_FFT_Complex lhs
, const Meow_FFT_Complex rhs
)
{
Meow_FFT_Complex result =
{
lhs.r - rhs.r
, lhs.j - rhs.j
};
return result;
}
inline Meow_FFT_Complex meow_negate(const Meow_FFT_Complex lhs)
{
Meow_FFT_Complex result =
{
-lhs.r
, -lhs.j
};
return result;
}
inline Meow_FFT_Complex meow_conjugate(const Meow_FFT_Complex lhs)
{
Meow_FFT_Complex result =
{
lhs.r
, -lhs.j
};
return result;
}
inline Meow_FFT_Complex meow_mul
(
const Meow_FFT_Complex lhs
, const Meow_FFT_Complex rhs
)
{
Meow_FFT_Complex result =
{
(lhs.r * rhs.r) - (lhs.j * rhs.j)
, (lhs.r * rhs.j) + (lhs.j * rhs.r)
};
return result;
}
inline Meow_FFT_Complex meow_mul_by_conjugate
(
const Meow_FFT_Complex lhs
, const Meow_FFT_Complex rhs
)
{
Meow_FFT_Complex result =
{
(lhs.r * rhs.r) + (lhs.j * rhs.j)
, (lhs.j * rhs.r) - (lhs.r * rhs.j)
};
return result;
}
inline Meow_FFT_Complex meow_mul_by_j(const Meow_FFT_Complex lhs)
{
Meow_FFT_Complex result =
{
-lhs.j
, lhs.r
};
return result;
}
inline Meow_FFT_Complex meow_mulf
(
const Meow_FFT_Complex lhs
, float rhs
)
{
Meow_FFT_Complex result =
{
lhs.r * rhs
, lhs.j * rhs
};
return result;
}
void meow_dft_n_dit
(
const Meow_FFT_Complex* w_n
, Meow_FFT_Complex* out
, unsigned count
, unsigned w_multiplier
, unsigned radix
, unsigned N
, unsigned reverse
)
{
// Can I do something with the knowledge that n is always odd?
Meow_FFT_Complex scratch[radix];
for (unsigned butterfly = 0; butterfly < count; ++butterfly)
{
for (unsigned i = 0; i < radix; i++)
{
scratch[i] = out[i * count + butterfly];
}
for (unsigned i = 0 ; i < radix ; ++i)
{
const unsigned index_out = i * count + butterfly;
// W0 is always 1
Meow_FFT_Complex sum = scratch[0];
for (unsigned j = 1; j < radix; ++j )
{
const unsigned wi = (j * w_multiplier * index_out) % N;
Complex w = w_n[wi];
Complex in = scratch[j];
float rr;
float jj;
if (reverse)
{
rr = (in.r * w.r) - (in.j * w.j);
jj = (in.r * w.j) + (in.j * w.r);
}
else
{
rr = (in.r * w.r) + (in.j * w.j);
jj = (in.j * w.r) - (in.r * w.j);
}
sum.r += rr;
sum.j += jj;
}
out[index_out] = sum;
}
}
}
// -----------------------------------------------------------------------------
// Algorithms taken from
// http://www.briangough.com/fftalgorithms.pdf
// (equations 135 to 146)
// in, out and twiddle indicies taken from kiss_fft
// All twiddles are assumed to be ifft calculated. Conjugation is done in the
// maths.
// All twiddle input arrays are assumed to be sequentiall accessed. Twiddle
// indicies are pre-calculated.
// -----------------------------------------------------------------------------
// Forward
// -----------------------------------------------------------------------------
void meow_radix_2_dit
(
const Meow_FFT_Complex* w_n
, Meow_FFT_Complex* out
, unsigned count
)
{
// butteryfly 0 always has the twiddle factor == 1.0f
// so special case that one.
{
Complex z0 = out[0];
Complex z1 = out[count];
out[0] = meow_add(z0, z1);
out[count] = meow_sub(z0, z1);
}
for (unsigned butterfly = 1; butterfly < count; ++butterfly)
{
Complex w = w_n[butterfly - 1];
const unsigned i0 = butterfly;
const unsigned i1 = butterfly + count;
Complex z0 = out[i0];
Complex z1 = meow_mul_by_conjugate(out[i1], w);
out[i0] = meow_add(z0, z1);
out[i1] = meow_sub(z0, z1);
// Equation 135
}
}
#define MEOW_SIN_PI_3 -0.866025403784438646763723170752936183471402626905190314f
void meow_radix_3_dit
(
const Meow_FFT_Complex* w_n
, Meow_FFT_Complex* out
, unsigned count
)
{
// W[0] is always 1.0f;
{
const unsigned i0 = 0 * count;
const unsigned i1 = 1 * count;
const unsigned i2 = 2 * count;
Complex z0 = out[i0];
Complex z1 = out[i1];
Complex z2 = out[i2];
Complex t1 = meow_add(z1, z2);
Complex t2 = meow_sub(z0, meow_mulf(t1, 0.5));
Complex t3j = meow_mul_by_j(meow_mulf(meow_sub(z1, z2), MEOW_SIN_PI_3));
out[i0] = meow_add(z0, t1);
out[i1] = meow_add(t2, t3j);
out[i2] = meow_sub(t2, t3j);
}
unsigned wi = 0;
for (unsigned butterfly = 1; butterfly < count; butterfly++, wi+=2)
{
Complex w1 = w_n[wi + 0];
Complex w2 = w_n[wi + 1];
const unsigned i0 = butterfly;
const unsigned i1 = butterfly + count;
const unsigned i2 = butterfly + 2 * count;
Complex z0 = out[i0];
Complex z1 = meow_mul_by_conjugate(out[i1], w1);
Complex z2 = meow_mul_by_conjugate(out[i2], w2);
Complex t1 = meow_add(z1, z2);
Complex t2 = meow_sub(z0, meow_mulf(t1, 0.5));
Complex t3j = meow_mul_by_j(meow_mulf(meow_sub(z1, z2), MEOW_SIN_PI_3));
// Equation 136
out[i0] = meow_add(z0, t1);
out[i1] = meow_add(t2, t3j);
out[i2] = meow_sub(t2, t3j);
// Equation 137
}
}
void meow_radix_4_dit
(
const Meow_FFT_Complex* w_n
, Meow_FFT_Complex* out
, unsigned count
)
{
// W[0] is always 1.0f;
{
const unsigned i0 = 0 * count;
const unsigned i1 = 1 * count;
const unsigned i2 = 2 * count;
const unsigned i3 = 3 * count;
Complex z0 = out[i0];
Complex z1 = out[i1];
Complex z2 = out[i2];
Complex z3 = out[i3];
Complex t1 = meow_add(z0, z2);
Complex t2 = meow_add(z1, z3);
Complex t3 = meow_sub(z0, z2);
Complex t4j = meow_negate(meow_mul_by_j(meow_sub(z1, z3)));
out[i0] = meow_add(t1, t2);
out[i1] = meow_add(t3, t4j);
out[i2] = meow_sub(t1, t2);
out[i3] = meow_sub(t3, t4j);
}
unsigned wi = 0u;
for (unsigned butterfly = 1; butterfly < count; ++butterfly, wi+=3)
{
Complex w1 = w_n[wi + 0];
Complex w2 = w_n[wi + 1];
Complex w3 = w_n[wi + 2];
const unsigned i0 = butterfly + 0 * count;
const unsigned i1 = butterfly + 1 * count;
const unsigned i2 = butterfly + 2 * count;
const unsigned i3 = butterfly + 3 * count;
Complex z0 = out[i0];
Complex z1 = meow_mul_by_conjugate(out[i1], w1);
Complex z2 = meow_mul_by_conjugate(out[i2], w2);
Complex z3 = meow_mul_by_conjugate(out[i3], w3);
Complex t1 = meow_add(z0, z2);
Complex t2 = meow_add(z1, z3);
Complex t3 = meow_sub(z0, z2);
Complex t4j = meow_negate(meow_mul_by_j(meow_sub(z1, z3)));
// Equations 138
// Also instead of conjugating the input and multplying with the
// twiddles for the ifft, we invert the twiddles instead. This works
// fine except here, the mul_by_j is assuming that it's the forward
// fft twiddle we are multiplying with, not the conjugated one we
// actually have. So we have to conjugate it _back_ if we are doing the
// ifft.
// Also, had to multiply by -j, not j for reasons I am yet to grasp.
out[i0] = meow_add(t1, t2);
out[i1] = meow_add(t3, t4j);
out[i2] = meow_sub(t1, t2);
out[i3] = meow_sub(t3, t4j);
// Equations 139
}
}
#define MEOW_SQR_5_DIV_4 0.5590169943749474241022934171828190588601545899028814f
#define MEOW_SIN_2PI_5 -0.9510565162951535721164393333793821434056986341257502f
#define MEOW_SIN_2PI_10 -0.5877852522924731291687059546390727685976524376431459f
void meow_radix_5_dit
(
const Meow_FFT_Complex* w_n
, Meow_FFT_Complex* out
, unsigned count
)
{
// W[0] is always 1.0f;
{
const unsigned i0 = 0 * count;
const unsigned i1 = 1 * count;
const unsigned i2 = 2 * count;
const unsigned i3 = 3 * count;
const unsigned i4 = 4 * count;
Complex z0 = out[i0];
Complex z1 = out[i1];
Complex z2 = out[i2];
Complex z3 = out[i3];
Complex z4 = out[i4];
Complex t1 = meow_add(z1, z4);
Complex t2 = meow_add(z2, z3);
Complex t3 = meow_sub(z1, z4);
Complex t4 = meow_sub(z2, z3);
// Equations 140
Complex t5 = meow_add(t1, t2);
Complex t6 = meow_mulf(meow_sub(t1, t2), MEOW_SQR_5_DIV_4);
Complex t7 = meow_sub(z0, meow_mulf(t5, 0.25f));
// Equation 141
Complex t8 = meow_add(t7, t6);
Complex t9 = meow_sub(t7, t6);
// Equation 142
Complex t10j = meow_mul_by_j
(
meow_add
(
meow_mulf(t3, MEOW_SIN_2PI_5)
, meow_mulf(t4, MEOW_SIN_2PI_10)
)
);
Complex t11j = meow_mul_by_j
(
meow_sub
(
meow_mulf(t3, MEOW_SIN_2PI_10)
, meow_mulf(t4, MEOW_SIN_2PI_5)
)
);
// Equation 143
out[i0] = meow_add(z0, t5);
// Equation 144
out[i1] = meow_add(t8, t10j);
out[i2] = meow_add(t9, t11j);
// Equation 145
out[i3] = meow_sub(t9, t11j);
out[i4] = meow_sub(t8, t10j);
// Equation 146
}
unsigned wi = 0u;
for (unsigned butterfly = 1; butterfly < count; ++butterfly, wi+=4)
{
Complex w1 = w_n[wi + 0];
Complex w2 = w_n[wi + 1];
Complex w3 = w_n[wi + 2];
Complex w4 = w_n[wi + 3];
unsigned i0 = butterfly + 0 * count;
unsigned i1 = butterfly + 1 * count;
unsigned i2 = butterfly + 2 * count;
unsigned i3 = butterfly + 3 * count;
unsigned i4 = butterfly + 4 * count;
Complex z0 = out[i0];
Complex z1 = meow_mul_by_conjugate(out[i1], w1);
Complex z2 = meow_mul_by_conjugate(out[i2], w2);
Complex z3 = meow_mul_by_conjugate(out[i3], w3);
Complex z4 = meow_mul_by_conjugate(out[i4], w4);
Complex t1 = meow_add(z1, z4);
Complex t2 = meow_add(z2, z3);
Complex t3 = meow_sub(z1, z4);
Complex t4 = meow_sub(z2, z3);
// Equations 140
Complex t5 = meow_add(t1, t2);
Complex t6 = meow_mulf(meow_sub(t1, t2), MEOW_SQR_5_DIV_4);
Complex t7 = meow_sub(z0, meow_mulf(t5, 0.25f));
// Equation 141
Complex t8 = meow_add(t7, t6);
Complex t9 = meow_sub(t7, t6);
// Equation 142
Complex t10j = meow_mul_by_j
(
meow_add
(
meow_mulf(t3, MEOW_SIN_2PI_5)
, meow_mulf(t4, MEOW_SIN_2PI_10)
)
);
Complex t11j = meow_mul_by_j
(
meow_sub
(
meow_mulf(t3, MEOW_SIN_2PI_10)
, meow_mulf(t4, MEOW_SIN_2PI_5)
)
);
// Equation 143
out[i0] = meow_add(z0, t5);
// Equation 144
out[i1] = meow_add(t8, t10j);
out[i2] = meow_add(t9, t11j);
// Equation 145
out[i3] = meow_sub(t9, t11j);
out[i4] = meow_sub(t8, t10j);
// Equation 146
}
}
#define MEOW_1_DIV_SQR_2 0.707106781186547524400844362104849039284835938f
static void meow_radix_8_dit
(
const Meow_FFT_Complex* w_n
, Meow_FFT_Complex* out
, unsigned count
)
{
const float* W = &w_n[0].r;
{
float T3;
float T23;
float T18;
float T38;
float T6;
float T37;
float T21;
float T24;
float T13;
float T49;
float T35;
float T43;
float T10;
float T48;
float T30;
float T42;
{
float T1;
float T2;
float T19;
float T20;
T1 = out[0].r;
T2 = out[count * 4].r;
T3 = T1 + T2;
T23 = T1 - T2;
{
float T16;
float T17;
float T4;
float T5;
T16 = out[0].j;
T17 = out[count * 4].j;
T18 = T16 + T17;
T38 = T16 - T17;
T4 = out[count * 2].r;
T5 = out[count * 6].r;
T6 = T4 + T5;
T37 = T4 - T5;
}
T19 = out[count * 2].j;
T20 = out[count * 6].j;
T21 = T19 + T20;
T24 = T19 - T20;
{
float T11;
float T12;
float T31;
float T32;
float T33;
float T34;
T11 = out[count * 7].r;
T12 = out[count * 3].r;
T31 = T11 - T12;
T32 = out[count * 7].j;
T33 = out[count * 3].j;
T34 = T32 - T33;
T13 = T11 + T12;
T49 = T32 + T33;
T35 = T31 - T34;
T43 = T31 + T34;
}
{
float T8;
float T9;
float T26;
float T27;
float T28;
float T29;
T8 = out[count * 1].r;
T9 = out[count * 5].r;
T26 = T8 - T9;
T27 = out[count * 1].j;
T28 = out[count * 5].j;
T29 = T27 - T28;
T10 = T8 + T9;
T48 = T27 + T28;
T30 = T26 + T29;
T42 = T29 - T26;
}
}
{
float T7;
float T14;
float T51;
float T52;
T7 = T3 + T6;
T14 = T10 + T13;
out[count * 4].r = T7 - T14;
out[0].r = T7 + T14;
T51 = T18 + T21;
T52 = T48 + T49;
out[count * 4].j = T51 - T52;
out[0].j = T51 + T52;
}
{
float T15;
float T22;
float T47;
float T50;
T15 = T13 - T10;
T22 = T18 - T21;
out[count * 2].j = T15 + T22;
out[count * 6].j = T22 - T15;
T47 = T3 - T6;
T50 = T48 - T49;
out[count * 6].r = T47 - T50;
out[count * 2].r = T47 + T50;
}
{
float T25;
float T36;
float T45;
float T46;
T25 = T23 + T24;
T36 = MEOW_1_DIV_SQR_2 * (T30 + T35);
out[count * 5].r = T25 - T36;
out[count * 1].r = T25 + T36;
T45 = T38 - T37;
T46 = MEOW_1_DIV_SQR_2 * (T42 + T43);
out[count * 5].j = T45 - T46;
out[count * 1].j = T45 + T46;
}
{
float T39;
float T40;
float T41;
float T44;
T39 = T37 + T38;
T40 = MEOW_1_DIV_SQR_2 * (T35 - T30);
out[count * 7].j = T39 - T40;
out[count * 3].j = T39 + T40;
T41 = T23 - T24;
T44 = MEOW_1_DIV_SQR_2 * (T42 - T43);
out[count * 7].r = T41 - T44;
out[count * 3].r = T41 + T44;
}
}
out = out + 1;
{
unsigned m;
for (m = 1; m < count; m = m + 1, out = out + 1, W = W + 14)
{
float T7;
float T76;
float T43;
float T71;
float T41;
float T65;
float T53;
float T56;
float T18;
float T77;
float T46;
float T68;
float T30;
float T64;
float T48;
float T51;
{
float T1;
float T70;
float T6;
float T69;
T1 = out[0].r;
T70 = out[0].j;
{
float T3;
float T5;
float T2;
float T4;
T3 = out[count * 4].r;
T5 = out[count * 4].j;
T2 = W[6];
T4 = W[7];
T6 = (T2 * T3) + (T4 * T5);
T69 = (T2 * T5) - (T4 * T3);
}
T7 = T1 + T6;
T76 = T70 - T69;
T43 = T1 - T6;
T71 = T69 + T70;
}
{
float T35;
float T54;
float T40;
float T55;
{
float T32;
float T34;
float T31;
float T33;
T32 = out[count * 7].r;
T34 = out[count * 7].j;
T31 = W[12];
T33 = W[13];
T35 = (T31 * T32) + (T33 * T34);
T54 = (T31 * T34) - (T33 * T32);
}
{
float T37;
float T39;
float T36;
float T38;
T37 = out[count * 3].r;
T39 = out[count * 3].j;
T36 = W[4];
T38 = W[5];
T40 = (T36 * T37) + (T38 * T39);
T55 = (T36 * T39) - (T38 * T37);
}
T41 = T35 + T40;
T65 = T54 + T55;
T53 = T35 - T40;
T56 = T54 - T55;
}
{
float T12;
float T44;
float T17;
float T45;
{
float T9;
float T11;
float T8;
float T10;
T9 = out[count * 2].r;
T11 = out[count * 2].j;
T8 = W[2];
T10 = W[3];
T12 = (T8 * T9) + (T10 * T11);
T44 = (T8 * T11) - (T10 * T9);
}
{
float T14;
float T16;
float T13;
float T15;
T14 = out[count * 6].r;
T16 = out[count * 6].j;
T13 = W[10];
T15 = W[11];
T17 = (T13 * T14) + (T15 * T16);
T45 = (T13 * T16) - (T15 * T14);
}
T18 = T12 + T17;
T77 = T12 - T17;
T46 = T44 - T45;
T68 = T44 + T45;
}
{
float T24;
float T49;
float T29;
float T50;
{
float T21;
float T23;
float T20;
float T22;
T21 = out[count * 1].r;
T23 = out[count * 1].j;
T20 = W[0];
T22 = W[1];
T24 = (T20 * T21) + (T22 * T23);
T49 = (T20 * T23) - (T22 * T21);
}
{
float T26;
float T28;
float T25;
float T27;
T26 = out[count * 5].r;
T28 = out[count * 5].j;
T25 = W[8];
T27 = W[9];
T29 = (T25 * T26) + (T27 * T28);
T50 = (T25 * T28) - (T27 * T26);
}
T30 = T24 + T29;
T64 = T49 + T50;
T48 = T24 - T29;
T51 = T49 - T50;
}
{
float T19;
float T42;
float T73;
float T74;
T19 = T7 + T18;
T42 = T30 + T41;
out[count * 4].r = T19 - T42;
out[0].r = T19 + T42;
{
float T67;
float T72;
float T63;
float T66;
T67 = T64 + T65;
T72 = T68 + T71;
out[0].j = T67 + T72;
out[count * 4].j = T72 - T67;
T63 = T7 - T18;
T66 = T64 - T65;
out[count * 6].r = T63 - T66;
out[count * 2].r = T63 + T66;
}
T73 = T41 - T30;
T74 = T71 - T68;
out[count * 2].j = T73 + T74;
out[count * 6].j = T74 - T73;
{
float T59;
float T78;
float T62;
float T75;
float T60;
float T61;
T59 = T43 - T46;
T78 = T76 - T77;
T60 = T51 - T48;
T61 = T53 + T56;
T62 = MEOW_1_DIV_SQR_2 * (T60 - T61);
T75 = MEOW_1_DIV_SQR_2 * (T60 + T61);
out[count * 7].r = T59 - T62;
out[count * 5].j = T78 - T75;
out[count * 3].r = T59 + T62;
out[count * 1].j = T75 + T78;
}
{
float T47;
float T80;
float T58;
float T79;
float T52;
float T57;
T47 = T43 + T46;
T80 = T77 + T76;
T52 = T48 + T51;
T57 = T53 - T56;
T58 = MEOW_1_DIV_SQR_2 * (T52 + T57);
T79 = MEOW_1_DIV_SQR_2 * (T57 - T52);
out[count * 5].r = T47 - T58;
out[count * 7].j = T80 - T79;
out[count * 1].r = T47 + T58;
out[count * 3].j = T79 + T80;
}
}
}
}
}
void meow_recursive_fft_mixed_meow_radix_dit
(
const Meow_FFT_Workset* fft
, unsigned stage
, Complex* in
, Meow_FFT_Complex* out
, unsigned w_mul
)
{
const unsigned radix = fft->stages.radix[stage];
const unsigned count = fft->stages.remainder[stage];
Complex* w = fft->wn;
const unsigned w_offset = fft->stages.offsets[stage];
Complex* w_sequential = &fft->wn_ordered[w_offset];
if (count == 1)
{
for (unsigned i = 0; i < radix; i++)
{
out[i] = in[i * w_mul];
}
}
else
{
const unsigned new_w_multiplier = w_mul * radix;
for (unsigned i = 0; i < radix; ++i)
{
meow_recursive_fft_mixed_meow_radix_dit
(
fft
, stage + 1
, &in[w_mul * i]
, &out[count * i]
, new_w_multiplier
);
}
}
switch (radix)
{
case 2: meow_radix_2_dit(w_sequential, out, count); break;
case 3: meow_radix_3_dit(w_sequential, out, count); break;
case 4: meow_radix_4_dit(w_sequential, out, count); break;
case 5: meow_radix_5_dit(w_sequential, out, count); break;
case 8: meow_radix_8_dit(w_sequential, out, count); break;
default: meow_dft_n_dit(w, out, count, w_mul, radix, fft->N, 0); break;
}
}
void meow_fft
(
const Meow_FFT_Workset* data
, const Meow_FFT_Complex* in
, Meow_FFT_Complex* out
)
{
meow_recursive_fft_mixed_meow_radix_dit
(
data
, 0
, in
, out
, 1
);
}
|
the_stack_data/45449933.c | #include <stdio.h>
#define ABS(a) a >= 0 ? a : -a
int main() {
short hh, mm, ss;
int sec1, sec2, secdiff;
printf("Primo orario:\t");
scanf("%hd:%hd:%hd", &hh, &mm, &ss);
sec1 = 3600 * hh + 60 * mm + ss;
printf("Secodo orario:\t");
scanf("%hd:%hd:%hd", &hh, &mm, &ss);
sec2 = 3600 * hh + 60 * mm + ss;
secdiff = ABS(sec1 - sec2);
hh = secdiff / 3600;
secdiff %= 3600;
mm = secdiff / 60;
ss = secdiff % 60;
printf("Distanza:\t%02d:%02d:%02d\n", hh, mm, ss);
return 0;
}
|
the_stack_data/218892075.c | // Copyright Kani Contributors
// SPDX-License-Identifier: Apache-2.0 OR MIT
#include <assert.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
size_t my_add(size_t num, ...)
{
va_list argp;
va_start(argp, num);
size_t accum = 0;
for (size_t i = 0; i < num; ++i) {
size_t next = va_arg(argp, size_t);
accum += next;
}
va_end(argp);
return accum;
}
int my_add2(size_t num, ...)
{
va_list argp;
va_start(argp, num);
int accum = 0;
for (int i = 0; i < num; ++i) {
int next = va_arg(argp, int);
accum += next;
}
va_end(argp);
return accum;
}
struct Foo {
unsigned int i;
unsigned char c;
}; // __attribute__((packed));
struct Foo2 {
uint32_t i;
uint8_t c;
uint32_t i2;
}; // __attribute__((packed));
uint32_t S = 12;
void update_static() { S++; }
uint32_t takes_int(uint32_t i) { return i + 2; }
uint32_t takes_ptr(uint32_t *p) { return *p + 2; }
uint32_t takes_ptr_option(uint32_t *p)
{
if (p) {
return *p - 1;
} else {
return 0;
}
}
void mutates_ptr(uint32_t *p) { *p -= 1; }
uint32_t name_in_c(uint32_t i) { return i + 2; }
uint32_t takes_struct(struct Foo f) { return f.i + f.c; }
uint32_t takes_struct_ptr(struct Foo *f) { return f->i + f->c; }
uint32_t takes_struct2(struct Foo2 f)
{
assert(sizeof(unsigned int) == sizeof(uint32_t));
return f.i + f.i2;
}
uint32_t takes_struct_ptr2(struct Foo2 *f) { return f->i + f->c; }
|
the_stack_data/73261.c | #include <pthread.h>
#include <stdio.h>
int f1() { return 4; }
int f2() { return 5; }
int (*fp)() = f1;
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
void *t_fun(void *arg) {
pthread_mutex_lock(&mutex1);
fp = f2; // RACE
pthread_mutex_unlock(&mutex1);
return NULL;
}
int main(void) {
pthread_t id;
pthread_create(&id, NULL, t_fun, NULL);
pthread_mutex_lock(&mutex2);
fp(); // RACE
pthread_mutex_unlock(&mutex2);
pthread_join (id, NULL);
return 0;
}
|
the_stack_data/54527.c | #include <threads.h>
static int start_func (void *arg) {
int iarg = *(int *)arg;
return iarg;
}
void main (void) {
thrd_t thr;
int arg = 1;
if (thrd_create(&thr, start_func, (void *)&arg) != thrd_success) {
;
}
}
|
the_stack_data/1245397.c | /* ==========================================================================
* setproctitle.c - Linux/Darwin setproctitle.
* --------------------------------------------------------------------------
* Copyright (C) 2010 William Ahern
* Copyright (C) 2013 Salvatore Sanfilippo
* Copyright (C) 2013 Stam He
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
* ==========================================================================
*/
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stddef.h> /* NULL size_t */
#include <stdarg.h> /* va_list va_start va_end */
#include <stdlib.h> /* malloc(3) setenv(3) clearenv(3) setproctitle(3) getprogname(3) */
#include <stdio.h> /* vsnprintf(3) snprintf(3) */
#include <string.h> /* strlen(3) strchr(3) strdup(3) memset(3) memcpy(3) */
#include <errno.h> /* errno program_invocation_name program_invocation_short_name */
#if !defined(HAVE_SETPROCTITLE)
#if (defined __NetBSD__ || defined __FreeBSD__ || defined __OpenBSD__ || defined __DragonFly__)
#define HAVE_SETPROCTITLE 1
#else
#define HAVE_SETPROCTITLE 0
#endif
#endif
#if !HAVE_SETPROCTITLE
#if (defined __linux || defined __APPLE__)
#ifdef __GLIBC__
#define HAVE_CLEARENV
#endif
extern char **environ;
static struct {
/* original value */
const char *arg0;
/* title space available */
char *base, *end;
/* pointer to original nul character within base */
char *nul;
_Bool reset;
int error;
} SPT;
#ifndef SPT_MIN
#define SPT_MIN(a, b) (((a) < (b))? (a) : (b))
#endif
static inline size_t spt_min(size_t a, size_t b) {
return SPT_MIN(a, b);
} /* spt_min() */
/*
* For discussion on the portability of the various methods, see
* http://lists.freebsd.org/pipermail/freebsd-stable/2008-June/043136.html
*/
int spt_clearenv(void) {
#ifdef HAVE_CLEARENV
return clearenv();
#else
extern char **environ;
static char **tmp;
if (!(tmp = malloc(sizeof *tmp)))
return errno;
tmp[0] = NULL;
environ = tmp;
return 0;
#endif
} /* spt_clearenv() */
static int spt_copyenv(int envc, char *oldenv[]) {
extern char **environ;
char **envcopy = NULL;
char *eq;
int i, error;
int envsize;
if (environ != oldenv)
return 0;
/* Copy environ into envcopy before clearing it. Shallow copy is
* enough as clearenv() only clears the environ array.
*/
envsize = (envc + 1) * sizeof(char *);
envcopy = malloc(envsize);
if (!envcopy)
return ENOMEM;
memcpy(envcopy, oldenv, envsize);
/* Note that the state after clearenv() failure is undefined, but we'll
* just assume an error means it was left unchanged.
*/
if ((error = spt_clearenv())) {
environ = oldenv;
free(envcopy);
return error;
}
/* Set environ from envcopy */
for (i = 0; envcopy[i]; i++) {
if (!(eq = strchr(envcopy[i], '=')))
continue;
*eq = '\0';
error = (0 != setenv(envcopy[i], eq + 1, 1))? errno : 0;
*eq = '=';
/* On error, do our best to restore state */
if (error) {
#ifdef HAVE_CLEARENV
/* We don't assume it is safe to free environ, so we
* may leak it. As clearenv() was shallow using envcopy
* here is safe.
*/
environ = envcopy;
#else
free(envcopy);
free(environ); /* Safe to free, we have just alloc'd it */
environ = oldenv;
#endif
return error;
}
}
free(envcopy);
return 0;
} /* spt_copyenv() */
static int spt_copyargs(int argc, char *argv[]) {
char *tmp;
int i;
for (i = 1; i < argc || (i >= argc && argv[i]); i++) {
if (!argv[i])
continue;
if (!(tmp = strdup(argv[i])))
return errno;
argv[i] = tmp;
}
return 0;
} /* spt_copyargs() */
void spt_init(int argc, char *argv[]) {
char **envp = environ;
char *base, *end, *nul, *tmp;
int i, error, envc;
if (!(base = argv[0]))
return;
nul = &base[strlen(base)];
end = nul + 1;
for (i = 0; i < argc || (i >= argc && argv[i]); i++) {
if (!argv[i] || argv[i] < end)
continue;
end = argv[i] + strlen(argv[i]) + 1;
}
for (i = 0; envp[i]; i++) {
if (envp[i] < end)
continue;
end = envp[i] + strlen(envp[i]) + 1;
}
envc = i;
if (!(SPT.arg0 = strdup(argv[0])))
goto syerr;
#if __GLIBC__
if (!(tmp = strdup(program_invocation_name)))
goto syerr;
program_invocation_name = tmp;
if (!(tmp = strdup(program_invocation_short_name)))
goto syerr;
program_invocation_short_name = tmp;
#elif __APPLE__
if (!(tmp = strdup(getprogname())))
goto syerr;
setprogname(tmp);
#endif
if ((error = spt_copyenv(envc, envp)))
goto error;
if ((error = spt_copyargs(argc, argv)))
goto error;
SPT.nul = nul;
SPT.base = base;
SPT.end = end;
return;
syerr:
error = errno;
error:
SPT.error = error;
} /* spt_init() */
#ifndef SPT_MAXTITLE
#define SPT_MAXTITLE 255
#endif
void setproctitle(const char *fmt, ...) {
char buf[SPT_MAXTITLE + 1]; /* use buffer in case argv[0] is passed */
va_list ap;
char *nul;
int len, error;
if (!SPT.base)
return;
if (fmt) {
va_start(ap, fmt);
len = vsnprintf(buf, sizeof buf, fmt, ap);
va_end(ap);
} else {
len = snprintf(buf, sizeof buf, "%s", SPT.arg0);
}
if (len <= 0)
{ error = errno; goto error; }
if (!SPT.reset) {
memset(SPT.base, 0, SPT.end - SPT.base);
SPT.reset = 1;
} else {
memset(SPT.base, 0, spt_min(sizeof buf, SPT.end - SPT.base));
}
len = spt_min(len, spt_min(sizeof buf, SPT.end - SPT.base) - 1);
memcpy(SPT.base, buf, len);
nul = &SPT.base[len];
if (nul < SPT.nul) {
*SPT.nul = '.';
} else if (nul == SPT.nul && &nul[1] < SPT.end) {
*SPT.nul = ' ';
*++nul = '\0';
}
return;
error:
SPT.error = error;
} /* setproctitle() */
#endif /* __linux || __APPLE__ */
#endif /* !HAVE_SETPROCTITLE */
|
Subsets and Splits