printing string from the array - arrays

as you can see this while I run this it works perfectly till "The array is " but cant show the string that I enter
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main()
{
int size;
char arr[size];
printf("input size of array ");
scanf("%d", &size);
printf("\ninput elements of array ");
for (int i = 0; i < size; i++)
{
scanf("%s", &arr[i]);
}
printf("\nThe array is ");
for (int i = 0; i < size; i++)
{
printf("%s\n", arr[i]);
}
return 0;
}

There are multiple things wrong with this code.
int size;
char arr[size];
You are declaring a char array arr with size elements, but size is not yet initialized yet and may be any value. Also note that "deciding the size of an array at runtime" is only valid in modern C (C99 onwards).
You should first read size and only after the scanf declare arr.
for (int i = 0; i < size; i++){
scanf("%s", &arr[i]);
}
You read a string (%s) with scanf and try to store it in a char (&arr[i] points to the ith char in arr). Every C string is atleast 1 character long (the terminating \0 character), you are trying to store multiple characters in a single char.
Instead use
scanf("%s", arr);
Note that scanf is not safe. Even if you enter more than size characters, it will still try to store them in arr. That leads to undefined behaviour, because arr is too small. Instead you can use fgets, that lets you set the number of characters to read.
for (int i = 0; i < size; i++){
printf("%s\n", arr[i]);
}
Here you are trying to print a String (%s), but you are passing a char (arr[i] is the ith char in arr).
Instead use
printf("%s\n", arr);

Related

I want to print all the input of this string in for loop but it only prints the last input

Help me correcting this code.... I don't know what extra details should I give so it lets me post.
#include<stdio.h>
int main(){
char s[34];
int a = 4;
for (int i = 0; i < a; i++)
{
printf("Student %d enter your name: ", i+1);
scanf("%s", s);
}
for (int i = 0; i < a; i++)
{
printf("Student %d name is %s\n", i+1, s);
}
return 0;
}
You are overwriting the same block of memory: scanf("%s", s);.
You should have s as an array of pointers to char i.e. char *s[4] in which case you should allocate space for each name using malloc and then use free to give back all allocated memory to the OS.
Or, you could declare s to be char s[4][34] and use s[i] in your scanf and printf statements.

Dynamically allocate an array of strings

How can I fix this code in a way that it prints the words in the array? Moreover this is the right way to dynamically allocate memory for n words of max size 40?
int main() {
int n;
char *arr;
int i;
printf("Give me a number:");
scanf("%d", &n);
arr = malloc(n * 40);
for (i = 0; i < n; i++)
{
printf("Give me a word: ");
scanf("%s", &arr[i]);
}
for (i = 0; i < n; i++)
{
printf("%s", arr[i]); //< --problem here
}
return 0;
}
Your allocation is not the best, and printf argument arr[i] expects a char* but you pass it an int (a char if you'd like).
Here is how you should do it, with comments:
Live demo
#include <stdio.h>
#include <stdlib.h> //for malloc
int main(){
int n;
int i;
printf("Give me a number:");
scanf("%d", &n);
//declare a variable of pointer to pointer to char
//allocate memory for the array of pointers to char,
//each one capable of pointing to a char array
char **arr = malloc(n * sizeof *arr);
if(arr == NULL){ //check for allocation errors
perror("malloc");
return EXIT_FAILURE;
}
//allocate memory for each individual char array
for(i = 0; i < n; i++){
arr[i] = malloc(40); //char size is always 1 byte
if(arr == NULL){ //check for allocation errors
perror("malloc");
return EXIT_FAILURE;
}
}
for (i = 0; i < n; i++){
printf("Give me a word: ");
//limit the size of read input to 39 charaters to avoid overflow,
//a nul character will be added by scanf
scanf("%39s", arr[i]);
}
for (i = 0; i < n; i++){
printf("%s\n", arr[i]);
}
for(int i = 0; i < n; i++){ //free the memory for each char array
free(arr[i]);
}
free(arr); //free array of pointers
return 0;
}
You can also do this with less code using a pointer to array of 40 chars, this will simplify the memory allocation and deallocation:
Sample with comments:
Live demo
#include <stdio.h>
#include <stdlib.h> //for malloc
int main(){
int n;
int i;
printf("Give me a number:");
scanf("%d", &n);
//declare a pointer to array of chars and
//allocate memory for all the char arrays
char (*arr)[40] = malloc(n * sizeof *arr);
if(arr == NULL){ //check for allocation errors
perror("malloc");
return EXIT_FAILURE;
}
for (i = 0; i < n; i++){
printf("Give me a word: ");
scanf("%39s", arr[i]);
}
for (i = 0; i < n; i++){
printf("%s\n", arr[i]);
}
free(arr); //free allocated memory
return 0;
}
This:
for(i=0;i<n;i++){
printf("Give me a word: ");
scanf("%s",&arr[i]);
}
is probably not what you want.
You probably want this instead:
for(i=0; i<n; i++){
printf("Give me a word: ");
scanf("%s", arr + i*40);
}
then later:
for(i=0; i<n; i++){
printf("%s", arr + i*40);
}
Remember that a string in C is just an array of characters.
Thus when defining char *arr, you are creating a single string. Had you done char **arr it would have been an array of strings, which is what you want.
However, I find that allocating/freeing arrays of arrays on the heap to be rather inconvenient, and prefer 'flattening' them into a single array.
This is exactly what you were doing with arr = malloc(n*40), but then later you treated this array of characters as an array of strings when you did this:
for(i=0; i<n; i++){
printf("Give me a word: ");
scanf("%s", &arr[i]);
}
Note that this is actually perfectly legal (scanf wanted a char* and you gave it one), but it's a logical error since you are giving it the n-th character when you wanted to give it the n-th array.
And oh yes, don't forget to free(arr) later.

Program Termination error while printing the array

#include <stdio.h>
int main() {
int n, i;
char arr[20];
clrscr();
printf("Enter size of array(<=20)");
scanf("%d", &n);
printf("Enter array");
for (i = 0; i < n; i++) {
scanf("%s", &arr[i]);
}
for (i = 0; i < n; i++) {
printf("%s", arr[i]);
}
getch();
return 0;
}
The program does not prints the array
and instead shows
Program termination message
The image shows the program termiantion message
The problem is with the line
printf("%s", arr[i]);.
If you change this line to
printf("%c", arr[i]);
then it will work because %s is used with character arrays that contain strings
I am just giving the solution for your program termination. Still we can do some modification in your code.
Thanks

Reading a two dimensional string using gets

int main(int argc, char const *argv[])
{
char str[100][100];
int n, i;
scanf("%d", &n);
for (i = 0; i < n; i++)
gets(str[i]);
for (i = 0; i < n; i++)
printf("%s\n",str[i]);
}
Why i'm unable to read the string properly?
raja#raja-Inspiron-N5110:~/myctry$ ./a.out
2
abc def
abc def
change
scanf("%d",&n);
to
scanf("%d\n",&n);
if you press enter to input your number. this form gets rid of the '\n' in str[1] when scanf().
You're using 1-based indexing. C uses 0-based indexing.
Change the for loop to for(i=0;i<n;i++)
Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.
MAN
There are several issues:
You need to start your for loop at index 0.
You should print your string out
int main(int argc, char const *argv[])
{
char str[100][100];
int n,i;
scanf("%d",&n);
for(i=0;i<n;i++) // start at i = 0
gets(str[i]); // store string to str[0]
printf("%s\n", str[0]); // print the results
}
Start loop from index 0 - you have started from 1
for (i = 0; i <= n; i++)
Moreover, you should print the string as well.
#include<string.h>
#include<stdio.h>
int main()
{
int n,i;
char str[100][100];
scanf("%d", &n);
for(i=0;i<n;i++)
{gets(str[i]);}
for(i=0;i<n;i++)
{printf("%s\n",str[i]); }
return 0;
}
As 7-isnotbad said,gets() is not safe,fgets() is a better choice.
Both gets() and fgets() read a line end by '\n' from buffer.
maybe you can try this code:
#include "stdio.h"
#define MAX_LINE 1024
#define MAX_ROW 100
int main()
{
char str[MAX_ROW][MAX_LINE];
int i,n;
printf("input the row of lines :\n");
scanf("%d\n",&n);
if(n < 1)
{printf("input error!\n");return -1;}
for(i = 0; i < n; ++i)
fgets(str[i],MAX_LINE - 1,stdin);
for(i = 0; i < n; ++i)
fputs(str[i],stdout);
return 0;
}

C : Array of strings - Can input only n-1 strings for an input size of n

I have to sort strings in a lexicographical order using the Bubble Sort technique without using any library functions. I have written the following code which is working fine in sorting the strings.
But the problem is that if I give n as the input (say n = 4), I can enter only n-1 strings (only 3 strings).
The problem can be solved by running the for loops from 0 to n, but that isn't a logical solution.
What am I doing wrong here?
#include <stdio.h>
#include <string.h>
#include <malloc.h>
void swap(int indx[], int j)
{
int temp;
temp = indx[j];
indx[j] = indx[j+1];
indx[j+1] = temp;
}
void sort(char **str, int indx[], int n)
{
int i, j, k;
for(i=0; i<n; i++)
{
for(j=0; j<n-i-1; j++)
{
k = 0;
while(str[j][k] != '\0')
{
if((str[indx[j]][k]) > (str[indx[j+1]][k]))
{
swap(indx, j);
break;
}
else if((str[indx[j]][k]) < (str[indx[j+1]][k]))
break;
else
k++;
}
}
}
}
void display(char **str, int indx[], int n)
{
int i;
printf("Sorted strings : ");
for(i=0; i<n; i++)
printf("%s\n", str[indx[i]]);
}
int main(void)
{
char **str;
int n, i, j, *indx;
printf("Enter no. of strings : ");
scanf("%d", &n);
str = (char **) malloc (n * (sizeof(char *)));
indx = (int *) malloc (n * sizeof(int));
for(i=0; i<n; i++)
str[i] = (char *)malloc(10 * sizeof(char));
printf("Enter the strings : ");
for(i=0; i<n; i++)
{
gets(str[i]);
indx[i] = i;
}
sort(str, indx, n);
display(str, indx, n);
}
The problem is your use of scanf(). When you do scanf("%d", &n), the scanf() function reads input until it finds an integer, and puts the value into n. However, when you entered that integer, you didn't just type '4', you typed '4' and pressed Enter. And the newline is still in the input buffer. The gets() function, on the other hand, reads input up to and including the first newline, and the newline character is discarded. So when you're reading the input strings, the gets call to gets() reads the newline, and returns immediately. And then, the first string that you enter is read by the second call to gets()...
Incidentally, The gets() function should never, ever, under any circumstances, ever be used for real programs, because it doesn't allow you to limit input. Better would be to use fgets(). fgets(str[i], BUFFERSIZE-1, stdin).
int main(void)
{
char **str;
int n=4, i, j, *indx;
printf("Enter no. of strings : ");
//scanf("%d", &n);
str = (char **) malloc (n * (sizeof(char *)));
indx = (int *) malloc (n * sizeof(int));
for(i=0; i<n; i++)
str[i] = (char *)malloc(10 * sizeof(char));
printf("Enter the strings : ");
for(i=0; i<n; i++)
{
gets(str[i]);
indx[i] = i;
}
sort(str, indx, n);
display(str, indx, n);
}
//if i comment out scanf and give int the value it works fine //
so the problem is use of fgets just after scanf as scanf leave a newline character in the buffer// so consume it before using fgets
Try this at the line where you have to input the string. Instead of:
gets(str[i]);
type:
scanf("%s",str[i]);

Resources