I have got this template.
#include <stdio.h>
#include <string.h>
#define SIZE 10
int findTarget(char *target, char nameptr[SIZE][80], int size);
int main()
{
char nameptr[SIZE][80];
char t[40];
int i, result, size;
printf("Enter no. of names: ");
scanf("%d", &size);
printf("Enter %d names: ", size);
for (i = 0; i<size; i++)
scanf("%s", nameptr[i]);
printf("Enter target name: ");
scanf("\n");
gets(t);
result = findTarget(t, nameptr, size);
printf("findTarget(): %d\n", result);
return 0;
}
int findTarget(char *target, char nameptr[SIZE][80], int size)
{
/* write your code here */
int i;
for (i = 0; i < size; i++) {
if (nameptr[i] == *target)
return i;
}
return -1;
}
And the code under /* write your code here */ is my code.
The code doesn't work. I think something is wrong with (nameptr[i] == *target).
Examples of output:
Enter no. of names: 4
Enter 4 names: Peter Paul John Mary
Enter target name: John
findTarget(): 2
Enter no. of names: 4
Enter 4 names: peter mary john steve
Enter target name: may
findTarget(): -1
I think the template is correct cos its provided by school.
Thank you for helps.
This:
if (nameptr[i] == *target)
is wrong because you are comparing a pointer with an integer and that makes no sense. Also, in order to compare two strings, use strcmp. Using == will compare the pointers and not the content of them.
Fix:
if (strcmp(nameptr[i], target) == 0)
Related
The task is: Develop a function that extracts from a sentence the first word containing a given combination of characters. Use the keyboard to enter a few sentences and letter combinations. Based on the developed function, extract from all the entered sentences all the words containing the given letter combination. Print the result of the extraction.
Here's what I already have:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int i = 0, k = 0;
char sentences[20][100], search[20];
void Input(void);
void Find(char search[]);
int main() {
system("chcp 1251");
Input();
Find(search);
return 0;
}
void Input() {
printf("Enter number of sentences:\n");
scanf_s("%d", &k);
rewind(stdin);
printf("Enter %d sentences:\n", k);
for (i = 0; i < k; i++) {
gets_s(sentences[i]);
}
rewind(stdin);
printf("Enter letter combination:\n");
gets_s(search);
}
void Find(char search[]) {
int coinc = 0;
printf("\n");
for (i = 0; i < k; i++) {
if (strstr(sentences[i], search)) {
printf("%s\n", sentences[i]);
coinc++;
}
}
printf("\nCoincidence is %found.\n", (coinc > 0) ? "":"not ");
}
Example:
Input:
Nice weather
It`s nice to see you!
Hi there
She`s a nice girl
Find:
ice
Output:
weather
It`s to see you
She`s a girl
This question already has answers here:
How to access a local variable from a different function using pointers?
(10 answers)
Closed 1 year ago.
I have written a program which makes use of array of structures in order to maintain a sort of "database" program with different options that can be used to manipulate the "database".
The program has 4 modes of operation, if the user enters:
'i' data can be inserted into the "database".
's' searches the "database" for a part with a part number of a item.
'u' updates something in the database based on the part number of a item.
'p' prints the whole "database".
Here is the code which is made of 3 files:
database.h:
#ifndef DATABASE
#define DATABASE
struct db
{
int part_number;
char *part_name;
int part_quantity;
};
extern struct db database[50];
extern void insert(int i);
extern int search(int i);
extern int update(int i);
extern int print(int i);
#endif
database.c
#include <string.h>
#include <stdio.h>
#include "database.h"
struct db database[50];
void insert(int i)
{
char name_of_part[21], c;
printf("%p\n", &database[i].part_name);
printf("\n");
printf("Enter a part number: ");
scanf("%d", &database[i].part_number);
while((c = getchar()) != '\n' && c != EOF); // flush stdin
printf("Enter a part name: ");
fgets(name_of_part, 20, stdin);
printf("Enter quantity of part: ");
scanf("%d", &database[i].part_quantity);
database[i].part_name = name_of_part;
printf("\n");
}
int search(int i)
{
int input;
printf("\n");
printf("Enter a part number: ");
scanf("%d", &input);
for (int j = 0; j <= i; j++)
{
if (database[j].part_number == input)
{
printf("Part name: %s\n", database[j].part_name);
printf("Quantity on hand: %d\n", database[j].part_quantity);
return 0;
}
}
printf("Part not found.\n");
}
int update(int i)
{
int input, quantity;
printf("\n");
printf("Enter part number: ");
scanf("%d", &input);
for (int j = 0; j <= i; j++)
{
if (database[j].part_number == input)
{
printf("Enter part quantity: ");
scanf("%d", &quantity);
database[j].part_quantity = quantity;
return 0;
}
}
printf("Part number not found.");
}
int print(int i)
{
for (int j = 0; j < i; j++)
{
printf("Part number: %d\n Part name: %s\n Part quantity: %d\n", database[j].part_number, database[j].part_name,database[j].part_quantity);
}
}
main.c
#include <stdio.h>
#include <string.h>
#include "database.h"
int main()
{
int i = 0;
char code;
while (1)
{
printf("Enter a function code: ");
scanf(" %c", &code);
switch (code)
{
case 'i':
insert(i);
i += 1;
break;
case 's':
search(i);
break;
case 'u':
update(i);
break;
case 'p':
print(i);
break;
}
}
return 0;
}
The problem i have is that when i insert into the "database", the name in each structure gets overwritten. for example:
Enter a function code: i
Enter a part number: 111
Enter a part name: 111
Enter quantity of part: 111
Enter a function code: i
Enter a part number: 222
Enter a part name: 222
Enter quantity of part: 222
Enter a function code: p
Part number: 111
Part name: 222
Part quantity: 111
Part number: 222
Part name: 222
Part quantity: 222
Enter a function code:
As you can see first i insert something new in the "database", take note of the "Part name" which is "111".
Next i insert something else into the database
this time the "Part name" is "222".
Lastly i print the whole "database" what i am confused about is why the part name has now overlapped. but why is this? all the other members such as the part_number and part_quantity remain intact in both insert operations so why does char *part_name stay the same ? and how do i fix this ?
You have the part_name member declared as a char * and you assign to it the address of a local array in the insert function. When the function returns, that array goes out of scope and the stored pointer becomes invalid. Subsequently trying to use that pointer triggers undefined behavior.
Change part_name to be an array:
struct db
{
int part_number;
char part_name[21];
int part_quantity;
};
And write directly to that:
printf("Enter a part name: ");
fgets(database[i].part_name, 21, stdin);
The line
database[i].part_name = name_of_part;
is bad. This is assigning a pointer to the non-static local variable. The variable ends its life on returning from the function and dereferencing pointers pointing to that is illegal.
Instaed of this, you have to copy the string. If you system supports strdup(), it can be done like this:
database[i].part_name = strdup(name_of_part);
If strdup() is not supported or you want to stick to the standard, you dan do like this:
database[i].part_name = malloc(strlen(name_of_part) + 1); /* +1 for ther terminating null-character */
if (database[i].part_name != NULL)
{
strcpy(database[i].part_name, name_of_part);
}
Add #include <stdlib.h> to use malloc().
I am programming a registration system using array strings for postal code and home address. I use a constant to determine the postal code limit of just 8 characters.
When the program start the register function, it makes the address and postal code inputs correct, but when I list it, the address appears normal and the postal code of position 1 together with the others below. Why is this happening? I put 8 character positions for the postal code and it increases by placing the second one as well.
My program:
#include <stdio.h>
#define LIMIT_POSTAL 8
#define LIMIT_REGISTER 5
#define LIMIT_ADDRESS 20
char postal_c[LIMIT_REGISTER][LIMIT_POSTAL], address[LIMIT_REGISTER][LIMIT_ADDRESS];
int line;
void reg()
{
int op;
do
{
printf("Address: ");
scanf("%s", &address[line]);
printf("Postal code: ");
scanf("%s", &postal_c[line]);
op = -1;
printf("1 - Continue\nAny number - Exit\n");
scanf("%d", &op);
line++;
} while(op == 1);
}
int main()
{
int i;
reg();
for(i = 0; i < line; i++)
{
printf("Address: %s\n", address[i]);
printf("Postal: %s\n", postal_c[i]);
}
return 0;
}
Output:
Address: foo
Postal code: 11111111
1 - Continue
Any number - Exit
1
Address: foo2
Postal code: 22222222
1 - Continue
Any number - Exit
0
Address: foo
Postal: 1111111122222222
Address: foo2
Postal: 22222222
In your code probably:
#include <stdio.h>
#define LIMIT_POSTAL 8
#define LIMIT_REGISTER 5
#define LIMIT_ADDRESS 20
char postal_c[LIMIT_REGISTER][LIMIT_POSTAL], address[LIMIT_REGISTER][LIMIT_ADDRESS];
int line;
void reg()
{
int op;
do
{
printf("Address: ");
scanf("%s", &address[line]);
printf("Postal code: ");
scanf("%s", &postal_c[line]);
op = -1;
printf("1 - Continue\nAny number - Exit\n");
scanf("%d", &op);
line++;
} while(op == 1);
}
int main()
{
int i;
reg();
for(i = 0; i < line; i++)
{
printf("Address: %s\n", address[i]);
printf("Postal: %s\n", postal_c[i]);
}
return 0;
}
I can't see you had initialized line variable in you program and you are using it directly to pointing the index, hence you didn't assigned any value so probably it contains garbage value and pointing invalid memory address in your program.
I am assuming your rest code is correct.
try doing...
int line =0;
I have to declare a vector with the "struct" type which, for every n students, it creates a value for the group that student belongs to (which is like a counter), their names and their grades.
The program has to output the name of the students with the highest grade found in these groups. I have to allocate the vector on the heap (I only know the theoretical explanation for heap, but I have no idea how to apply it) and I have to go through the vector using pointers.
For example if I give n the value 4, there will be 4 students and the program will output the maximum grade together with their names as shown here.
This will output Ana 10 and Eva 10.
I gave it a try, but I have no idea how to expand it or fix it so I appreciate all the help I can get with explanations if possible on the practical application of heap and pointers in this type of problem.
#include <stdio.h>
#include <stdlib.h>
struct students {
int group;
char name[20];
int grade;
};
int main()
{
int v[100], n, i;
scanf("%d", n);
for (i = 0; i < n; i++) {
v[i].group = i;
scanf("%s", v[i].name);
scanf("%d", v[i].grade);
}
for (i = 0; i < n; i++) {
printf("%d", v[i].group);
printf("%s", v[i].name);
printf("%d", v[i].grade);
}
return 0;
}
Here I was just trying to create the vector, nothing works though..
It appears, int v[100]; is not quite what you want. Remove that.
You can follow either of two ways.
Use a VLA. After scanning the value of n from user, define the array like struct students v[n]; and carry on.
Define a fixed size array, like struct students v[100];, and use the size to limit the loop conditions.
That said,
scanf("%d", n); should be scanf("%d", &n);, as %d expects a pointer to integer type argument for scanf(). Same goes for other cases, too.
scanf("%s", v[i].name); should better be scanf("%19s", v[i].name); to avoid the possibility of buffer overflow by overly-long inputs.
Even though you are asking for the number of students (groups) using scanf, you hardcoded the upper bound of this value using v[100]. So, I passed your input variable n (the number of students) to malloc in order to allocate the space you need for creating an array of n students.
Also, I used qsort to sort the input array v where the last element would be the max value. Here qsort accepts an array of structs and deference the pointers passed to the comp function to calculate the difference of the comparison.
Finally, I printed the sorted array of structs in the last loop.
#include <stdio.h>
#include <stdlib.h>
struct students {
int group;
char name[20];
int grade;
};
int comp(const void *a, const void *b)
{
return ((((struct students *)a)->grade > ((struct students *)b)->grade) -
(((struct students *)a)->grade < ((struct students *)b)->grade));
}
int main()
{
int n;
printf("Enter number of groups: ");
scanf("%d", &n);
printf("\n");
struct students *v = malloc(n * sizeof(struct students));
int i;
for(i = 0; i < n; i++)
{
v[i].group = i;
printf("\nName: ");
scanf("%s", v[i].name);
printf("Grade: ");
scanf("%d", &v[i].grade);
}
qsort(v, n, sizeof(*v), comp);
for(i = 0; i < n; i++)
{
printf("Group %d, Name %s, grade %d\n", v[i].group, v[i].name, v[i].grade);
}
return (0);
}
You need to replace the standalone array v[100], with an array of structs referencing your structure:
struct students v[100];
However, if you want to use malloc to allocate memory on the heap, you will need to do something like this:
struct students *students = malloc(n * sizeof(struct students));
/* Check void* return pointer from malloc(), just to be safe */
if (students == NULL) {
/* Exit program */
}
and free the requested memory from malloc() at the end, like this:
free(students);
students = NULL;
Additionally, adding to #Sourav Ghosh's answer, it is also good to check the return value of scanf(), especially when dealing with integers.
Instead of simply:
scanf("%d", &n);
A more safe way is this:
if (scanf("%d", &n) != 1) {
/* Exit program */
}
With all this said, your program could look something like this:
#include <stdio.h>
#include <stdlib.h>
#define NAMESTRLEN 20
typedef struct { /* you can use typedef to avoid writing 'struct student' everywhere */
int group;
char name[NAMESTRLEN+1];
int grade;
} student_t;
int
main(void) {
int n, i;
printf("Enter number of students: ");
if (scanf("%d", &n) != 1) {
printf("Invalid input.\n");
exit(EXIT_FAILURE);
}
student_t *students = malloc(n * sizeof(*students));
if (!students) {
printf("Cannot allocate memory for %d structs.\n", n);
exit(EXIT_FAILURE);
}
for (i = 0; i < n; i++) {
students[i].group = i;
printf("Enter student name: ");
scanf("%20s", students[i].name);
printf("Enter students grade: ");
if (scanf("%d", &(students[i].grade)) != 1) {
printf("Invalid grade entered.\n");
exit(EXIT_FAILURE);
}
}
printf("\nStudent Information:\n");
for (i = 0; i < n; i++) {
printf("Group: %d Name: %s Grade: %d\n",
students[i].group,
students[i].name,
students[i].grade);
}
free(students);
students = NULL;
return 0;
}
The question:
Read up to 6 pairs of names and ages into TWO separate arrays, and use a linear search to locate a target name and to print that person’s age. The two arrays are called names and ages:
I am getting lots of errors .. I am not sure about passing the arrays into functions..
#include <stdio.h>
#define ASIZE 20
#define RECSIZE 6
struct record {
char name[ASIZE];
int age[ASIZE];
};
struct record na[RECSIZE];
int linearSearch(struct record *a, char *find)
{
int x;
for(x=0; x<RECSIZE; x++)
{
// if(na[x].name==find[x])
if(a->name[x]==find[x])
{
return x;
}
}
return -1;
}
int main()
{
int i;
for (i=0; i<RECSIZE; i++)
{
printf("Enter name: ");
scanf("%s",na[i].name);
printf("Enter age: ");
scanf("%i",&na[i].age);
}
printf("Enter the Search name: ");
char temp[ASIZE];
scanf("%s",temp[ASIZE]);
int result;
result=linearSearch(&na, &temp[]);
printf("%i", result);
return 0;
}
Please help.
The error is in:
result=linearSearch(&na, &temp[]);
#include <stdio.h>
#include <string.h>
#define ASIZE 20
#define RECSIZE 6
struct record {
char name[ASIZE];
int age;
};
struct record na[RECSIZE];
int linearSearch(struct record *a, char *find){
int x;
for(x=0; x<RECSIZE; x++){
if(strcmp(a[x].name, find)==0)
return x;
}
return -1;
}
int main(){
int i;
for (i=0; i<RECSIZE; i++){
printf("Enter name: ");
scanf("%s", na[i].name);//No protection when entered past the buffer
printf("Enter age: ");
scanf("%i", &na[i].age);
}
printf("Enter the Search name: ");
char temp[ASIZE];
scanf("%s", temp);
int result;
result=linearSearch(na, temp);
printf("%i", result);
return 0;
}
On my system, the compiler gave me these errors for your exact code. Just look at the line numbers (should be exactly like yours) and address each error by looking at the error description. Once you address these, you will be further down the path of understanding your execution flow: