Another C question - c

I have a piece of code shown below
#include <stdio.h>
#include <stdlib.h>
void Advance_String(char [2],int );
int Atoi_val;
int Count_22;
int Is_Milestone(char [2],int P2);
char String[2] = "0";
main()
{
while(1)
{
if(Is_Milestone(String,21)==1)
{
if(atoi(String)==22)
{
Count_22 = Count_22 + 1;
}
}
Atoi_val = atoi(String);
Advance_String(S,Atoi_val);
}
}
int Is_Milestone(char P1[2],int P2)
{
int BoolInit;
char *Ptr = P1;
int value = atoi(Ptr);
BoolInit = (value > P2);
return BoolInit;
}
void Advance_String(char P1[2],int Value)
{
if(Value!=7)
{
P1[1] = P1[1]+1;
}
else
{
P1[1] = '0';
P1[0] = P1[0]+1 ;
}
}
Now my problem is Count_22 never increments as the char increments never achieves the value 21 or above.Could anyone please tell me the reason for this unexpected behaviour?My question here is to find the value of Count_22.Is there any problem with the code?
Thanks and regards,
Maddy

Your code is probably one of the worst pieces of C code i've ever seen (no offense, everybody has to learn sometime).
It has syntax errors (maybe copy/paste problem), logical problems, meaningless obfuscation, bad practices (globals), buffer overflow (atoi used on a char where there is no place to store the terminating zero byte), uninitialized values (Count_22), surprising naming convention (mixed CamelCase and underscore, variables and functions beginning with capital letter), infinite loop, no header and I forget some.
More, if you want anyone to help you debug this code, you should at list say what it is supposed to do...
To answer to the original question: why Count_22 is never incremented ?
Because Is_Milestone is always false (with or without #Jay change). Is_Milestone intend seems to be to compare the decimal value of the string "22" with the integer 21 (or 1, boolean result of 21 == 1) depending on the version).
It's logical because of Advance_String behavior. both because String has bad initial value (should probably be char String[3] = "00";) and because of the Value != 7 test. I guess what you wanted was comparing the digit with 7, but atoi works with a full string. Another minor change to achieve that Atoi_val = atoi(String+1); in the body of your loop. Then again you won't see much as the loop never stop and never print anything.
If it is a first attempt at an exercice given by some teacher (something like "programming a two digit counter in base 7" or similar). You should consider not using atoi at all and converting characters digit to value using something like:
digit_value = char_value - '0';
example:
char seven_as_char = '7';
int seven_as_int = seven_as_char - '0';
If you can explain what you are really trying to do, we may be able to show you some simple sample code, instead of the horror you are trying to debug.
EDIT
It is really more simple with original code...
After reading the Ada source, I can confirm it is indeed an Ascii based octal counter. The original code is allready of poor quality, and that explains part of the bad quality of the resulting C code.
A possible direct port could be as following (but still need a serious cleanup to look like native C code... and is quite dumb anyway as it prints a constant):
#include <stdio.h>
#include <stdlib.h>
void Advance_String(char * P1)
{
if((P1[1]-'0') != 7){
P1[1]++;
}
else{
P1[1] = '0';
P1[0]++ ;
}
}
int Is_Milestone(char * P1, int P2)
{
return (atoi(P1) > P2);
}
main()
{
int Count_11 = 0;
int Count_22 = 0;
int Count_33 = 0;
int Count_44 = 0;
char S[3] = "00";
int cont = 1;
while(cont)
{
if(Is_Milestone(S, 10)){
if(atoi(S) == 11){
Count_11 = Count_11 + 1;
}
if(Is_Milestone(S, 21)){
if(atoi(S) == 22){
Count_22 = Count_22 + 1;
}
if(Is_Milestone(S, 32)){
if(atoi(S) == 33){
Count_33 = Count_33 + 1;
}
if(Is_Milestone(S, 43)){
if(atoi(S) == 44){
Count_44 = Count_44 + 1;
}
if (atoi(S) == 77){
cont = 0;
}
}
}
}
}
Advance_String(S);
}
printf("result = %d\n", Count_11 + Count_22 + Count_33 + Count_44);
}

This statement
if(Is_Milestone(S,21==1) // Braces are not matching. If statement is not having the closing brace. Compilation error should be given.
should be
if(Is_Milestone(S,21)==1)
I guess.
Also, the code you have posted doesn't seem to be correct. It will surely give compilation errors. You have declared Count22, but are using Count_22.
Please check.

Related

Identify User Defined Function and Library Defined Function

I'm given a task to write a program that checks a piece of code, maximum of 20 lines of code, when the program runs you type in a function name, number of lines of code and type in the codes.
It's meant to search in the code and return if the function name you entered is a Library Function or User Defined Function or No Function if it doesn't find it, the code I've written is below, it doesn't work because I made mistakes and I've been trying to fix it but can't seem to figure it out, and I tried debugging to see where I made mistake, and I figured that in the function SearchRealisation it returns an error that
Run-Time Check Failure #2 - Stack around the variable 'buff' was
corrupted.
This program sample returns Library function instead of user defined function
type the function name: addition
Get count string in code: 9
int addition(int num1, int num2)
{
int result = num1 + num2; //trial
return result;
}
int main()
{
addition(8, 9);
}
Output is Library Function but correct output should be User Defined Function since it was defined in the code
void InputText(int length, char Text[MAX_STRINGS][MAX_COLUMNS])
{
//Repeat by Count String
gets_s(Text[0]);
for (int i = 0; i < length; i++)
gets_s(Text[i]);
//Output a string (starting with � zero and ending with Count String-1)
}
void OutMesseg(int param)
{
//Display one of three messages according to the parameter
if (param == -2)
printf("%s", "user defined function");
else if (param == -1)
printf("%s", "no function");
else
printf("%s", "library function");
}
char* DeleteComentsInString(char Text[MAX_STRINGS], char New[MAX_STRINGS])
{
char* a = strstr(Text, "//");
int len = strlen(Text);
if (a != NULL) len -= strlen(a);
strncpy(New, Text, len);
New[len] = '\0';
return New;
}
bool IsTypeC(char Word[MAX_STRINGS])
{
char ctype[6][MAX_STRINGS] =
{
"int",
"bool",
"char",
"float",
"double",
"void"
};
for (int i = 0; i < 6; i++)
{
if (strstr(Word, ctype[i]) != 0)
return true;
}
return false;
}
int SearchRealisation(int length, char Text[MAX_STRINGS][MAX_COLUMNS], int index_fanc, int& end)
{
int count = 0;
int start = -1;
end = -1;
char buff[MAX_STRINGS];
//Find first {
for (int i = index_fanc + 1; i < length && !count; i++)
{
if (strstr(DeleteComentsInString(Text[i], buff), "{") != NULL)
{
count++;
start = i;
}
}
//find last }
for (int i = start + 1; i < length && count; i++)
{
if (strstr(DeleteComentsInString(Text[i], buff), "{") != NULL)
count++;
else if (strstr(DeleteComentsInString(Text[i], buff), "}") != NULL)
count--;
if (!count)
end = i;
}
if (end == -1)
start = -1;
else
return start;
}
int SearchFunction(int length, char Text[MAX_STRINGS][MAX_COLUMNS], char FunctionName[MAX_COLUMNS], int& end)
{
//bool flag = false;
char commentDel[120];
int in;
for (int i = 0; i < length; ++i)
{
DeleteComentsInString(Text[i], commentDel);
if (strstr(commentDel, FunctionName) != NULL)
{
in = strlen(commentDel) - strlen(strstr(commentDel, FunctionName));
if ((in == 0 || (in != 0 && commentDel[in - 1] == ' ')) && (commentDel[in + strlen(FunctionName)] == ' ' || commentDel[in + strlen(FunctionName)] == '(') && strstr(commentDel, ";") == NULL)
{
return SearchRealisation(length, Text, i, end);
}
}
}
end = -1;
return -1;
}
int SearchResult(int length, char Text[MAX_STRINGS][MAX_COLUMNS], char FunctionName[MAX_COLUMNS])
{
int index;
int end;
int start = SearchFunction(length, Text, FunctionName, end);
if (start == -1)
return -1;
index = SearchFunction(length, Text, FunctionName, end);
if (index < 0)
return -2;
return index;
}
int findFunction(char string[MAX_STRINGS][MAX_COLUMNS], char* functName, int M)
{
return 0;
}
int main()
{
int length = 0;
char Code[MAX_STRINGS][MAX_COLUMNS] = { 0 };
char FunctionName[MAX_COLUMNS];
//char ConstantName[MAX_STRINGS];
printf("type the function name: ");
scanf("%s", &FunctionName);
printf("Get count string in code: ");
scanf("%d", &length);
InputText(length, Code);
printf("\n");
OutMesseg(SearchResult(length, Code, FunctionName));
return 0;
}
Well, you have been given a very difficult task:
There's no way to check this, as functions are resolved by a dynamic process that depends on your filesystem state, which is not available at runtime, after you have already compiled your program.
How do you distinguish a function that is compiled in a separate (but user defined) compilation unit from a system defined function? (e.g. double log(double);) that is defined in a math library? There is no way: the linker gets both from a different place (in the first case it gets it from the place you compiled the separate module, in the system case it gets it from a common library directory that has all the system related functions), but you don't have that information available at runtime).
In order to do this task feasible, you'd at least have the full set of source code files of your program. Preprocess them with the cpp(1) preprocessor (so you bypass all the macro expansion invocations) and then check for all function calls in the source code that are not provided in the full set of sources you have. This is quite similar to what the linker does. After compilation, the compiler leaves an object file with the compiled code, and a symbol table that identifies all the unresolved identifiers, and more important all the provided identifiers from this module. The linker then goes on all your modules trying to solve the unknowns, and for each that it doesn't have a solution in your code, it goes to the library directory to search for it. If it doesn't find it in either one, it fails telling you something is wrong.
In my opinion, you have been given a trap task, as the C language preprocess its input (this is something you should do, as many functions are hidden in the internals of macro bodies), then parse the code (for this, you need to write a C parser, which is no trivial task) to select which identifiers are defined in your code and which aren't. Finally you need to check all the calls you do in the code to divide the set in two groups, calls that are defined (and implemented) in your code, and calls that aren't (implemented, all the calls the compiler needs must be defined with some kind of prototype).
It's my opinion, but you have not a simple task, solvable in a short program (of perhaps one hundred lines) but a huge one.
Thanks a lot to everyone that answered I came up with a way to search the code for function definition and thereby return a value if its defined or not, or not even found, might not be the best solution to the task but works so far

Dynamically allocate and initialize new object with 30% probability

I'm writing a program that will simulate a randomized race between runners who are climbing up a mountain where dwarf orcs (dorcs) are coming down the mountain to attack the runners. It begins with two runners named harold and timmy at the bottom of the mountain. The runners make their way up the mountain in randomized moves where they may make progress forward up the mountain, or they may slide back down the mountain. Dorcs are randomly generated, and they inflict damage on a runner if they collide. The simulation ends when one of the runners reaches the top of the mountain, or when both runners are dead.
I'm struggling with a part where I have to implement the actual race loop. Once the race is initialized, the race loop will iterate until the race is over. This happens when either a winner has been declared, or when all runners are dead.
Every iteration of the race loop will do the following:
with 30% probability, dynamically allocate a new dorc as an EntityType structure, and initialize it as follows:
(a) a dorc’s avatar is always “d”
(b) each dorc begins the race at the top of the mountain, which is at row 2
(c) with equal probability, the dorc may be placed either in the same column as timmy, or in the same column as the harold, or in the column exactly half-way between the two
(d) add the new dorc to the race’s array of dorcs
(e) using the pthread_create() function, create a thread for the new dorc, and save the thread pointer in the dorc’s entity structure; the function that each dorc thread will execute is the void* goDorc(void*) function that you will implement in a later step; the parameter to the goDorc() function will be the EntityType pointer that corresponds to that dorc
I guess I'm confused with the logic of how to approach this. I decided to make a function called isOver() to indicate if the race is over, and then a separate function called addDorc() to initialize the Dorc elements and do all the requirements above.
In isOver(), I attempt to add a dorc object to the dorcs array by doing addDorc(race); with every iteration of the race loop/if the race hasn't ended or no one died. But I keep getting the error:
control.c:82:3: error: too few arguments to function ‘addDorc’
addDorc(race);
The problem is I don't think I can manually declare all the parameters in addDorc() because some elements like the "path" argument are based on probability. As mentioned above, with equal probability, the dorc may be placed either in the same column as timmy, or in the same column as the harold, or in the column exactly half-way between the two. The issue is I don't know how to factor this random value when calling addDorc() and would appreciate some help. I also don't know if I'm doing the "with 30% probability, dynamically allocate a new dorc as an EntityType structure" correctly and would be grateful for some input on that as well.
defs.h
typedef struct {
pthread_t thr;
char avatar[MAX_STR];
int currPos;
int path;
} EntityType;
typedef struct {
EntityType ent;
char name[MAX_STR];
int health;
int dead;
} RunnerType;
typedef struct {
int numRunners;
RunnerType *runners[MAX_RUNNERS];
int numDorcs;
EntityType *dorcs[MAX_DORCS];
char winner[MAX_STR];
int statusRow;
sem_t mutex;
} RaceInfoType;
void launch();
int addDorc(RaceInfoType*, char*, int, int);
int isOver(RaceInfoType*);
void initRunners(RaceInfoType*);
int addRunner(RaceInfoType*, char*, char*, int, int, int, int);
int randm(int);
void *goRunner(void*);
void *goDorc(void*);
RaceInfoType *race;
control.c
void launch(){
race = malloc(sizeof(RaceInfoType));
race->numRunners = 0;
initRunners(race);
if (sem_init(&race->mutex, 0, 1) < 0) {
printf("semaphore initialization error\n");
exit(1);
}
strcpy(race->winner, " ");
srand((unsigned)time(NULL));
int i;
for(i = 0; i < race->numRunners; ++i){
pthread_create(&(race->runners[i]->ent.thr), NULL, goRunner, " ");
}
race->numDorcs = 0;
}
int addDorc(RaceInfoType* race, char *avatar, int path, int currPos){
if(race->numDorcs == MAX_DORCS){
printf("Error: Maximum dorcs already reached. \n");
return 0;
}
race->dorcs[race->numDorcs] = malloc(sizeof(EntityType));
int timmysColumn = race->dorcs[race->numDorcs]->currPos;
int haroldsColumn = race->dorcs[race->numDorcs]->currPos;
int halfwayColumn = (timmysColumn+haroldsColumn)/2;
int r = rand()%100;
pthread_t dorc;
if(r <= 30){
strcpy(race->dorcs[race->numDorcs]->avatar, "d");
race->dorcs[race->numDorcs]->currPos = 2;
if(r <= 33){
race->dorcs[race->numDorcs]->path = timmysColumn;
}else if(r <= 66){
race->dorcs[race->numDorcs]->path = haroldsColumn;
}else{
race->dorcs[race->numDorcs]->path = halfwayColumn;
}
pthread_create(&dorc, NULL, goDorc, " ");
}
race->numRunners++;
}
int isOver(RaceInfoType* race){
int i;
for(i = 0; i < race->numRunners; ++i){
if((race->winner != " ") || (race->runners[race->numRunners]->dead = 1)){
return 1;
}
addDorc(race);
return 0;
}
}
void initRunners(RaceInfoType* r){
addRunner(r, "Timmy", "T", 10, 35, 50, 0);
addRunner(r, "Harold", "H", 14, 35, 50, 0);
}
int addRunner(RaceInfoType* race, char *name, char *avatar, int path, int currPos, int health, int dead){
if(race->numRunners == MAX_RUNNERS){
printf("Error: Maximum runners already reached. \n");
return 0;
}
race->runners[race->numRunners] = malloc(sizeof(RunnerType));
strcpy(race->runners[race->numRunners]->name, name);
strcpy(race->runners[race->numRunners]->ent.avatar, avatar);
race->runners[race->numRunners]->ent.path = path;
race->runners[race->numRunners]->ent.currPos = currPos;
race->runners[race->numRunners]->health = health;
race->runners[race->numRunners]->dead = dead;
race->numRunners++;
return 1;
}
Caveat: Because there's so much missing [unwritten] code, this isn't a complete solution.
But, I notice at least two bugs: the isOver bugs in my top comments. And, incrementing race->numRunners in addDorc.
isOver also has the return 0; misplaced [inside the loop]. That should go as the last statement in the function. If you had compiled with -Wall [which you should always do], that should have been flagged by the compiler (e.g. control reaches end of non-void function)
From that, only one "dorc" would get created (for the first eligible runner). That may be what you want, but [AFAICT] you want to try to create more dorcs (one more for each valid runner).
Also, the bug the compiler flagged is because you're calling addDorc(race); but addDorc takes more arguments.
It's very difficult to follow the code when you're doing (e.g.) race->dorcs[race->numDorcs]->whatever everywhere.
Better to do (e.g.):
EntityType *ent = &race->dorcs[race->numDorcs];
ent->whatever = ...;
Further, it's likely that your thread functions would like a pointer to their [respective] control structs (vs. just passing " ").
Anyway, I've refactored your code to incorporate these changes. I've only tried to fix the obvious/glaring bugs from simple code inspection, but I've not tried to recompile or address the correctness of your logic.
So, there's still more work to do, but the simplifications may help a bit.
void
launch(void)
{
race = malloc(sizeof(RaceInfoType));
race->numRunners = 0;
initRunners(race);
if (sem_init(&race->mutex,0,1) < 0) {
printf("semaphore initialization error\n");
exit(1);
}
strcpy(race->winner," ");
srand((unsigned)time(NULL));
int i;
for (i = 0; i < race->numRunners; ++i) {
RunnerType *run = &race->runners[i];
EntityType *ent = &run->ent;
pthread_create(&ent->thr,NULL,goRunner,ent);
}
race->numDorcs = 0;
}
int
addDorc(RaceInfoType* race,char *avatar,int path,int currPos)
{
if (race->numDorcs == MAX_DORCS) {
printf("Error: Maximum dorcs already reached. \n");
return 0;
}
EntityType *ent = malloc(sizeof(*ent));
race->dorcs[race->numDorcs] = ent;
int timmysColumn = ent->currPos;
int haroldsColumn = ent->currPos;
int halfwayColumn = (timmysColumn + haroldsColumn) / 2;
int r = rand()%100;
#if 0
pthread_t dorc;
#endif
if (r <= 30) {
strcpy(ent->avatar,"d");
ent->currPos = 2;
if (r <= 33) {
ent->path = timmysColumn;
} else if (r <= 66) {
ent->path = haroldsColumn;
} else {
ent->path = halfwayColumn;
}
pthread_create(&ent->thr,NULL,goDorc,ent);
}
#if 0
race->numRunners++;
#else
race->numDorcs += 1;
#endif
}
int
isOver(RaceInfoType* race)
{
int i;
for (i = 0; i < race->numRunners; ++i) {
#if 0
if ((race->winner != " ") ||
(race->runners[race->numRunners]->dead = 1))
return 1;
#else
RunnerType *run = &race->runners[i];
if ((race->winner != " ") || (run->dead == 1))
return 1;
#endif
addDorc(race);
#if 0
return 0;
#endif
}
#if 1
return 0;
#endif
}
void
initRunners(RaceInfoType* r)
{
addRunner(r,"Timmy","T",10,35,50,0);
addRunner(r,"Harold","H",14,35,50,0);
}
int
addRunner(RaceInfoType* race,char *name,char *avatar,int path,int currPos,
int health,int dead)
{
if (race->numRunners == MAX_RUNNERS) {
printf("Error: Maximum runners already reached. \n");
return 0;
}
RunnerType *run = malloc(sizeof(*run));
race->runners[race->numRunners] = run;
strcpy(run->name,name);
EntityType *ent = &run->ent;
strcpy(ent->avatar,avatar);
ent->path = path;
ent->currPos = currPos;
run->health = health;
run->dead = dead;
race->numRunners++;
return 1;
}
UPDATE:
I noticed in addDorc(), you put pthread_t dorc; in an if statement. I don't quite understand what my if statement is actually supposed to be checking though.
I forgot to mention/explain. I wrapped your/old code and my/new code with preprocessor conditionals (e.g.):
#if 0
// old code
#else
// new code
#endif
After the cpp stage, the compiler will only see the // new code stuff. Doing this was an instructional tool to show [where possible] what code you had vs what I replaced it with. This was done to show the changes vs. just rewriting completely.
If we never defined NEVERWAS with a #define NEVERWAS, then the above block would be equivalent to:
#ifdef NEVERWAS
// old code ...
#else
// new code
#endif
Would it still be under the if(r <= 30) part like I did in my original code?
Yes, hopefully now, it is more clear. #if is a cpp directive to include/exclude code (as if you had edited that way). But, a "real" if is an actual executable statement that is evaluated at runtime [as it was before], so no change needed.
My other concern is it doesn't look like dorc is used anywhere in the function because you write pthread_create(&ent->thr,NULL,goDorc,ent); which seems to use ent instead?
That is correct. It is not used/defined and the value goes to ent->thr. As you had it, the pthread_t value set by pthread_create would be lost [when dorc goes out of scope]. So, unless it's saved somewhere semi-permanent (e.g. in ent->thr), there would be no way to do a pthread_join call later.

What is Best way concatenate strings and number - Performance Using C?

Please go down and read new/last update section.
i very try to write a code with good performance.
but also php interpreter script is more fast of my c app.
i am test this in a big loop. and i sure then speed of my concatenate code is bad.
and sure then can make this better like php script.
Complate Source(c):
for(int count=1;count<=1000000;count++)
{
results=str_int("New Item",count);
}
str_int(...) Function :
#1 :
DATA_VALUE_String *str_int(DATA_VALUE_String *s1,DATA_VALUE_Int64 s2)
{
DATA_VALUE_String *result=malloc(sizeof(s1)+sizeof(s2)+2*sizeof(DATA_VALUE_String *));
snprintf(result,sizeof(s2)+sizeof(s2),"%s%d",s1,s2);
return result;
}
Time : 0m0.135s
#2 :
DATA_VALUE_String *str_int(DATA_VALUE_String *s1,DATA_VALUE_Int64 s2)
{
DATA_VALUE_String *result=malloc(sizeof(s1)+sizeof(s2)+2*sizeof(DATA_VALUE_String *));
DATA_VALUE_String *ss2;
ss2=malloc((sizeof(s2)+2)*sizeof(DATA_VALUE_String *));
sprintf(ss2,"%"PRId64,s2);
strcat(strcpy(result,s1),ss2);
return result;
}
Time : 0m0.160s
But Php 7.1.4 : 0.081s
<?php
//$myArrays = [];
for($count=1;$count<=1000000;$count++)
{
$results="";
$results="New Item".$count;
}
//unset($myArrays);
?>
please help me to make this c file more fast...
i want make my c code better.
php have more performance in concatenate string,int.
but my c code is not like them.
how can make this better?
tank you very much. :like:
=============
New Update for Answer 1:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
void int64ToChar(char **mesg, int64_t num) {
//*mesg="..";
*(int64_t *)mesg = num;
}
int main()
{
int64_t num=4694;
char *nums=malloc(6*sizeof(char *));
int64ToChar(&nums,num);
printf("%s",nums);
return 0;
}
Error : Segmentation fault (core dumped)
New/Last Update for Bad Performance (C vs PHP)
php(last version) : http://codepad.org/9D26wLEA
$ time php arrays2.php
real 0m0.089s
user 0m0.086s
sys 0m0.004s
c : http://codepad.org/JmemaXOr
$ gcc arrays.c -o arrays -O3 -w
$ time ./arrays
real 0m0.131s
user 0m0.091s
sys 0m0.040s
How can make my C file better?
You can try to concatenate strings in C by directly adding the second string to the end of the first string in memory via pointers.
char* strConcat(char* str1,char* str2){
while (*str1) str1++;
do{
*str1++ = *str2++
}while (*str2);
return --str1; //return a pointer to the end of the new string
}
This returns a pointer to the end of the new concatenated string so you can just pass the pointer along to continue to concatenate to this current string. Alternately, if no further concatenation is necessary, you can maintain the pointer to the head of the concatenated string.
Someone gave an algorithm much faster than snprintf for converting an int to a string :
How to convert an int to string in C
This algo (I named it xitoa below) is also faster than the PHP script.
(I tested with int32, rather than int64, but it illustrates a significant improvement over snprintf)
My benchmark:
with snprintf: 1.54s
with xitoa: 0.99s
with PHP: 1.23s
These results were obtained with gcc optimization -O2 (for snprintf and xitoa).
Here is the algo that I tested (copied from the given link):
char * xitoa (int value, char *buffer, int base)
{
// check that the base if valid
if (base < 2 || base > 36) { *buffer = '\0'; return buffer; }
char* ptr = buffer, *ptr1 = buffer, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
// reverse the characters, as they were stored less-significant first
while (ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return buffer;
}

Find Verbs in a String

I am trying (and having trouble) to write a program (In C) that accepts a string in the command line (eg. $ test.out "This is a string") and looks through the string to find verbs (and nouns, but if I figure out verbs, I can do nouns on my own).
A list of aplphabetically sorted verbs is given in the file lexicon.h, and is what I am supposed to use as my dictionary.
I know how to accept the string from the command line and use that input to create an array of strings, each string itself being a separate word, and I already have a working program that can do that, and that I hope to use part of for this one.
I am supposed to create a function called binary_search(...stuffgoeshere...) and use that to search through the lexicon file and find the verb.
I would like some suggestions or guidance on how to create a function (binary_search) that can check to see if an already separated word matches any on the list in lexicon.h. I do not want someone to just write an answer, I would like to know why you are suggesting what you do. Hopefully I can learn something fun out of this!
I know it's messy, but this is what I have so far.
Also note that lexicon's verb array has 637 values (as seen when I make int size = 637)
This program does not compile anymore, as I have not yet figured out how to make the binary_search function work yet. I am trying to modify a binary search function used in an example for class, however, that one sorted numbers in a text file, not strings of characters.
If there is anything else I should include, let me know. Thank you for your help!
#include <stdio.h>
#include <string.h>
#include "lexicon.h"
int binary_search(char word[], char verbs[][], int size);
int
main(int argc, char*argv[])
{
char word[80];
char str[80],
args[80][80];
int counter = 0,
a = 0,
i = 0,
index = 0,
t = 0;
while(str[a] != '\0')
{
if(str[a] == ' ')
{
args[index][i] = '\0';
i = 0;
a++;
index ++;
counter ++;
}
args[index][i++] = str[a++];
}
args[index][i] = '\0';
counter = counter + 1;
printf("\nThe verbs were: ");
int verbposition= -1;
int size = 637;
while(t<counter)
{
strcpy(word, args[t]);
verbposition = binary_search(word, verbs, size);
if(verbposition > -1)
printf("%s", args[t]);
t++;
}
return 0;
}
int
binary_search(char word[], char &verbs[][], int size)
{
int bottom = 0,
top = size - 1,
found = 0,
middle;
while(bottom <= top && !found)
{
middle = (bottom + top) / 2;
if(strcmp(word, verbs[middle]))
{
found = 1;
return = middle;
}
if(strcmp(word, verbs[middle]) > 0)
{
top = middle - 1;
}
else
bottom = middle + 1;
}
return -1;
}
You are on the right track. I would highly suggest you to use print statements as you will have a clear idea of where you are going wrong.

Fastest way to print a certain number of characters to stdout in C

I have to print a certain number of blank spaces to stdout, but this number is not fixed. I'm using putchar(), but I'm not sure if this is fast. What is the fastest way to print a certain number of characters to stdout in C? Also, I cannot use system functions.
Thanks for you help!
I would just use fwrite. Simple. Correct. Easy.
void put_spaces(int n)
{
static const char SPACES[32] = " ";
for (; n >= 32; n -= 32)
fwrite(SPACES, 32, 1, stdout);
if (n)
fwrite(SPACES, n, 1, stdout);
}
Note, however, that the naive version is also quite fast:
void put_spaces(int n)
{
while (n--)
putchar(' ');
}
Why is it fast? On most systems, putchar is a macro which writes directly into a buffer most of the time. If you're not sure it's fast, the correct answer is profile your application, not "optimize first".
Stay away from malloc (it's just unnecessary), puts (which adds a '\n' every time you call it), and printf (it's too complicated for such a simple task).
I would try to use the system commands instead of making my own.
something like:
void print_spaces(unsigned int number_of_spaces) {
char* spaces = malloc(sizeof(char)*number_of_spaces + 1);
memset (spaces,' ',number_of_spaces);
spaces[number_of_spaces] = '\0';
printf("%s",spaces);
free(spaces);
}
would do the trick.
printf() allows you to adjust the number of spaces to be print, but this has to be stated in the format string. Se here for reference.
char format[256];
sprintf(format, "%%%ds", number_of_spaces); // creates the format string
printf(format, " ");
I'm assuming by "system functions", you mean non-standard extensions. In which case, it all depends on whether you mean fastest to write or fastest to execute?
If the former, and assuming there's an upper limit, you can just use something like:
void outSpaces (unsigned int num) {
static char *lotsaSpaces = " ";
printf ("%*.*s", num, num, lotsaSpaces);
}
If the latter, something like this should be a good starting point:
void outSpaces (unsigned int num) {
static char *hundredSpaces = "<<insert 100 spaces here>>";
while (num >= 100) {
puts (hundredSpaces);
num -= 100;
}
printf ("%*.*s", num, num, hundredSpaces);
}
You need to be aware that function calls can be expensive, even with output buffering. In that case, it may be best to call puts once to output a hundred characters rather than call putchar a hundred times.
Perhaps:
void PrintSpaces (int num_spaces)
{
char *spaces = " "; /* twenty spaces */
while (num_spaces > 20)
{
puts (spaces);
num_spaces -= 20;
}
if (num_spaces)
{
puts (&spaces [19 - num_spaces]);
}
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
int main() {
const size_t size = 5;
char* const data = (char*)malloc(size * sizeof(char) + 1);
if (!data) {
return EXIT_FAILURE;
}
memset(data, ' ', size);
data[size] = '\0'; // not needed (in this case)
fwrite(data, sizeof(char), size, stdout);
free(data);
return EXIT_SUCCESS;
}
(If the number of spaces isn't outrageous)
I don't known c, but here is the basic idea.
create an array of size 8192, and completely fill that particular array with spaces, now you can use puts or write system call or use something which is efficient, and then print this array.
Here I have a code snippet in go, but if you prefer c, you can see an example of how you do it, its actually GNU's yes program which is freaking fast at printing things, there is followed up explanation over there.
package main
import (
"bufio"
"os"
)
func main() {
t := []byte{'y', '\n'}
var used int
const tot = 8192
buf := make([]byte, 0, tot)
for used < tot {
buf = append(buf, t...)
used += 2
}
//Filled complete array named as buf with "y\n"
w := bufio.NewWriter(os.Stdout)
for {
w.Write(buf) //using write system call to print.
}
w.Flush()
}
//syscall.Write({without buf}) : 1.40MiB/s
//syscall.Write(buf) : 1.5GiB/s

Resources