strcmp not working in c - c

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
struct Position
{
char* x1[2];
char* x2[2];
};
int main(void)
{
struct Position positions[4];
struct Position p1[4];
char* p;
matrix[10][10];
if(r==0) //stores horizontal words in matrix
{
emptyH=0;
do
{
x=(rand()%size);
y=(rand()%10);
emptyH=0;
for(k=0;k<ans;k++)
{
if ( matrix[y][x+k]!='1')
{
emptyH=1;
k=ans;
} // checks whether word fits in matrix and position is empty
}
}while(emptyH);
token = strtok(words[random],search); //strtok to seperate char by char
matrix[y][x]=token;
if(x!=0)
{
p=(char)x;
p1[i].x1[0] = p;//SAVING the positions of x and y
}
else
p1[i].x1[0]='\0';
if(y!=0)
{
p=(char)y;
p1[i].x1[1]=p;
}
else
p1[i].x1[1]='\0';
x++;
while(token!=NULL)
{
token = strtok(NULL, search);
if(token!=NULL)
{
matrix[y][x]=token;
p=(char*)x;
p1[i].x2[0]=p;
p=(char*)y;
p1[i].x2[1]=p; // saving positions of x and y
x++;
positions[i] = p1[i];
}
}
}
correct=0;
do
{
puts("\nenter the word:");
scanf("%s",&name);
printf("\n Enter the start and end position of the word");
puts("\nstart:");
scanf("%s",&start);
puts("\n\tend:");
scanf("%s",&end);
for(k=0;k<4;k++)
{
if((strcmp(positions[k].x1,start)==0)&&(strcmp(positions[k].x2,end)==0))
{
puts("viola!");
correct=1;
}
else
puts("incorrect answer! try again");
}
}
while(correct!=1);
}
this is my code. however string compare always gives wrong answer.also
sometimes there is a runtime error as i store the positions in the
'p1[i].x1[0]'. any ideas why? thankyou for your help in advance.

You are not setting up your pointers properly. You do this:
p1[i].x1[0]='\0';
So you are initializing x1[0] to point to the zero address. That's bad. You need to allocate some space and init x1[0] to point to that space.
You could add:
p1[i].x1[0] = malloc(sizeof(char)); // Now x1[0] points to some allocated space.
and then you could dereference x1[0] properly:
*(p1[i].x1[0])='\0';

Related

Using Struct in C to create a library for items and giving location feedback based upon user entry. I just cant seem to find my error

//make a location marker for key items
#include <stdio.h>
#include <string.h>
struct find {int index; char name[50]; char location[50]; };
int main() {
char locate_item[50];
//using struct to add items
struct find item1;
item1.index = 1;
strcpy(item1.name, "guitar");
strcpy(item1.location, "Usually near the table in the living room area.\n");
struct find item2;
item2.index = 2;
strcpy(item2.name, "ipad");
strcpy(item2.location, "Usually on the table or charging on the bed.\n");
//using while and if statements to get user feedback and display the appropriate location
while (locate_item != item1.name || locate_item != item2.name) {
printf("what is the item you want to find? \n");
scanf("%s", locate_item);
printf("You entered %s\n", locate_item);
if (locate_item == item1.name) {
printf("%s", item1.location);
} else if (locate_item == item2.name) {
printf("%s", item2.location);
} else {
printf("Incorrect entry. Please try again.\n");
}
}
return 0;
}
locate_item != item1.name || locate_item != item2.name compares pointer, however, you want to use strcmp() to compare two strings by value. strcmp() returns 0 if the two strings are the same.
In either case, your program doesn't make a lot of sense. You probably want to find locate_item in the an array of items (renamed from find) along these lines:
#include <stdio.h>
#include <string.h>
struct item {
int index;
char name[50];
char location[50];
};
int main() {
struct item items[] = {
{ 1, "guitar", "Usually near the table in the living room area." },
{ 2, "ipad", "Usually on the table or charging on the bed." },
{ 0 }
};
for(;;) {
printf("what is the item you want to find? \n");
char locate_item[50];
scanf("%s", locate_item);
//printf("You entered %s\n", locate_item);
for(int i = 0; items[i].name[0]; i++) {
if(!strcmp(items[i].name, locate_item)) {
printf("%s\n", items[i].location);
goto done;
}
}
printf("Incorrect entry. Please try again.\n");
}
done:
return 0;
}

Insert structure arrays dynamic in C. Exited, segmentation fault

I have a problem with structure arrays, to insert dynamic values.
Cannot insert values ​​into dynamic arrays, response "Exited, segmentation fault".
Can anyone help me, that's problem.
Thank you
............................................................................................................................................................................................................................................................................................................................
Syntax:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#define FLUSH while (getchar() != '\n')
typedef struct{
char *Name;
int Qty;
} Item;
static void insert(Item* i, char *name, int qty)
{
i->Name = name;
i->Qty = qty;
}
int main() {
int storage = 0, menu;
printf("Temporary Storage\n");
//Input storage amount
bool isInputStorage = true;
while (isInputStorage) {
printf("Input Storage amount [1..10]: ");
scanf("%d", &storage);
if (storage <= 10 && storage >= 1) {
isInputStorage = false;
}
else {
printf("\n[!]Please enter numbers [1..10] for Storage amount.\n\n");
}
FLUSH;
}
Item *dataItems;
//Input Menu
bool isInputMenu = true;
while (isInputMenu) {
printf("\n\nMenu\n");
printf("=============\n");
printf("1. Add items\n");
printf("4. Exit\n");
printf("Choose Menu [1..4]: ");
scanf("%d", &menu);
if (menu >= 1 && menu <= 4) {
if (menu == 1) {
char* name;
int qty;
//Insert to arrays storage
int currentStorageAmount = sizeof(dataItems) / sizeof(dataItems[0]);
if (currentStorageAmount >= storage) {
printf("Storage is Full");
}
else {
printf("Input name of Item : ");
scanf("%s", name);
bool isQty = true;
while (isQty) {
FLUSH;
printf("Input qty of Item : ");
int correctQty = scanf("%d", &qty);
if (correctQty == 1) {
isQty = false;
}
else {
printf("\n[!]Please enter number for Qty!\n\n");
}
}
//action to insert
insert(&dataItems[currentStorageAmount], name, qty);
}
}
else if (menu == 4) {
printf("\nThank you for using this application.\n");
isInputMenu = false;
}
}
else {
printf("\n[!]Please enter numbers [1..4] for choose Menu.");
}
menu = 0;
FLUSH;
}
system("pause");
return 0;
}
Result:
Temporary Storage
Input Storage amount [1..10]: 4
Menu
=============
1. Add items
4. Exit
Choose Menu [1..4]: 1
Input name of Item : test
Input qty of Item : 5
exited, segmentation fault
You are asking about arrays but there is no one array in your code...
What you really have is the pointer to Item. This means three things:
You have not initialized this pointer, and it points to somewhere. So the expression &dataItems[currentStorageAmount] gives you a random position in memory that leads you to the segmentation fault.
The expression sizeof(dataItems) / sizeof(dataItems[0]) gives you something different from what you expect: size of the pointer divided to size of the structure. In other words it is zero.
You need to allocate memory before using the dataItems.
I check the code with GDB, the error is at line 65,
scanf("%s", name);
you have declared a pointer char* name, but you have not allocated its heap memory yet. The correct solution is to change the line,
char *name
To
char* name = malloc(128);
Then, the code is running.

Python's binascii.unhexlify function in C

I'm building a program that takes input as if it is a bare MAC address and turn it into a binary string. I'm doing this on a embedded system so there is no STD. I have been trying something similar to this question but after 2 days I haven't achieved anything, I'm really bad with these kind of things.
What I wanted is output to be equal to goal, take this into consideration:
#include <stdio.h>
int main() {
const char* goal = "\xaa\xbb\xcc\xdd\xee\xff";
printf("Goal: %s\n", goal);
char* input = "aabbccddeeff";
printf("Input: %s\n", input);
char* output = NULL;
// Magic code here
if (output == goal) {
printf("Did work! Yay!");
} else {
printf("Did not work, keep trying");
}
}
Thanks, this is for a personal project and I really want to finish it
First, your comparison should use strcmp else it'll be always wrong.
Then, I would read the string 2-char by 2-char and convert each "digit" to its value (0-15), then compose the result with shifting
#include <stdio.h>
#include <string.h>
// helper function to convert a char 0-9 or a-f to its decimal value (0-16)
// if something else is passed returns 0...
int a2v(char c)
{
if ((c>='0')&&(c<='9'))
{
return c-'0';
}
if ((c>='a')&&(c<='f'))
{
return c-'a'+10;
}
else return 0;
}
int main() {
const char* goal = "\xaa\xbb\xcc\xdd\xee\xff";
printf("Goal: %s\n", goal);
const char* input = "aabbccddeeff";
int i;
char output[strlen(input)/2 + 1];
char *ptr = output;
for (i=0;i<strlen(input);i+=2)
{
*ptr++ = (a2v(input[i])<<4) + a2v(input[i]);
}
*ptr = '\0';
printf("Goal: %s\n", output);
if (strcmp(output,goal)==0) {
printf("Did work! Yay!");
} else {
printf("Did not work, keep trying");
}
}

Very Basic Encryption

#include <stdio.h>
int limit;
char alp[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','w','x','y','z'};
void encode(char message[21],char enc_message[21],int key);
void decode(char enc_message[21],char dec_message[21],int key);
main()
{
int key,i=0,j=0;
char message[21];
char enc_message[21];
char dec_message[21];
char encrypted[21];
char a='\0';
printf("Input the characters to encrypt\n");
while(i<21 && a!='\n')
{
scanf("%c",&a);
message[i]=a;
i=i+1;
}
for(i=0;;i++) /*custom strlen*/
{
if( message[i]= '\0')
{
limit=i;
break;
}
}
printf("Input the key");
scanf("%d",key);
for(i=0;i<21;i++)
{
enc_message[i]=message[i];
}
encode(message[21],enc_message[21],key);
for(i=0;i<21;i++)
{
dec_message[i]=enc_message[i];
}
for(i=0;i<limit;i++)
{
printf("%c",enc_message[i]);
}
printf("\n\n");
decode(enc_message[21],dec_message[21],key);
for(i=0;i<limit;i++)
{
printf("%c",dec_message[i]);
}
}
void encode(char message[21],char enc_message[21],int key)
{
/*char temp[21];*/
int x,y;
for(x=0;x<limit;x++) /* message check */
{
for(y=0;y<26;y++) /* <----- alphabet check */
{
if (enc_message[x]==alp[y]) enc_message[x]=alp[y+key];
}
}
}
/*------------------------------------------------------------------------*/
void decode(char enc_message[21],char dec_message[21],int key)
{
int x,y;
for (x=0;x<limit;x++)
{
for(y=0;y<26;y++)
{
if (dec_message[x]==alp[y+key]) dec_message[x]=alp[y];
}
}
}
The compiler says,the mistake has to do with the way I call functions(and write them)and says: passing argument1 of 'encode' makes pointer from integer without a cast ,and that is for argument 2 of 'encode' and the exact same for 'decode'
Thanks in advance!
You are passing a single element and it's not even a valid element, try
decode(enc_message, dec_message, key);
Also, format your code so it's readable that is really important, and looping to compute the length of the string to use it in another loop is not a very smart thing, print it in a loop like
for (int i = 0 ; enc_message[i] != '\0' ; ++i) ...
also, don't over use break, just think about the logical condition for the loop, it's the same one where you break. Code is much more readable if the condition appears in the right place.

Making y[i] a modifiable variable in C

I am building a program that randomly generates a password using the ascii tabe of values and can only contain one of each char. it generates a password that is 8 char long.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define SIZE 10
char Charactor(char x);
void Check(char* y);
int main()
{
char string[SIZE];//defines varriables
char* point;
point=&string[SIZE];
srand(time(NULL));
for (int i=0;i<SIZE-1;i++)//empties out the string
{
string[i]='\0';
}
for (int i=0;i<SIZE-2;i++)//randomizes a char for each space in the string
{
string[i]=Charactor(*point);
}
Check(point);/checks the string for duplicated values
printf("%s\n",string);//prints string on screen
}
char Charactor(char x)
{
int rnd=0;
rnd=rand()%2;//chooses char or number using ascii
if (rnd==0)
{
rnd=rand()%10+48;
}
else
{
rnd=rand()%26+65;
}
x=(char)rnd;
return x;
}
void Check(char* y)
{
int run=0;
for (int i=0; i<SIZE-2;i++)
{
for (int x=0; x<SIZE-2; x++)
{
if (y[i]==y[x] && run=0)
{
run++;
continue;
}
else
{
y[i]='\0';
y[i]=Charactor(*y);
}
}
}
return;
}
with those changes the code is running now I just have to figure out how to change the correct value so I dont have any duplication.
Fix:
char* point =&string[0]; //Make it to point to first element
Since your Charactor(*point); is really not doing anything based on *point and later you use Check(point); probably to start a scan from start of string.
And
if (y[i]==y[x] && run==0)
^^Use Equality check
You cannot modify a boolean outcome of y[i]==y[x] && run as zero.
Note :
However if (y[i]==y[x] && (run=0) ) wouldn't have thrown this error.
Your error seems to be that you are mistakenly setting run=0 in
if (y[i]==y[x] && run=0)
This is the part that most likely confuses your compiler. Doesn't have to do anything with Y.
Fix to:
if (y[i]==y[x] && run==0)

Resources