Ok so i am trying to write a function that checks whether or not a letter of a word exists within an array of strings(It does that for every letter in the word). After tinkering with it for a while, i figured that it crashed when it tried to use the strcmp(). I don't know what i am doing wrong since i just started learning C so any help would be appreciated. Here is the function:
char SingleChar(char *lex, int wordnum,char *word){
int i,j,k;
for(i=0;i<strlen(word);i++){
for(j=0;j<wordnum;j++){
for(k=0;k<strlen(lex[j]);k++){
if(strcmp(word[i],lex[k])){
return word[i];
}
}
}
}
return 0;
}
You have a misunderstanding about what char * means. It is a pointer to character. In C string are just a pointer to a character, flowed by other characters and a null terminator. What this means in your case, is that lex is a single string, not a list of strings.
ie
char *a = "imastring"; denotes that a is the address of a sequential piece of memory containing the characters [i][m][a][s][t][r][i][n][g][\0]. In C the null terminator is used to denote the end of a string.
What this means is that when you are calling strlen(lex[j]) you are just referencing a single character in lex and then reading to the end of the string, so your result will just decrease monotonically.
You probably want to do is use a double pointer. char ** list will point to an address, which points to an address referencing a block of sequential characters.
char ** list = (char **)malloc(sizeof(char *) * 5); would allocate you 5 sequential memory address which could then point to strings themselves. And you can assign them values as follows.
list[0] = a
I hope this helps.
Don't really see an array of strings... Your C file should look roughly like this:
#include <stdio.h>
char SingleChar(char *lex, int wordnum, char *word){"your function in here"};
int main(){
// Declare your variables here
// Call your function here SingleChar(params)
return 0;
}
To compare characters:
if(word[i]==lex[k]){
return word[i];
break;
}
Not quite sure what you are trying to do with your function other than that. You need to be more specific, I don't see your array of strings input.
In C there is no true string type. A string in C is just an array of characters.
An array of strings would be an array of pointers to an array of characters in memory.
If you wanted to check for a letter within an array of "strings".
You would want a pointer that moves through each letter of the array and compares each character.
The strcmp() function will return true (1) or false (0), depending on whether the strings are equal or not.
So what you'd want I think is for your program to compare the characters of your word with every other word in the array of strings.
This program goes through the entire word then tells you if the letter exists.
For each letter of whatever word you enter.
--
#include <stdio.h>
#include <string.h>
/*
Function to check for a letter of a word
in an array of strings */
void singleChar(char *word,int arrlength, char *strings[])
{
int length = 0;
length = strlen(word); /* Calculates the length of the string */
for(int y = 0; y < arrlength ; y++) /*Increments to the next word in the array */
{
for(int i=0; i <= length ; i++) /*increments to the next letter of the word you want to check */
{
for(int x=0; x < strlen(strings[y]) ; x++) /*Increments x based on the length of the string */
{
char *p = strings[y];
if(word[i] == p[x]) /*Compares the the first letter of both strings */
{
printf("The letter %c exists.\n", word[i]);
}
}
}
}
}
int main ( void )
{
/*Example */
char *p = "Hello";
char *a[2];
a[0]="Hello";
singleChar(p, 1,a);
}
Related
I want to preface my question by mentioning that I am a CS student that is very new to coding.
I am attempting to write a script that will add a set of array of characters to two arrays that are nested within a loop. The array of characters are prefixes for two courses, and I am using a function called "matcher" (that accepts an array that will hold a prefix, and an integer that holds the course number that we want to match to the corresponding prefix) within the loop.
The issue that I am facing is that when I run this, the first array(.prefix3) gets concatenated with the prefix for the second array(.prefix4), which seems to happen after the loop runs for a second time. I am unsure as to why this is occurring, specially since each array can only hold 7 characters. Here is the code, thank you all in advance:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char name[20];
int ID;
int number_of_courses;
int course_numbers[4];
char prefix1[7];
char prefix2[7];
char prefix3[7];
char prefix4[7];
int taken;
} student_info;
void matcher(char *,int );
int main()
{
student_info students[100];
int j=2;
int course_placeholder;
for(int i=0;i<2;i++)
{
printf("Enter course number %d:",i+1);//Type "9696" or "1232"
scanf("%d",&course_placeholder);
if(j==1)
{
matcher(students[0].prefix2,course_placeholder);
}
else if(j==2)
{
matcher(students[0].prefix3,course_placeholder);//this is concatenating the string for some reason. Trying to determine why.
}
else if(j==3)
{
matcher(students[0].prefix4,course_placeholder);
}
j++;
}
printf("%s\n%s\n",students[0].prefix3,students[0].prefix4);//students[0].prefix3 is concatenating for an unknown reason.
return 0;
}
void matcher(char *prefix_placeholder,int course_placeholder)
{
if(course_placeholder==9696)
{
strcpy(prefix_placeholder,"MAT 236");
}
else if(course_placeholder==1232)
{
strcpy(prefix_placeholder,"COP 220");
}
}
Although you cannot see it, string literals with 7 visible characters, such as this one:
"COP 220"
^ - NULL terminator is implied here
actually contain 8 characters, not 7. The last character is \0 ( AKA NULL )
So, when allocating memory in an array which is designed to contains C strings ( defined as a NULL terminated char array ) always include space enough for the NULL
char prefix1[8] = {0}; //1 extra element for NULL, all elements initialized to NULL
To test this yourself, do this:
size_t size = sizeof "MAT 236" ;//expect size == 8 (includes NULL)
int len = strlen("MAT 236");//expect len == 7 (does not include NULL)
The arrays
char prefix1[7];
char prefix2[7];
char prefix3[7];
char prefix4[7];
are too short to store 7-character strings like "MAT 236" and "COP 220" because they require at least 8-character arrays including terminating null-characters.
Allocate enough elements to avoid troubles.
I am rather new to the C language right now and I am trying some practice on my own to help me understand how C works. The only other language I know proficiently is Java. Here is my code below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const char * reverse(char word[]);
const char * reverse(char word[]) {
char reverse[sizeof(word)];
int i, j;
for (i = sizeof(word - 1); i <= 0; i--) {
for (j = 0; j > sizeof(word - 1); j++) {
reverse[i] = word[j];
}
}
return reverse;
}
int main() {
char word[100];
printf("Enter a word: ");
scanf("%s", word);
printf("%s backwards is %s\n", word, reverse(word));
return 0;
}
When the user enters a word, the program successfully prints it out when i store it but when i call the reverse function I made it doesnt return anything. It says on my editor the address of the memory stack is being returned instead and not the string of the array I am trying to create the reverse of in my function. Can anyone offer an explanation please :(
sizeof(word) is incorrect. When the word array is passed to a function, it is passed as a pointer to the first char, so you are taking the size of the pointer (presumably 4 or 8, on 32- or 64-bit machines). Confirm by printing out the size. You need to use strlen to get the length of a string.
There are other problems with the code. For instance, you shouldn't need a nested loop to reverse a string. And sizeof(word-1) is even worse than sizeof(word). And a loop that does i-- but compares i<=0 is doomed: i will just keep getting more negative.
There are multiple problems with your reverse function. C is very different from Java. It is a lot simpler and has less features.
Sizes of arrays and strings don't propagate through parameters like you think. Your sizeof will return wrong values.
reverse is an identifier that is used twice (as function name and local variable).
You cannot return variables that are allocated on stack, because this part of stack might be destroyed after the function call returns.
You don't need two nested loops to reverse a string and the logic is also wrong.
What you probably look for is the function strlen that is available in header string.h. It will tell you the length of a string. If you want to solve it your way, you will need to know how to allocate memory for a string (and how to free it).
If you want a function that reverses strings, you can operate directly on the parameter word. It is already allocated outside the reverse function, so it will not vanish.
If you just want to output the string backwards without really reversing it, you can also output char after char from the end of the string to start by iterating from strlen(word) - 1 to 0.
Edit: Changed my reverse() function to avoid pointer arithmetic and to allow reuse of word.
Don't return const values from a function; the return value cannot be assigned to, so const doesn't make sense. Caveat: due to differences between the C and C++ type system, you should return strings as const char * if you want the code to also compile as C++.
Arrays passed as params always "decay" to a pointer.
You can't return a function-local variable, unless you allocate it on the heap using malloc(). So we need to create it in main() and pass it as a param.
Since the args are pointers, with no size info, we need to tell the function the size of the array/string: sizeof won't work.
To be a valid C string, a pointer to or array of char must end with the string termination character \0.
Must put maximum length in scanf format specifier (%99s instead of plain %s — leave one space for the string termination character \0), otherwise vulnerable to buffer overflow.
#include <stdio.h> // size_t, scanf(), printf()
#include <string.h> // strlen()
// 1. // 2. // 3. // 4.
char *reverse(char *word, char *reversed_word, size_t size);
char *reverse(char *word, char *reversed_word, size_t size)
{
size_t index = 0;
reversed_word[size] = '\0'; // 5.
while (size-- > index) {
const char temp = word[index];
reversed_word[index++] = word[size];
reversed_word[size] = temp;
}
return reversed_word;
}
int main() {
char word[100];
size_t size = 0;
printf("Enter a word: ");
scanf("%99s", word); // 6.
size = strlen(word);
printf("%s backwards is %s\n", word, reverse(word, word, size));
return 0;
}
Essentially I'm trying to strcat a letter from a 2d array onto a 1d array. I've got this user inputted grid of letters and from these letters I'm combining them letter by letter into a 1d array and checking it against a dictionary to see if its a valid word.
I've been trying something like
strcat(wordTester, board[i][j]);
but I keep getting runtime errors. Any help would be appreciated.
strcat() is for connecting null-terminated string, so passing a character to it will lead to crush because the character will likely converted to an invalid pointer.
Try using this functon:
#include <string.h>
char* charcat(char *target, char c) {
size_t len;
if (target != NULL) {
len = strlen(target);
target[len] = c;
target[len + 1] = '\0';
}
return target;
}
Usage (assuming char wordTester[MAX]; char board[M][N]; where MAX, M and N are properly defined):
charcat(wordTester, board[i][j]);
I'm new in C programming and I'm trying to make a function that sends what is stored in one array character that each time is going to change. So if my array is first "hello" it should send only 5 characters, but if later is "goodbye" it should send 7. What I want to avoid is have to write a lot of characters if I want to extend my array, like in this:
int say (buttonpressed){
char a[11] = {'h','e','l','l','o'};
int i;
for (i = 0;i<12;i++)
{
U2TXREG = a[i];
while(U2STAbits.TRMT==0);
}
buttonpressed = 0;
return 0;
}
I would apreciate any ideas, thanks!
You need to know the length of your array or use an End-Of-String character (which usually is \x0 - a binary zero).
int say (buttonpressed){
char* a = "hello";
int i;
int size=strlen(a);
for (i = 0;i<size;i++)
{ //rest as before
By using a string constant you initialize the array to end with a null (0) char. This can then be used to find the string length using strlen.
I have also just used a pointer to the string constant as you are not modifying it.
You really need to explain more what do you want to do.
From what you say I understand that you want to change the size and contents of your array without changing the for loop.
If that's the case you can use this:
#define ARRAY_LENGTH 12 /* 12 is an example */
int say (buttonpressed)
{
char a[ARRAY_LENGTH] = { . . . . };
int i;
for(i =0; i<ARRAY_LENGTH; i++){
...
}
....
}
I would store the data and the actual size in a struct (similiar to how you would use a std::vector in C++
struct vec{
char data[11];
unsigned int size;
}
Then in your for loop can just loop from i=0 to i
If your array is always going to be a string, a c-style string would be idiomatic in c. This is just an char array terminated by \0, and test for \0 while looping over the array.
An array of pointers to strings is provided as the input. The task is to reverse each string stored in the input array of pointers. I've made a function called reverseString() which reverses the string passed to it. This functions works correctly as far as i know.
The strings stored/referenced in the input array of pointers are sent one by one to the reverseString() function. But the code hangs at some point in the reverseString() function when the values of the passed string are swapped using a temp variable. I can't figure out why the code is hanging while swapping values. Please help me with this.
The code is as follows:
#include <stdio.h>
void reverseString(char*);
int main()
{ char *s[] = {"abcde", "12345", "65gb"};
int i=0;
for(i=0; i< (sizeof(s)/sizeof(s[0]) ); i++ )
{ reverseString(s[i]);
printf("\n%s\n", s[i]);
}
getch();
return 0;
}//end main
void reverseString(char *x)
{ int len = strlen(x)-1;
int i=0;
char temp;
while(i <= len-i)
{ temp = x[i];
x[i] = x[len-i];
x[len-i] = temp;
i++;
}
}//end reverseString
You are trying to change string literals.
String literals are usually not modifiable, and really should be declared as const.
const char *s[] = {"abcde", "12345", "65gb"};
/* pointers to string literals */
If you want to make an array of modifiable strings, try this:
char s[][24] = {"abcde", "12345", "65gb"};
/* non-readonly array initialized from string literals */
The compiler will automatically determine you need 3 strings, but it can't determine how long each needs to be. I've made them 24 bytes long.
The strings ("abcde" etc) could be stored in readonly memory. Anything is possible when you try to modify those strings, therefore. The pointers to the strings are modifiable; it is just the strings themselves that are not.
You should include <string.h> to obtain the declaration of strlen(3), and another header to obtain the function getch() - it is not in <stdio.h> on my MacOS X system (so I deleted the call; it is probably declared in either <stdio.h> or <conio.h> on Windows).
Hope this helps you! what i am doing here is that i am going to the address of the last character in the string then printing them all by decreasing the pointer by 1 unit (for character its 2 bytes(please check)).
//program to reverse the strings in an array of pointers
#include<stdio.h>
#include<string.h>
int main()
{
char *str[] = {
"to err is human....",
"But to really mess things up...",
"One needs to know C!!"
};
int i=0; //for different strings
char *p; //declaring a pointer whose value i will be setting to the last character in
//the respective string
while(i<3)
{
p=str[i]+strlen(str[i])-1;
while(*p!='\0')
{
printf("%c",*p);
p--;
}
printf("\n");
i++;
}
}