Why is NULL printed here? - C-90 - c

The code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 500
#define M 100
/*Version 1*/
void replace_word(char *word);
void add_new_word_dictionary(void);
void do_nothing(void);
void return_basic(void);
void check_word(void);
void compute_words(void);
void compute_characters(void);
void compute_ch_sp(void);
void compute_num_dif_words(void);
void create_istogram(void);
void save_file(void);
int get_choice(void);
void return_word(void);
void insert_text(int numwords, char matrix[N][M], int posit);
int main() {
int j;
int choice = 0;
char matrix[N][M];
char word[40] = { "t" };
while (1) {
choice = get_choice();
if (choice == 0) {
insert_text(M, matrix, 1);
}
if (choice == 1) {
add_new_word_dictionary();
}
if (choice == 2) {
do_nothing();
}
if (choice == 3) {
save_file();
}
if (choice == 4) {
compute_words();
}
if (choice == 5) {
break;
}
for (j = 0; j < M; j++) {
printf("%s", matrix[N][M]);
}
}
printf("\n End of Program \n");
return 0;
}
void replace_word(char *word) {
return;
}
void add_new_word_dictionary(void) {
char word[50] = { "s" };
printf("\nPlease enter the word\n");
scanf("\n%s", word);
printf("Your word is %s", word);
return;
}
void do_nothing(void) {
printf("\n do_nothing \n");
return;
}
void return_basic(void) {
printf("\n return basic \n");
return;
}
void check_word(void) {
printf("\n check word \n");
return;
}
void compute_words(void) {
printf("\n compute_words \n");
return;
}
void compute_characters(void) {
printf("\n compute characters \n");
}
void compute_ch_sp(void) {
printf("\n compute_ch_sp \n");
return;
}
void compute_num_dif_words(void) {
printf("\n compute_num_same_words \n");
return;
}
void create_istogram(void) {
printf("\n create istogram \n");
return;
}
void save_file(void) {
printf("\n save_file \n");
return;
}
int get_choice(void) {
int choice = 0;
printf("\n Select a choice from the below \n");
printf("\n Select 0 to add text \n");
printf("\n Select 1 to add new words in the dictionary \n");
printf("\n Select 2 to enter enter correction mode \n");
printf("\n Select 3 to save the text \n");
printf("\n Select 4 to see the statistics about your text \n");
printf("\n Select 5 to exit the program\n");
scanf("\n%d", &choice);
return choice;
}
void insert_text(int numwords, char matrix[N][M], int posit) {
int i;
int j;
char word2[40] = { "" };
while (strcmp(word2, "*T*E*L*O*S*")) {
printf("\n Add the word \n");
scanf("\n%s", word2);
if (posit + 1 > numwords) {
printf("\n Out of Bounds \n ");
}
for (i = numwords - 2; i >= posit; i--) {
strcpy(matrix[i + 1], matrix[i]);
if (!i)
break;
}
strcpy(matrix[posit], word2);
j++;
}
for (i = 0; i < j; i++) {
printf("%s", matrix[i]);
printf("\n j is %d\n", j);
}
return;
}
The problem: I have a function called insert_text. This function adds a string in the 1st position of an array (at least that is what I think it does) and it is called if choice is 0 and executes itself until the string *Ī¤ELOS* is given. When in insert_text I print matrix I get a bunch of *(null)*s... I can count how many words matrix has (by declaring a variable j and incrementing by 1 inside the while loop, but that does not seem to work either. How can I fix this?

The printing code is incorrect: matrix is an array of N arrays of M characters, where you store null terminated C strings. As coded, you pass a single character just beyond the end of the array to printf for %s, which expects a string. The loop should be:
for (j = 0; j < N; j++) {
printf("%s ", matrix[j]);
}
Note that char matrix[N][M]; is uninitialized, so its contents will seem random. Initialize matrix as char matrix[N][M] = { "" };
Also note that in add_new_word_dictionary(), the scanf() conversion should be scanf("%49s", word); to prevent a potential buffer overflow if the user enters a very long word.
Same in insert_text, the code should be scanf("%39s", word2) ans you should test the return value to check for input errors.
Finally, arrays are indexed from 0 in C, so insert_text should be given a position of 0 and the number of words should be N, not M.
Both the test and the insertion loop have problems too.
Here is a modified version:
// call from main as insert_text(N, matrix, 0);
//
void insert_text(int numwords, char matrix[N][M], int posit) {
char word2[40];
int i, j = 0;
for (;;) {
printf("\n Add the word \n");
if (scanf("%39s", word2) != 1) {
break; // end of file or input error
}
if (!strcmp(word2, "TELOS")) {
break; // magic word
}
if (posit >= numwords) {
printf("\n Out of Bounds \n");
break;
}
for (i = numwords - 2; i >= posit; i--) {
strcpy(matrix[i + 1], matrix[i]);
}
strcpy(matrix[posit], word2);
j++;
}
for (i = 0; i < j; i++) {
printf("%s ", matrix[i]);
}
printf("\n j is %d\n", j);
}
Here is a modified version of the whole program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 500
#define M 100
/*Version 1*/
void replace_word(char *word);
void add_new_word_dictionary(void);
void do_nothing(void);
void return_basic(void);
void check_word(void);
void compute_words(void);
void compute_characters(void);
void compute_ch_sp(void);
void compute_num_dif_words(void);
void create_istogram(void);
void save_file(void);
int get_choice(void);
void return_word(void);
void insert_text(int numwords, char matrix[N][M], int posit);
int main() {
int j, done = 0;
char matrix[N][M] = { "" };
while (!done) {
switch (get_choice()) {
case 0:
insert_text(N, matrix, 0);
break;
case 1:
add_new_word_dictionary();
break;
case 2:
do_nothing();
break;
case 3:
save_file();
break;
case 4:
compute_words();
break;
default:
done = 1;
break;
}
for (j = 0; j < N; j++) {
if (matrix[j][0])
printf("%s ", matrix[j]);
}
printf("\n");
}
printf("\n End of Program \n");
return 0;
}
void add_new_word_dictionary(void) {
char word[50];
printf("\nPlease enter the word\n");
if (scanf("%49s", word) == 1)
printf("Your word is %s\n", word);
}
void replace_word(char *word) { printf("\n replace word \n"); }
void do_nothing(void) { printf("\n do_nothing \n"); }
void return_basic(void) { printf("\n return basic \n"); }
void check_word(void) { printf("\n check word \n"); }
void compute_words(void) { printf("\n compute_words \n"); }
void compute_characters(void) { printf("\n compute characters \n"); }
void compute_ch_sp(void) { printf("\n compute_ch_sp \n"); }
void compute_num_dif_words(void) { printf("\n compute_num_same_words \n"); }
void create_istogram(void) { printf("\n create istogram \n"); }
void save_file(void) { printf("\n save_file \n"); }
int get_choice(void) {
int choice = -1;
printf("\nSelect a choice from the below \n");
printf("Select 0 to add text \n");
printf("Select 1 to add new words in the dictionary \n");
printf("Select 2 to enter enter correction mode \n");
printf("Select 3 to save the text \n");
printf("Select 4 to see the statistics about your text \n");
printf("Select 5 to exit the program\n");
scanf("%d", &choice);
return choice;
}
// call from main as insert_text(N, matrix, 0);
//
void insert_text(int numwords, char matrix[N][M], int posit) {
char word2[40];
int i;
for (;;) {
printf("\n Add the word \n");
if (scanf("%39s", word2) != 1) {
break; // end of file or input error
}
if (!strcmp(word2, "TELOS")) {
break; // magic word
}
if (posit >= numwords) {
printf("\n Out of Bounds \n");
break;
}
for (i = numwords - 2; i >= posit; i--) {
strcpy(matrix[i + 1], matrix[i]);
}
strcpy(matrix[posit], word2);
posit++;
}
for (i = 0; i < posit; i++) {
printf("%s ", matrix[i]);
}
printf("\n posit is %d\n", posit);
}

Related

How to check if value exists in struct or not?

I want to ask you guys, here my code cannot check is my value is exist or not in struct, I've input the value, but none of them enter the if else condition, can anyone help me?
#include <stdio.h>
int main(){
int a,i;
struct data {
char nim[10];
};
struct data batas[100];
printf("TEST1 : "); scanf("%[^\n]s", batas[0].nim);
printf("TEST2 : "); scanf(" %[^\n]s", batas[1].nim);
printf("TEST3 : "); scanf(" %[^\n]s", batas[3].nim);
printf("TEST : "); scanf(" %[^\n]s", batas[a].nim);
for(i=0; i<a; i++){
if (batas[a].nim == batas[i].nim) {
printf("Value exist");
} else {
printf("Value doesn't exist");
}
}
return 0;
}
You can not compare array of chars with the equal operator, instead:
if (strcmp(batas[a].nim, batas[i].nim) == 0)
or
if (!strcmp(batas[a].nim, batas[i].nim))
you need to #include <string.h>
Also, note that you are using a uninitialized.
from what you give, it still can't enter the "Value exist" value. Here are my full line of code.
#include <stdio.h>
#include <string.h>
struct data {
char nim[10];
};
struct data batas[100];
int a=0, b, c, d;
int i, j;
char x[20];
void inputdata()
{
printf("\nInput Data\n");
printf("=======================\n");
printf("NIM : "); scanf("%s", batas[a].nim);
for(i=0; i<a; i++){
if (!strcmp(batas[a].nim, batas[i].nim)) {
strcpy(x, "FLAG");
} else {
strcpy(x, "FLAGX");
}
}
printf("%s", x);
a++;
}
void showdata()
{
j=0;
for(i=0; i<a; i++){
j = j + 1;
printf("\nData-%i", j);
printf("\nNIM : %s", batas[i].nim);
}
}
int main() {
int menu;
do {
printf("\nChoose input = "); scanf("%d", &menu);
switch(menu)
{
case 1 : inputdata(); break;
case 2 : showdata(); break;
}
}while (menu != 3);
return 0;
}

C programming call by reference pointer function to delete a member of a structure

This is for schoolwork and the question is asking to make a programme like a student database where I am able to input, print and remove students from the structure s using pointers function. However I am unable to delete the student records as something weird happens. The target student gets deleted but the rest of the students records(names only) are shifted, with only the first character being correct. Please help!
#include <stdio.h>
#include <string.h>
#define SIZE 50
typedef struct {
int id;
char name[50];
} Student;
void inputStud(Student *s, int size);
void printStud(Student *s, int size);
int removeStud(Student *s, int *size, char *target);
int main()
{
Student s[SIZE];
int size=0, choice;
char target[80], *p;
int result;
printf("Select one of the following options: \n");
printf("1: inputStud()\n");
printf("2: removeStud()\n");
printf("3: printStud()\n");
printf("4: exit()\n");
do {
printf("Enter your choice: \n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter size: \n");
scanf("%d", &size);
printf("Enter %d students: \n", size);
inputStud(s, size);
break;
case 2:
printf("Enter name to be removed: \n");
scanf("\n");
fgets(target, 80, stdin);
if (p=strchr(target,'\n')) *p = '\0';
printf("removeStud(): ");
result = removeStud(s, &size, target);
if (result == 0)
printf("Successfully removed\n");
else if (result == 1)
printf("Array is empty\n");
else if (result == 2)
printf("The target does not exist\n");
else
printf("An error has occurred\n");
break;
case 3:
printStud(s, size);
break;
}
} while (choice < 4);
return 0;
}
void inputStud(Student *s, int size)
{
int i=0;
char *p,dummy[50];
while (i<size) {
printf("Student ID: \n");
scanf("%d",&((s+i)->id));
printf("Student Name: \n");
scanf("\n");
fgets((s+i)->name, 50,stdin);
if (p=strchr((s+i)->name,'\n')) *p = '\0';
i++;
}
}
void printStud(Student *s, int size)
{
int i;
printf("The current student list: \n");
if (size==0) printf("Empty array\n");
else {
for (i=0; i<size; i++) {
printf("Student ID: %d ",(s+i)->id);
printf("Student Name: %s\n",(s+i)->name);
}
}
}
int removeStud(Student *s, int *size, char *target)
{
int i,j,k;
if (*size==0) return 1;
for (i=0;i<*size;i++) {
if (strcmp(((s+i)->name),target)==0) {
--*size;
for (j=i; j<=*size; j++) {
k = j + 1;
*((s+j)->name) = *((s+k)->name);
(s+j)->id = (s+j+1)->id;
if ((s+j+1)->id=='\0') (s+j)->id = '\0';
}
return 0;
}
}
return 2;
}
you were almost there.
The problem is at line 97: *((s+j)->name) = *((s+k)->name);
To make it work, this instruction should be substituted with:
strcpy((s+j)->name, (s+k)->name);
Why:
you are coping with char arrays, so doing *((s+j)->name) = *((s+k)->name) means: "put the value of the first char of s+k->name into s+j->name first char".
Instead, you want to copy the whole name of s+k into the s+j name.
on how to use strcpy you can take a look here

swap strings function in c with pointers

When I try to swap between strings in the function Update_student it doesn't make it. Why?
#include <stdio.h>
#include <string.h>
#define SIZE 1
struct student {
int id_number;
char name[50];
char sex[6];
int quiz_score[2];
int total_score;
};
void Add_Student_Records(struct student *pupil) {
printf("ID:");
scanf("%d", &pupil->id_number);
printf("Name: ");
scanf("%s", &pupil->name);
printf("Sex :");
scanf("%s", &pupil->sex);
for (int i = 0; i < 2; i++) {
printf("Quit score %d:", i + 1);
scanf("%d", &pupil->quiz_score[i]);
}
pupil->total_score = pupil->quiz_score[0] + pupil->quiz_score[1];
return;
}
void Add_Students(struct student *students) {
for (int i = 0; i < SIZE; i++) {
printf("Student %d:\n", i + 1);
Add_Student_Records(students);
}
return;
}
void Print_Students(struct student *students) {
for (int i = 0; i < SIZE; i++) {
printf("Student %d details: \n", i + 1);
printf("ID:%d\n", students->id_number);
printf("Name:%s\n", students->name);
printf("Sex:%s\n", students->sex);
for (int i = 0; i < 2; i++) {
printf("Quit score %d:\n", students->quiz_score[i]);
}
printf("Total score: %d\n", students->total_score);
students++;
}
return;
}
void Replace_Strings(char **old_string, char **new_string) {
*old_string = *new_string;
return;
}
void Update_Student(struct student *students) {
int i = 0;
char name[50], new_name[50], cur_name[50];
printf("You can update name, and scores.\n");
printf(" current Name: ");
scanf("%s", name);
printf("new name: ");
scanf("%s", &new_name);
while (i < SIZE) {
strcpy(cur_name, students->name);
if (strcmp(cur_name, name) == 0) {
char *ptr_old_stud_name = students->name;
char *ptr_new_stud_name = new_name;
Replace_Strings(&ptr_old_stud_name, &ptr_new_stud_name);
}
i++;
students++;
}
return;
}
int main() {
struct student students[SIZE];
char ch;
/*1.Add student, 2. Print student*/
printf("1.Add student\n2.Print students\n3.Update student\n");
scanf("%c", &ch);
while (ch != 'E') {
if (ch == '1') {
Add_Students(&students[0]);
}
else if (ch == '2') {
Print_Students(&students[0]);
}
else if (ch =='3') {
Update_Student(&students[0]);
}
printf("Another operation:\t");
scanf("%c", &ch);
}
}
Replace_Strings(&ptr_old_stud_name,&ptr_new_stud_name); passes the addresses of ptr_old_stud_name and ptr_new_stud_name to ReplaceStrings.
ptr_old_stud_name and ptr_new_stud_name are local variables. The first is a pointer that has been set to point to students->name. The second is a pointer that has been set to point to new_name.
Replace_Strings changes the first thing it is passed a pointer to to the second thing it is passed a pointer to. So it changes ptr_old_stud_name to have the value of ptr_new_stud_name.
The result is that the local variable ptr_old_stud_name has a new value. This does not change the thing it points to, students->name.
More specifically, ptr_old_stud_name was pointing to the first character of students->name. students->name is an array, and it cannot be altered by changing pointers to it, and its address cannot be changed. To change its contents, you must copy new values into the bytes within it, which you could do by using strcpy to copy bytes into it from new_name.
Your function Update_student is confusing, you should just iterate through the array of students and compare the student's name with cur_name and replace the name when there is a match.
You should also pass the number of students to handle as an argument.
Here is a modified version:
void Update_Student(struct student *students, int count) {
char cur_name[50], new_name[50];
printf("You can update name, and scores.\n");
printf(" current Name: ");
scanf("%49s", cur_name);
printf("new name: ");
scanf("%49s", new_name);
for (int i = 0; i < count; i++) {
if (strcmp(cur_name, students[i].name) == 0) {
strcpy(students[i].name, new_name);
}
}
}
Call from main as Update_Student(students, SIZE);
Note also that you should ignore whitespace when reading the commands by adding a space before the %c:
scanf(" %c", &ch);
Here is a modified version with for multiple students:
#include <stdio.h>
#include <string.h>
#define SIZE 10
struct student {
int id_number;
char name[50];
char sex[6];
int quiz_score[2];
int total_score;
};
int Add_Student_Records(struct student *pupil) {
printf("ID:");
if (scanf("%d", &pupil->id_number) != 1)
return 0;
printf("Name: ");
if (scanf("%49s", pupil->name) != 1)
return 0;
printf("Sex :");
if (scanf("%1s", pupil->sex) != 1)
return 0;
for (int i = 0; i < 2; i++) {
printf("Quiz score %d:", i + 1);
if (scanf("%d", &pupil->quiz_score[i]) != 1)
return 0;
}
pupil->total_score = pupil->quiz_score[0] + pupil->quiz_score[1];
return 1;
}
int Add_Students(struct student *students, int count) {
int i;
for (int i = 0; i < count; i++) {
printf("Student %d:\n", i + 1);
if (Add_Student_Records(students + i) == 0)
break;
}
return i;
}
void Print_Students(struct student *students, int count) {
for (int i = 0; i < count; i++) {
printf("Student %d details: \n", i + 1);
printf("ID:%d\n", students->id_number);
printf("Name:%s\n", students->name);
printf("Sex:%s\n", students->sex);
for (int i = 0; i < 2; i++) {
printf("Quit score %d:\n", students->quiz_score[i]);
}
printf("Total score: %d\n", students->total_score);
students++;
}
}
void Update_Student(struct student *students, int count) {
char cur_name[50], new_name[50];
printf("You can update name, and scores.\n");
printf(" current Name: ");
if (scanf("%49s", cur_name) != 1)
return;
printf("new name: ");
if (scanf("%49s", new_name) != 1)
return;
for (int i = 0; i < count; i++) {
if (strcmp(cur_name, students[i].name) == 0) {
strcpy(students[i].name, new_name);
}
}
}
int main() {
struct student students[SIZE];
int n = 0;
char ch = 'E';
/* print the menu */
printf("1. Add student\n"
"2. Print students\n"
"3. Update student\n");
scanf(" %c", &ch);
while (ch != 'E') {
if (ch == '1') {
if (n == SIZE) {
printf("student array is full\n");
} else {
/* add more students */
n += Add_Students(&students[n], SIZE - n);
}
} else
if (ch == '2') {
Print_Students(students, n);
} else
if (ch =='3') {
Update_Student(students, n);
}
scanf("%*[^\n]"); // consume the rest of the pending input line
printf("Another operation:\t");
if (scanf(" %c", &ch) != 1)
break;
}
return 0;
}

I want to printout them in ascending order with the given function code

I really need help for this, like i want to print out them and what do i need to adding to this function to work.
#include <stdio.h>
#include <stdlib.h>
#define nameSizeMax 31
#define listSizeMax 100
char studentList[listSizeMax][nameSizeMax];
int listSize;
void addStudent() {
if(listSize == listSizeMax) {
printf("List is full!\n\n");
} else {
printf("Enter name of the student: ");
fflush(stdin);
char name[nameSizeMax];
gets(name);
trim(name);
strupr(name);
strcpy(studentList[listSize], name);
listSize++;
printf("The new student have been added!\n\n");
}
}
int searchStd(char list[][nameSizeMax], char item[], int size) {
int i;
for(i=0;i<size; i++);
if (strcmp(list[i], item) == 0) return 1;
return -1;
}
void removeStudent() {
int i
if (listSize == 0) {
printf("List is empty!\n\n");
} else {
printf ("Enter name of the removed student: ");
fflush(stdin);
char name[nameSizeMax];
gets(name);
trim(name);
strupr(name);
int pos = searchStd(studentList, name, listSize);
}
if(pos == -1) {
printf("This student does not exist!\n\n");
} else {
for (i=pos; i<listSize-1; i++);
strcpy(studentList[i], studentList[i+1]);
printf("This student has been removed from the list: \n\n");
listSize--;
}
}
void fintStudent() {
int i;
printf("Enter the name of student you want to search: ");
fflush(stdin);
char name[nameSizeMax];
gets(name);
trim(name);
strupr(name);
int pos = searchStd(studentList, name, listSize);
if(pos == -1) {
printf("This student does not exist:\n\n");
} else {
printf("\n This is the student list in the order you entered: \n");
for(i=0; i<listSize; i++) printf("%d - %s\n", i, studentList[i]);
printf ("This student's postition in the list is: %d\n\n", pos);
}
}
void printStudentAsc(char list[][nameSizeMax], int size) {
int i,j:
if (listSize == 0) {
printf("List is empty!\n\n");
} else {
char **listP = (char **) calloc(sizeof(char *));
for (i=o; i<size; i++) listP[i] = list[i];
for (i=0; i<size-1; i++)
for(j=i+1; j<size; j++) {
char *ln1,*ln2;
ln1= lastname(listP[i]);
ln2= lastname(listP[j]);
if (strcmp(ln1, ln2) == 1) {
char *tmp = listP[i];
listP[i] =listP[j];
listP[j] = tmp;
}
}
}
for (i = 0; i < (*pn); i++)
{
nameStr(list[i]);
printf("Name[%d] : %s \n", i, list[i]);
}
}
int menu(){
printf("Menu:\n");
printf("1- Add a student\n");
printf("2- Remove a student\n");
printf("3- Search a student\n");
printf("4- Print out the student list in ascending order\n");
int userChoice;
do{
printf("Insert ur operation: "); scanf("%d", &userChoice);
}
}
Edited :'( i really struggle about the printAsc like i dont know what to do next . Its really messed me up here. Only the printStudentAsc.
the Menu interface that im not finish yet but i can hanlde this.

unknown error in c. this program not going to void Linear_Search() function

/int arr[n]; int n;/
void Linear_Search() {
int i, q, flag = 0, num, n;
int arr[n];
printf("Enter the number of array\n");
scanf("%d", n);
printf("Enter the numbers from which searched\n");
for (i = 0; i <= n; i++); {
scanf("%d", & arr[i]);
}
printf("enter the number to be searched\n");
scanf("%d", & q);
for (i = 0; i <= n; i++) {
if (q == arr[i]); {
num = q;
flag = 1;
}
}
if (flag == 1) printf("found! number is %d", num);
else printf("number not present in group\n");
getch();
}
void main() {
printf("ALL SEARCHING TECHNIQUE\n");
printf("Choices\n");
printf("1.Linear Search\n2.Binary Search\n3.Interpolation Search\n4.Jump Search\n");
void Linear_Search();
int select, l = 1;
scanf("%d", & select);
switch (select) {
case 1:
printf("This is Linear Search\n");
void Linear_Search();
break;
}
/case 2: printf("This is Binary Search\n"); void Binary_Search(); break; case 3: printf("This is Interpolation Search\n"); void Interpolation_Search(); break; case 4: printf("This is Jump Search\n"); void Jump_Search(); break; } printf("To continue PRESS 1 or PRESS ANY KEY"); scanf("%d",&l);/
getch();
}
You are including the return type of the function at the places where you are trying to call them. This turns them from a function call to a function prototype declaration. Remove the return type (void in these cases) at the places where the function shall be called.

Resources