Even though array numbers match, it still comes back false - c

Hi I am currently having a problem with my program. When i enter a phone number char, and compare it with a different phone number char, the answer comes back false.
Here my function searches the "findContact" function for a exact number. The getTenDigitPhone is the function to get the phone number.
I end up getting the * Contact NOT FOUND * regardless if it matches or not
void searchContacts(const struct Contact contact[], int size) {
char phone[11];
int searchIndexContact;
printf("Enter the cell number for the contact: ");
getTenDigitPhone(phone);
searchIndexContact = findContactIndex(contact, size, phone);
if (searchIndexContact > -1) {
printf("\n");
printf("Contact found:\n");
displayContact(&contact[searchIndexContact]);
}
else {
printf("*** Contact NOT FOUND ***\n");
}
}
** Here is the getTenDigitPhone function
void getTenDigitPhone(char telNum[11])
{
int needInput = 1;
while (needInput == 1) {
scanf("%10s", telNum);
clearKeyboard();
// (String Length Function: validate entry of 10 characters)
if (strlen(telNum) == 10)
needInput = 0;
else
printf("Enter a 10-digit phone number: ");
}
}
And here is the findContactIndex (to find out if the numbers match)
int findContactIndex(const struct Contact contacts[], int size, const char cellNum[])
{
int i;
int value = 0;
for (i = 0; i < size; i++) {
if (contacts[i].numbers.cell == cellNum);{
printf(" %s %s",contacts[i].numbers.cell , cellNum);
value == 1;
}
}
if (value == 1) {
return value;
}
if (value == 0) {
return -1;
}
}

Enable your compiler's warnings! It would have found your problems. For example, with gcc, use at least
gcc -Wall -Wextra -pedantic ...
In findContactIndex,
value == 1;
is wrong. You were probably going for
value = 1;
but it should be
value = i;
break;
or just
return i;
since the function should return the index of the match. That means
int value = 0;
...
if (value == 1) {
return value;
}
if (value == 0) {
return -1;
}
should be
int value = -1;
...
return value;
or just
return -1;
Unrelated to your question, in findContactIndex,
if (...);{
should be
if (...) {
As you currently have it, the result of the conditional expression is disregarded, then the following block is executed unconditionally.
Unrelated to your question, in findContactIndex,
contacts[i].numbers.cell == cellNum
should be
strcmp(contacts[i].numbers.cell, cellNum) == 0
You are currently comparing the pointers instead of the strings.
Fixed:
int findContactIndex(const struct Contact contacts[], int size, const char cellNum[])
{
int i;
for (i=0; i<size; ++i) {
if (strcmp(contacts[i].numbers.cell, cellNum) == 0) {
return i;
}
}
return -1;
}

Related

Hanoi Tower Problem using stacks - It is not solving the hanoi problem but moving the disks

//Stack Study by yoonseul at 210719
#include <stdio.h>
#include <stdbool.h>
#define SIZE 9
#define _CRT_SECURE_NO_WARNINGS
typedef struct {
int item[SIZE];
int top;
} Stack;
void InitStack(Stack* pstack)
{
pstack->top = -1;
}
bool IsFull(Stack* pstack)
{
return pstack->top == SIZE - 1;
}
bool IsEmpty(Stack* pstack)
{
return pstack->top == -1
}
int Peek(Stack* pstack)
{
if (IsEmpty(pstack)) {
return -1;
}
return pstack->item[pstack->top];
}
void Push(Stack* pstack, int disk)
{
if (IsFull(pstack)) {
exit(1);
}
pstack->item[++(pstack->top)] = disk;
}
void Pop(Stack* pstack) {
if (IsEmpty(pstack)) {
exit(1);
}
--(pstack->top);
}
int exchange(int x);
int main()
{
int num;
int rod[3][SIZE];
char from='0', to;
int move;
scanf("%d", &num);
InitStack(&rod[0]);
InitStack(&rod[1]);
InitStack(&rod[2]);
for (int i = 0; i < num+1; i++) {
Push(&rod[0], i+1);
Push(&rod[1], 0);
Push(&rod[2], 0);
}
while (from != 'q') {
printf("%3c %3c %3c\n", 'A', 'B', 'C');
for (int i = 0;i<num; i++) {
printf("%3d %3d %3d\n", rod[0][i], rod[1][i], rod[2][i]);
}
scanf("%c %c", &from, &to);
if (from == 'q')
return 0;
int peekF, peekT;
int numF = exchange(from);
int numT = exchange(to);
peekF = Peek(&rod[numF]);
peekT = Peek(&rod[numT]);
if (peekF > peekT && peekT != -1) {
printf("Invalid Move");
}
else {
Pop(&rod[numF]);
Push(&rod[numT],peekF);
}
}
}
int exchange(int x)
{
switch (x) {
case 'A':
return 0;
case 'B':
return 1;
case 'C':
return 2;
}
}
Here is my full code for Hanoi Problem.
The objective is to make a problem that can move this between the rod, and print 'invalid move' if the move is invalid. Also, user can input the number of the disks.
When I debug, there are two errors occur.
One is beneath ' A B C' the last number disk is printed three times. My objective is to print ' 1 0 0'
(ex. if maximum disk is 3,' 3 3 3' is printed.)
edited I solved the first one.
for (int i = 0; i < num + 1; i++) {
Push(&rod[0], i+1);
}
for (int i = 0; i < num + 1; i++) {
Push(&rod[1], 0);
}
for (int i = 0; i < num + 1; i++) {
Push(&rod[2], 0);
}
I changed disk putting part like like using for statement three times. but I don't know the reason why this happens.
Edited
The hanoi Tower is printed twice, after 2nd scan. I want to know the reason why this happens. It seems like memory problem. I want to know why. I'm new to coding.
PLZ help me. I'm crying.

Define a function to check if its a perfect square in C

I tried to write a code to check if a number is a perfect square, but I'm not able to call the function I defined. Where is my mistake?
#include <stdio.h>
#include <math.h>
int isPerfectSquare(int number) {
int i;
for (i = 0; i <= number; i++) {
if (number == (i * i)) {
printf("Success");
break;
} else {
continue;
}
}
printf("Fail");
}
int main() {
int n;
printf("Enter a number: ");
scanf("%d", n);
isPerfectSquare(n);
return 0;
}
I don't get any answer ("Success" or "Fail").
You must pass the address of n instead of its value in scanf("%d", n);:
scanf("%d", &n);
Note however that your function will print both Success and Fail for perfect squares because you should return from the function instead of just breaking from the loop upon success.
Here is a modified version:
#include <stdio.h>
void isPerfectSquare(int number) {
int i;
for (i = 0; i <= number; i++) {
if (number == (i * i)) {
printf("Success\n");
return;
}
}
printf("Fail\n");
}
int main() {
int n;
printf("Enter a number: ");
if (scanf("%d", &n) == 1) {
isPerfectSquare(n);
}
return 0;
}
Note also that your method is quite slow and may have undefined behavior (and produce false positives) if i becomes so large that i * i exceeds the range of type int. You should instead use a faster method to figure an approximation of the square root of n and check if the result is exact.
It is also better for functions such as isPerfectSquare() to return a boolean value instead of printing some message, and let the caller print the message. Here is a modified version using the Babylonian method, also known as Heron's method.
#include <stdio.h>
int isPerfectSquare(int number) {
int s1 = 2;
if (number < 0)
return 0;
// use the Babylonian method with 10 iterations
for (int i = 0; i < 10; i++) {
s2 = (s1 + number / s1) / 2;
if (s1 == s2)
break;
s1 = s2;
}
return s1 * s1 == number;
}
int main() {
int n;
printf("Enter a number: ");
if (scanf("%d", &n) == 1) {
if (isPerfectSquare(n)) {
printf("Success\n");
} else {
printf("Fail\n");
}
}
return 0;
}

strcmp refuses to work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I've tried everything, yet strcmp (as well as strncmp) always give a value other than 0, both with and without using pointers, as well as inside and outside functions. What should I do?
The point of the program is to create a student data system for signing up and in, as well as managing and sorting said data, the latter which I haven't implemented yet.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int signup(char* ET, char* OT, int* G1T, int* G2T, int* G3T, int* avg, char* status, int* LI, int* sT, int* TT, char** UT, int** PT)
{
int i;
char LU[21];
int ID;
if (strcmp (status, "Register") == 0)
{
printf("Enter last name: ");
scanf("%s", ET);
printf("Enter first name: ");
scanf("%s", OT);
while(1)
{
printf("Enter C grade: ");
scanf("%d", G1T);
if (*G1T >= 0 && *G1T <= 10)
{
break;
}
}
while(1)
{
printf("Enter Java grade: ");
scanf("%d", G2T);
if (*G2T >= 0 && *G2T <= 10)
{
break;
}
}
while(1)
{
printf("Enter C++ grade :");
scanf("%d", G3T);
if (*G3T >= 0 && *G3T <= 10)
{
break;
}
}
*avg = (*G1T + *G2T + *G3T)/3;
*UT[*TT] = *ET;
*sT = 1;
}
else
{
printf("Enter username: ");
scanf("%s", &LU);
for (ID = 0; ID < 100; ID++)
{
if (strncmp(LU, UT[ID], 20) == 0)
{
break;
}
}
if (ID == 100)
{
return 0;
}
else
{
printf("Enter password: ");
scanf("%s", LU);
}
}
return 0;
}
void pass(char** User, int** Pass, int* Total)
{
int cd[21];
int i, j;
for (i=0; i<21; i++)
{
cd[i] = *User[i];
if (i%2 == 0)
{
if(cd[i] >= 97 && cd[i <= 122])
{
cd[i] = cd[i] - 32;
}
}
else
{
if(cd[i] >= 65 && cd[i] <= 90)
{
cd[i] = cd[i] + 32;
}
}
}
}
int main(void) {
int i, j, z;
int succ, *sT;
char intro[9], *status;
int Total = 0;
int* TT;
int LoggedIn = 0;
int* LI;
char Ep[100][21], *ET, On[100][21], *OT;
int Age[100], *AgeT, Gr1[100], *G1T, Gr2[100], *G2T, Gr3[100], *G3T, avg[100], *avgT;
char UN[100][21], *UT[100];
int PW[100][21], *PT[100];
while(1)
{
system("cls");
if (succ = 0)
{
printf("ERROR: Last name found.");
}
succ = 1;
while(1)
{
printf("Type your option (Login/Register): ");
scanf("%s", intro);
if ((strcmp (intro, "Login") == 0) || (strcmp (intro, "Register") == 0))
{
break;
}
}
if ((strcmp (intro, "Login") == 0) || (strcmp (intro, "Register") == 0))
{
for(i = 0; i < 100; i++)
{
UT[i] = &UN[i][0];
PT[i] = &PW[i][0];
}
ET = &Ep[Total][0];
OT = &On[Total][0];
G1T = &Gr1[Total];
G2T = &Gr2[Total];
G3T = &Gr3[Total];
avgT = &avg[Total];
LI = &LoggedIn;
status = &intro[0];
sT = &succ;
TT = &Total;
signup(ET, OT, Gr1, Gr2, Gr3, avg, status, LI, sT, TT, UT, PT);
for(i = 0; i<Total; i++)
{
if(strncmp(UN[Total], UN[i], 20) == 0)
{
succ = 0;
}
}
if (succ == 1)
{
pass(UT, PT, TT);
Total++;
}
}
}
return 0;
}
An example for my inputs is the following:
Register
LastName
FirstName
4
5
6
Then:
Register
LastName
FN2
7
6
5
And I expect to see "ERROR: Last name found." right above the starting message. However, it never appears, suggesting strcmp failed.
First off, you're allocating a lot of arrays in local variables in main(). That could lead to a stack overflow. You should probably use malloc() to allocate them instead.
Second, this line is an assignment, not a comparison, which is a bug:
if (succ = 0)
Change it to this, if you want it to be a comparison:
if (succ == 0)
Third, you're not initializing succ at the beginning of main() which is a bug.
If I see anything else suspect I'll update my answer. But start with fixing those issues.
There are a few issues with your code, as was pointed out, but the reason it doesn't work as you expect is the line: if(succ = 0)
I changed it to: if(succ==0)
And it worked as you described.
Additionally this line here: scanf("%s", &LU); should be scanf("%s", LU);
The compiler is probably generating a warning about the format.

Dynamic array of Structs, delet elements

I am trying to create a database program of students where you should be able to add/modify and delete students. I have managed to get the add function working, and also the modify function but the delete function gives me some problems. my code seems to crash when im trying to delete a student from the database, can anyone tell me where the problem lies?
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* TODO: Avoid global variables. */
struct student {
char name[60];
long long personalNumber;
char gender[6];
char studyProgram[60];
char email[30];
int age;
};
struct student *pointer = NULL;
int numberofstudents = 0;
void modify()
{
long long persnr;
long long comp;
int match = 0;
printf("Please enter the personal number that you wish to modify: \n");
scanf("%lld", &persnr);
getchar();
for(int i = 0; i <= numberofstudents; i++)
{
comp = ((pointer+i)->personalNumber);
printf("%lld\n", ((pointer+i)->personalNumber));
printf("%lld\n", comp);
printf("Inne");
if (pointer[i].personalNumber == persnr && match == 0)
{
printf("Enter name, personalnumber, gender, studyprogram, email and age in this order\n");
scanf("%s%lld%s%s%s%d", (pointer+i)->name, &(pointer+i)->personalNumber, (pointer+i)->gender, (pointer+i)->studyProgram, (pointer+i)->email, &(pointer+i)->age);
match = 1;
getchar();
}
if (match == 0)
{
printf("Could not find person");
}
}
}
void deletestudent()
{
long long persnr;
long long comp;
int match = 0;
printf("Please enter the personal number that you wish to delete: \n");
scanf("%lld", &persnr);
getchar();
struct student *temporary = malloc((numberofstudents - 1) * sizeof(struct student));
for(int i = 0; i <= numberofstudents; i++)
{
if (pointer[i].personalNumber == persnr && match == 0)
{
match = 1;
}
else if (match == 1){
temporary[i-1] = pointer[i];
}
else
{
temporary[i] = pointer[i];
}
if (match == 0)
{
printf("Could not find person");
}
}
free(pointer);
pointer = temporary;
}
void add(){
if (numberofstudents > 0)
{
pointer = (struct student*) realloc(pointer, (numberofstudents+1) * sizeof(struct student));
printf("Lyckades allokeringen!\n\n");
}
printf("Enter name, personalnumber, gender, studyprogram, email and age in this order\n");
scanf("%s%lld%s%s%s%d", (pointer+numberofstudents)->name, &(pointer+numberofstudents)->personalNumber, (pointer+numberofstudents)->gender, (pointer+numberofstudents)->studyProgram, (pointer+numberofstudents)->email, &(pointer+numberofstudents)->age);
getchar();
printf("Visar data:\n");
for(int i = 0; i <= numberofstudents; ++i)
{
printf("%s\t%lld\t%s\t%s\t%s\t%d\n", (pointer+i)->name, (pointer+i)->personalNumber, (pointer+i)->gender, (pointer+i)->studyProgram, (pointer+i)->email, (pointer+i)->age);
}
numberofstudents = numberofstudents+1;
}
int main(void)
{
pointer = (struct student*) malloc(2 * sizeof(struct student));
if (pointer == NULL)
{
printf("pointer NULL");
exit(1);
}
int run = 1;
int choice;
while (run == 1)
{
printf("Please enter an option listed below\n1.ADD\n2.Modify\n3.Delete\n4.Search\n5.Save\n6.Load\n7.Exit");
scanf("%d", &choice);
getchar();
switch(choice) {
case 1 :
add();
break;
case 2 :
modify();
break;
case 3 :
deletestudent();
case 7 :
exit(0);
break;
default :
break;
}
}
return 0;
}
As mentioned in a comment, this:
for(int i = 0; i <= numberofstudents; i++)
is a huge warning sign. In C, such a loop should typically have i < numberofstudents in it, assuming numberofstudents is the actual length of the array.
Using <= rather than < makes the loop go one step too far, thus indexing outside the array and causing undefined behavior.
Writing outside heap-allocated memory and then trying to free() it is a good way to provoke crashes, since there's a chance you're stepping on the heap allocator's data structures (in practice; in theory all that happens is that you get undefined behavior and thus anything can happen).

Memory can't be read when shortest function is run

I had a bunch of problems with this program but looks like this might be inches away from completion and I was hoping someone could tell me what the hell's wrong with the blasted thing!
#include <stdio.h>
#include <string.h>
#define SIZE_OF_STRING 21
void displayMenu(void);
void readArray(char [][SIZE_OF_STRING], int);
void printArray(char [][SIZE_OF_STRING], int);
int shortestArray(char [][SIZE_OF_STRING], int);
int smallestArray(char [][SIZE_OF_STRING], int);
void sortArray(char [][SIZE_OF_STRING], int);
int main(void)
{
int position, n = 0; /* all local to main */
char select[10]; /* select is a string */
char array[1000][SIZE_OF_STRING];
displayMenu();
scanf("%s", select); /* read first selection */
while (strcmp(select, "exit") != 0) /* while not exit */
{
if (strcmp(select, "read") == 0)
{
printf("How many names?");
scanf("%d", &n);
n++;
printf("Enter %d names", n - 1);
readArray(array, n);
}
else if (strcmp(select, "display") == 0)
{
printArray(array, n);
}
else if (strcmp(select, "shortest") == 0)
{
position = shortestArray(array, n);
printf("Shortest name is %s in position %d\n", array[position], position + 1);
}
else if (strcmp(select, "lowest") == 0)
{
position = smallestArray(array, n);
printf("Lowest name is %s in position %d\n",
array[position], position + 1);
}
else if (strcmp(select, "sort") == 0)
{
sortArray(array, n);
}
else
{
printf("INVALID SELECTION");
}
displayMenu();
scanf("%s", select); /* read next selection */
} /* end while */
}/* end main */
void displayMenu(void)
{
puts("Menu selection");
puts("Enter read to read names");
puts("Enter display to display names");
puts("Enter shortest for shortest name");
puts("Enter lowest for lowest names");
puts("Enter sort to sort names");
puts("Enter exit to exit\n");
}
void readArray(char a[][SIZE_OF_STRING], int n)
{
int i;
printf("\ntype one string per line\n");
for (i=0; i<n; i++)
{
gets(a[i]);
}
}
void printArray(char a[][SIZE_OF_STRING], int n)
{
int i;
printf("\ntype one string per line\n");
for (i=0; i<n; i++)
{
puts(a[i]);
}
}
int shortestArray(char a[][SIZE_OF_STRING], int n)
{
int i;
int chag = 0;
int position;
while (a[i] != '\0')
{
if (strlen(a[i]) < strlen(a[i-1]))
{
position = i;
chag = 1;
}
else
{
if (chag = 0)
{
position = 1;
}
else
{
printf("");
}
}
}
return position;
}
int smallestArray(char a[][SIZE_OF_STRING], int n)
{
puts("Not yet implemented\n");
return 0;
}
void sortArray(char a[][SIZE_OF_STRING], int n)
{
puts("Not yet implemented\n");
}
only worried about "shortest" function at the moment all others run okay.
I also know there are better ways of doing the search but I keep getting "declaration creates integer from pointer without cast" errors when I change to a more standard search with a default smallest etc.
chag is to say whether or not number one in a[] is the smallest as it never gets checked, going to change this as soon as I get it working as I can see a more effective way of doing it.
[edit]
My bad, the error that appears is an application error when "smallest" is selected.
the following appears
"the instruction at "0x77c478c0" referenced memory at "0xd2fd82e0". the memory could not be "read".
ok to terminate program, cancel to debug.
changed the shortest function to the following and still get a similar memory message;
int shortestArray(char a[][SIZE_OF_STRING], int n)
{
int i = 1;
int position = 1;
while (a[i] != '\0')
{
if (strlen(a[i + 1]) < strlen(a[i]))
{
position = i + 1;
i++;
}
else
{
i++;
}
}
return position;
}
There's a clbuttic typo in shortestArray():
if (chag = 0) {
position = 1;
}
// ...
This will always evaluate to false, so the else block is run.
Here, zero is assigned to chag which makes the expression evaluate to zero (false). Use the comparision operator == instead. You might want to crank up warning levels as I'm sure, any C compiler has an appropriate message for this.
One big and obvious problem is that in the function you use the variable i without initializing it.
Another problem is this expression: strlen(a[i-1]). If i is 0 then this will access memory before the array.
In addition to the other answers so far:
You don't increment i either.
If I imagine all the trivial fixes applied (correct iteration, comparison instead of assignment in the condition), the function is going to return position of last local minimum of length. I.e. having list of strings like
"a", "bbbb", "ccc", "dd"
it will return 3, but shortest string is at position 0!
You do remember array indices in C start from 0, right (in position = 1)?
you have to know the number of strings entered in the array to avoid unknown behavior.
a way to do this : in main, just after declaration of array, put :
strcpy(array[0], ""); // to indicate that the array is empty.
in the end of readArray() :
strcpy(a[n] , ""); // there is n strings written bythe user (a[0] to a[n-1]).
and finally :
in shortestArray(), the stop condition of the loop must be changed to :
while (strcmp(a[i],"") != 0 ) //a[i] == '\0' is not correct because a[i] is string and '\0' is char.
here is the entire code with the changes i made :
#include <stdio.h>
#include <string.h>
#define SIZE_OF_STRING 21
#define SIZE_OF_ARRAY 1000
void displayMenu(void);
void readArray(char [][SIZE_OF_STRING], int);
void printArray(char [][SIZE_OF_STRING]);
int shortestArray(char [][SIZE_OF_STRING]);
int smallestArray(char [][SIZE_OF_STRING], int);
void sortArray(char [][SIZE_OF_STRING], int);
int main(void)
{
int position, n = 0; /* all local to main */
char select[10]; /* select is a string */
char array[SIZE_OF_ARRAY][SIZE_OF_STRING]; //change here !
strcpy(array[0] , ""); //instruction added : means array is empty
displayMenu();
scanf("%s", select); /* read first selection */
while (strcmp(select, "exit") != 0) /* while not exit */
{
if (strcmp(select, "read") == 0)
{
printf("How many names?");
scanf("%d", &n);
while (n >= SIZE_OF_ARRAY)
{
printf("the number you entered is bigger than the maximum number of strings, please enter a number smaller than %d\n", SIZE_OF_ARRAY);
}
printf("Enter %d names", n);
readArray(array, n);
}
else if (strcmp(select, "display") == 0)
{
printArray(array);
}
else if (strcmp(select, "shortest") == 0)
{
position = shortestArray(array);
if (position == -1)
printf("there is no string entered !\n");
else
printf("Shortest name is %s in position %d\n", array[position-1], position );
}
else if (strcmp(select, "lowest") == 0)
{
position = smallestArray(array, n);
printf("Lowest name is %s in position %d\n",
array[position], position + 1);
}
else if (strcmp(select, "sort") == 0)
{
sortArray(array, n);
}
else
{
printf("INVALID SELECTION");
}
displayMenu();
scanf("%s", select); /* read next selection */
} /* end while */
}/* end main */
void displayMenu(void)
{
puts("Menu selection");
puts("Enter read to read names");
puts("Enter display to display names");
puts("Enter shortest for shortest name");
puts("Enter lowest for lowest names");
puts("Enter sort to sort names");
puts("Enter exit to exit\n");
}
void readArray(char a[][SIZE_OF_STRING], int n)
{
int i;
printf("\ntype one string per line\n");
for (i=0; i<n; i++)
{
scanf("%s",a[i]);
}
strcpy(a[n] , "");
}
void printArray(char a[][SIZE_OF_STRING])
{
int i;
for (i=0; i< SIZE_OF_ARRAY; i++)
{
if (strcmp(a[i] , "") == 0) // a[i-1] is last string entered
break; // this avoid printing non initialized string causing unknown behaviour.
printf("%s\n",a[i]);
}
}
int shortestArray(char a[][SIZE_OF_STRING])
{
int i = 0;
int position = 1;
if(strcmp (a[i] , "\0") == 0)
return position = -1; // there no string entered.
while (strcmp (a[i+1] , "\0") != 0)
{
if (strlen(a[i+1]) < strlen(a[i]))
{
position = i+2 ;
i++;
}
else
{
i++;
}
}
return position;
}
int smallestArray(char a[][SIZE_OF_STRING], int n)
{
puts("Not yet implemented\n");
return 0;
}
void sortArray(char a[][SIZE_OF_STRING], int n)
{
puts("Not yet implemented\n");
}

Resources