I am writing a function longestStrInAr() that takes in an array of strings str and size (>0) as parameters, and returns the longest string and also the length of the longest string.
If two or more strings have the same longest string length, then the first appeared string will be
returned to the calling function.
This is the main function:
#include <stdio.h>
#include <string.h>
#define N 20
char *longestStrInAr(char str[N][40], int size, int *length);
int main()
{
int i, size, length;
char str[N][40], first[40], last[40], *p, *result;
char dummychar;
printf("Enter array size: \n");
scanf("%d", &size);
scanf("%c", &dummychar);
for (i=0; i<size; i++) {
printf("Enter string %d: \n", i+1);
fgets(str[i], 40, stdin);
if (p=strchr(str[i],'\n')) *p = '\0';
}
result = longestStrInAr(str, size, &length);
printf("longest: %s \nlength: %d\n", result, length);
return 0;
}
This is the function I have to write:
char *longestStrInAr(char str[N][40], int size, int *length)
{
int i,j, len;
*length =0;
char *longstr;
for (i = 0; i< size; i++){
j = 0;
len = 0;
while (str[i][j]!='\0'){
len++;
j++;
if (len > *length){
*length = len;
longstr = str[i];
}
}
}
return longstr;
}
My test input is
Enter array size:
4
Enter string 1:
Kenny
Enter string 2:
Mary
Enter string 3:
Peter
Enter string 4:
Sun
In XCode, I am able to receive the correct output:
longest: Kenny
length: 5
But using 2 different online compilers, I get the output below on both occasions:
longest: Kenny
length: 6
Why does my length differ?
Thank you.
probably one of them is a windows based compiler.
there "\n" is tread as two characters \r and \n
\r is called as carriage return
\n is called as line feed.
with this you get a byte extra there.
Related
I'm new to c programming, and i'm suppose to write a code to find the longest string and it's string length from an array of strings. This is my code so far.
#include <stdio.h>
#include <string.h>
#define N 20
char *longestStrInAr(char str[N][40], int size, int *length);
int main()
{
int i, size, length;
char str[N][40], first[40], last[40], *p;
char dummychar;
printf("Enter array size: \n");
scanf("%d", &size);
scanf("%c", &dummychar);
for (i=0; i<size; i++) {
printf("Enter string %d: \n", i+1);
gets(str[i]);
}
p = longestStrInAr(str, size, &length);
printf("longest: %s \nlength: %d\n", p, length);
return 0;
}
char *longestStrInAr(char str[N][40], int size, int *length)
{
int i,j=0;
int len = 0;
*length = 0;
char word[N];
for(i=0;i<size;i++){
while(str[i][j]!='\0'){
len++;
j++;
}
if(*length<len){
*length = len;
strcpy(word,str[i]);
}
}
return word;
}
The main{} is a given function, and the code under *longestStrInAr is the one im suppose to write. However, my current code is only able to give me the longest string length, and prints out (null) instead of the longest string.
my output
Problems I see:
Problem 1
Don't use gets. It's a security hole. Use fgets instead.
fgets(str[i], 40, stdin);
Problem 2
You are using incorrect size for word. It needs to be of size 40.
char word[40];
Problem 3
You are returning a pointer to the first element of word from
longestStrInArr. However, that memory is invalid once the function returns. Hence, your program has undefined behavior.
You can fix it by returning the index of the longest string in str or by providing an input argument long enough to hold the longest string.
size_t longestStrInAr(char str[N][40], int size, int *length)
{
size_t index = 0
size_t i,j=0;
int len = 0;
*length = 0;
for(i=0;i<size;i++){
while(str[i][j]!='\0'){
len++;
j++;
}
if(*length<len){
*length = len;
index = i;
}
}
return index;
}
and then use it as:
size_t index = longestStrInAr(str, size, &length);
printf("longest: %s \nlength: %d\n", str[index], length);
You copy the string into local variable and then return pointer to it. But after returning, the variable is no longer valid. That is undefined behavior and "anything" can happen. In this case it seems some optimization or a debug helper turns it to null.
Instead just keep a pointer to the longest string in the str array, don't copy anything and return that pointer. Alternatively, if you want to simplify it, return the i index of the longest string.
I was writing a program to reverse an entered string in C and my code is :
#include<stdio.h>
#include<string.h>
void main()
{
int sz;
printf("Enter the size of the string : ");
scanf("%d",&sz);
char str[sz];
gets(str);
printf("Enter the string : \n");
gets(str);
char str1[sz];
int i =0;
--sz;
for(i=0;i<=sz;i++)
{
str1[sz-i]=str[i];
}
printf("%s",str1);
}
well this program is giving an weird output for string sizes 8,9 and 10
for size 8 the reversed string is being printed followed by a space and 2 garbage characters,for size 9 the reversed string is being printed followed by 2 garbage characters and for size 10 the reversed string is being printed by a garbage character and for other string sizes the program is running properly. why is this happening?
Note:
It is not smart to try to limit the input string by asking the user, the user can still write string with length greater/ less
Reading string from console does by default not allow spaces
First option:
Read a string of a static size:
char original[5];
scanf("%5s", original); // String containing 5 chars
Second option:
Read a string of variable size:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
// Length of String
unsigned expected;
printf("Enter the length of the string: ");
scanf("%u", &expected);
char *temp; // Warning: Uninitialized
// Get string
printf("Enter the string: ");
scanf("%s", temp);
unsigned actual = strlen(temp);
unsigned length = actual > expected ? expected : actual;
char *string = (char *) malloc(length * sizeof(char));
char *reverse = (char *) malloc(length * sizeof(char));
// Trim string to proper size
for (int i = 0; i < length; i++) {
string[i] = temp[i];
}
// Reverse string
for (int i = 0, j = length - 1; i <= j; i++) {
reverse[i] = string[j - i];
}
// Print Strings
printf("%s", string);
printf("\n%s", reverse);
There's a bunch of threads about C++, but I'm stuck with regular C here and can't find an answer anywhere.
#include <stdio.h>
#include <conio.h>
#include <string.h>
main() {
char word[26], letter, reverse[26], length;
printf("Enter word: ");
scanf("%s", &word);
length=strlen(word);
for (int i=0; i<=length; i++) {
letter = word[length-i];
strcpy(reverse, letter);
printf("%c\n", reverse);
}
getch();
}
I'm getting errors as the title states.
13 25 ~ [Error] invalid conversion from 'char' to 'const char*'
[-fpermissive]
51 18 C:\Program Files (x86)\Dev-Cpp\MinGW64\x86_64-w64-mingw32\include\string.h [Note]
initializing argument 2 of 'char* strcpy(char*, const char*)'
What the code should do is reverse the written word and type it out line by line, by each last letter.
Etc. - Type in "food" and the program should output:
d
od
ood
food
I know I messed up somewhere in the 'letter', but I have no clue how to fix it.
Also I'm trying to avoid using std::, personal prefrence.
Try this:
int main( void ) {
char word[26], reverse[26];
int length, i;
printf("Enter word: ");
scanf("%s", &word);
length=strlen(word);
for (i=0; i<length; i++) {
reverse[i] = word[length - i - 1];
}
/* Put \0 to terminate the string */
reverse[length]='\0';
printf("%s\n", reverse);
}
Note that in the for loop you have to use only < and not <= because you'll get out of bounds of the array (negative index) and you have to put the \0 terminator to terminate your reverse string. You don't need letter and btw strcpy works not with single chars, since a single char is not a string (because of the missing string terminator (\0)).
Edit:
int main( void ) {
char word[26], reverse[26];
int length, i;
printf("Enter word: ");
scanf("%s", &word);
length=strlen(word);
for (i=0; i<length; i++) {
reverse[i] = word[length - i - 1];
/* Put \0 to terminate the string */
reverse[i + 1]='\0';
printf("%s\n", reverse);
}
}
Problems:
You pass the address of an array to scanf, rather than passing the array.
You don't copy the null termination correctly.
strcat must have null terminated strings as parameters, it cannot work with single characters. You don't need to use it here anyway.
Fixed program:
#include <stdio.h>
#include <string.h>
int main (void)
{
char word[26];
char reverse[26];
size_t length;
size_t i;
printf("Enter word: ");
scanf("%s", word);
length=strlen(word);
for (i=0; i<length; i++)
{
reverse[i] = word[length-i-1];
}
reverse[i] = '\0';
printf("Reverse: %s\n", reverse);
return 0;
}
Output:
Enter word: stackoverflow
Reverse: wolfrevokcats
There are a bunch of errors in the code. The one that you are asking about is due to the fact that you are passing a char (i.e. the variable letter) rather than the address (i.e. &letter)
This "fix" would cause the compiler error to disappear, however it would cause another one to appear. This is because we'd now be passing a pointer to a char rather than a pointer to a terminated string.
for (i=0 ; i<26 ; i++)
reverse[i] = word[25-i];
Here i have to pass in strcat(char * s1, const char * s2);
Here reverse is the cha* and &letter is const char*.
Check out this one.
this is the code what you want as output.
int main()
{
char word[26], letter, length;
int n, c, d;
char reverse[26];
char temp[26];
printf("Enter word: ");
scanf("%s", word);
length=strlen(word);
for (int i=0; i<=length; i++)
{
letter = word[length-i];
strcat(reverse, &letter);
n = strlen(reverse);
for (c = n - 1, d = 0; c >= 0; c--, d++)
temp[d] = reverse[c];
temp[d] = '\0';
printf("%s\n", temp);
}
return 0;
}
Output :-
I am working on a program that, when specified by a number entered by the user, will only print out that number of characters. For example, if the user enters the number 10, then if 14 characters are entered (including newlines, blanks and tabs) only 10 characters will be printed. My code seems to work for the first three or so characters, then it prints out garbage. I'm not sure what is wrong.
#include <stdio.h>
#include <stdlib.h>
void findchars(char *abc, int number);
int main(void)
{
char *array; // the actual array
int num; // number of characters to read, becomes array value
printf("Number of characters:");
scanf_s("%d", &num);
array = (char *)malloc(num * sizeof(char));
findchars(array, num);
printf("The first %d characters: ", num);
puts(array);
free(array);
return 0;
}
void findchars(char *abc, int number)
{
int i;
printf("Type characters and I will stop at %d: ", number);
for (i = 0; i < number; i++)
{
abc[i] = getchar();
}
}
You are passing non-zero-terminated array to puts. If you want your program to work just create your array 1 item bigger and add '\0' in the end.
Edit: like this
array = (char *)malloc((num+1) * sizeof(char));
and then right before puts:
array[num] = '\0';
This program is supposed to convert the array of chars (string) into an array of ints by subtracting 97 from their ascii value (the input should be lower case cause a has an ascii value of 97). So if i enter the string abcd i should get 0123 but instead I somehow get this: 012134513789. I can't figure out where the problem is.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void userEnter(int*pattern, int n);
int main(void)
{
int n, i;
printf("What is the length of the array: ");
scanf("%d",&n);
int pattern[n];
printf("Enter the char array: ");
userEnter(pattern, n);
printf("The int array is: ");
for(i=0;i<n;i++)
{
printf("%d",pattern[i]);
}
printf("\n");
}
void userEnter(int*pattern, int n)
{
char input[n];
scanf("%s", input);
int i;
for(i = 0; i < n-1; i++)
{
pattern[i] = input[i]-97;
}
}
char input[n];
scanf("%s", &input);
should be
char input[n+1];
scanf("%s", input);
input is equivalent to &input[0]
You should also exit the for loop in userEnter when you encounter the nul character that ends the user-entered string. e.g. with something like
char* p = input;
while (*p != '\0') {
*pattern = (*p) - 'a';
p++;
pattern++;
}
As KingsIndian points out, you also need to increase the size of your input buffer. At present, you overflow that buffer and overwrite the loop counter i;
The length parameter n includes one character for null as well. So, if you input length for n 4 then you can only input 3 characters, for example abc because the 4th is for the null.
So you should change the declaration accordingly:
Change:
char input[n];
to:
char input[n+1];
Note that variable length arrays are allowed only since C99.