Simple print string array - arrays

Please let me know what is the mistake with this simple code.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n;
char a[100];
clrscr();
printf("\n Enter the size of the array");
scanf("%d",&n);
printf("\n Enter the array");
for(i=0;i<n;i++)
scanf("%s",a[i]);
printf("\n Your array is \n");
for(i=0;i<n;i++)
printf("%s",a[i]);
getch();
}
My input is
Enter the size of the array
2
Enter the array
Apple
Banana
Your array
(null) (null)
Can someone explain why this is? Where am i going wrong?
Even if my input is single characters like a or s, this is the same output.
Thanks in advance

You are not declaring array of string itself.
By char a[100]; means you are declaring an array which can hold 100 characters (one of them should be NULL for proper string termination). In other words you are declaring only one string.
Whereas you want an array of strings, thus you need to do something like char a[10][100];. This will declare an array of 10 strings, where every string can hold 100 characters.
After updating your code with char a[10][100];, I am getting following o/p (which you are looking for):
Enter the size of the array3
Enter the arrayhi
hello
com
Your array is
hi
hello
com

There are a few problems here.
When calling scanf, you need to use the & operator and pass the address of the string, e.g.
scanf("%s", &a[i]);
Next is that a is an array of char, not an array of strings. You might try
char a[20][100];
giving you 100 strings of 20 chars.

I edit your code check:
#include<stdio.h>
void main()
{
int i,n;
char a[100];
printf("\n Enter the size of the array: \n");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("\n Enter the array value: \n");
int input;
scanf("%d",&input);
a[i] = input;
}
printf("\n Your array is : ");
for(i=0; i<n; i++)
printf("%d , ",a[i]);
printf("\n");
}
your mistake was in the time to read the value and assign it to the array

Related

program returning garbage values even after declaring variables in c

how do i correct this
i didn't use structure intentionally
this is a program to input student's name, subject and marks.
in the last block, the array (subject+f) 's 1st subscript is returning garbage values while the rest subscript are returning desired result.
i have also posted the image of output as link.
#include<stdio.h>
#include<string.h>
int main()
{
int size,i,k,sub,a=0,reference;
int temp,sorted;
char temp_s[10];
char temp_sb[10];
printf("enter the size of class\n");
scanf("%d",&size);
printf("how many subjects are there?\n");
scanf("%d",&sub);
reference = sub;
char name[size][20];
char subject[size*sub][20];
int marks[sub*size];
int total,subtotal,retotal;
for(k=0;k<sub;k++)
{
printf("so what's the no. %d subject\n",k+1);
scanf(" %s",(subject[k]));
}
for(i=0;i<size;i++)
{
int j,k=0;
printf("Enter a name of student %d\n",i+1);
scanf(" %s",(name+i));
for(j=a;j<reference;j++)
{
printf("enter marks of %s\n",(subject[k]));
scanf("%d",(marks+j));
k++;
}
a=j;
reference=sub+j;
}
reference=sub;
a=0;
printf("\n list of students and marks:\n");
for(i=0;i<size;i++)
{
int j,f=0;
printf("%s\n",(name+i));
for(j=a;j<reference;j++)
{
printf("%s %d\n",(subject[f]),(marks[j]));
f++;
}
a=j;
reference=sub+j;
}
}
Besides the problem with length of names and subjects, this here is a major problem:
(subject+k)
You are probably misunderstanding the subject[k] and *(subject + k) equivalent.
The variable subject is an array of arrays. That means subject[i] is an array (of char and can be used as a zero-terminated string).
The expression (subject + k) is a pointer to the array in subject[k]. It's equal to &subject[k] which have the type char (*)[10]. It's can not be used as a zero-terminated string without dereferencing. So either use *(subject + k) or the simple, less-to-write and easier-to-read subject[k].
I think you also need to change
int marks[sub];
to
int marks[size * sub];
one mark for each subject for each student, correct?

how to display entered letter in c?

I am new to c programming. I have created a program for entered letters and finally displayed the entered letters.. but it displayed only final letters always.. please help .. i know its simple question but am beginner so please help guys..
#include<stdio.h>
int main()
{
char z;
int a;
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%s",&z);
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%s\n",&z);
}
return 0;
}
Problems:
You should use %c (for character) instead of %s (for string).
Use a character array for storing multiple characters. Read about arrays here.
Remove & from printf() in the second for loop.
Try this:
int main()
{
char z[10]; //can hold 10 characters like z[0],z[1],z[2],..
int a;
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",&z[i]);
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%c\n",z[i]);
}
return 0;
}
Please look into this for more details on scanf. You have given scanf("%s",&z); %s is for reading strings(array of chars except newline char and ended with null char). So if you put this inside loop you wont get desired result. And if you want read only a char at a time use %c here c for Character.
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",z+i);
}
char z is a place holder for one character only. And you are over writing what you set z to in the for loop. To take in more characters, use a char array as others have mentioned.
Or print the characters in the same you loop you are scanning them:
#include<stdio.h>
int main()
{
char z;
int a;
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%s",&z);
printf("letter scanned:%c\n", z);
}
return 0;
}
Letters are scanned using %c. And to scan multiple letters you can use char array: char z[10];
What you are trying to do can be done this way:
char z[10]; // Take some max size array
...
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",&z[i]); // Scan the letters on each array position.
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%c\n",z[i]); //'printf' doesn't require address of arg as argument hence no `&` required
}
%s argument is used to scan a string of chars.
Note the difference between string of chars and array of chars. The string of chars in C needs to be terminated with ASCII Character 0 represented as \0 in char format, while the array of char is just a collection of letters which need not be terminated with \0.
The difference becomes more important when you try to perform some operation on strings such as printf, strcpy, strlen, etc.. These functions work on null character termination property of string.
For Example: strlen counts the characters in the string till it finds \0, to find out the length of string. Similarly, printf prints the string character by character until it finds the \0 character.
UPDATE:
Forgot to mention that scanf is not a good option to input char format. Use fgetc instead, with stdin as input FILE stream.
#include <stdio.h>
int main()
{
char *z;
int a;
printf("enter the no.");
scanf("%d",&a);
z = (char *) malloc(a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",z+i);
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%c\n",z);
}
return 0;
}
first error in your code is you have used "%s" instead of "%c".Second is it is impossible to store multiple values in one variable so instead of using variable use arrays.third is that you have told the user to enter the number of character that he/she wants to entered which you don't know.They can enter 1 also and 100000 also so the number of members in array is not defined.Better is to use specific number of characters in array.
finally i got the answer thank you for the help stackoverflow guys simply rocks ...
#include<stdio.h>
#include<malloc.h>
int main()
{
int a;
char *z=(char *)malloc(sizeof(a));
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%s",&z[i]);
}
printf("the entered letters are:\n");
for(i=0;i<a;i++)
{
printf("%c\n",z[i]);
}
return 0;
}

Returning Array of pointers to string

I am confused and clueless as how can I return an Array of pointers to a String(Basically 2D array) from a function.
What I did(or about to do )in this code is , first insert words/names and then stored it in the array and also input the number 'n'. Than I passed this array and number into the function and their extracted the last 'n' names/words from the array and print that in the main.
Here is my code :
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<string.h>
char** fun(char *s[5],int no)
{
char *f[5];
int i,j=0;
for(i=5-no;i<5;i++)
{
f[j]=(char*)malloc(strlen(s[i])+1);
strcpy(f[j],s[i]);
j++;
}
/*for(j=0;j<no;j++) //I did it just to check whether 'f' stores the last 'n' names.
printf("\n%d. %s",j+1,f[j]);*/
return f;
}
void main()
{
char *name[5],*str,*list[5];
int i,n;
clrscr();
printf("Enther the Names of the list : " );
for(i=0;i<5;i++)
{
printf("%d. ",i+1);
str=(char*)malloc(30);
gets(str);
name[i]=(char*)malloc(strlen(str)+1);
strcpy(name[i],str);
free(str);
}
clrscr();
printf("\nEntered Names are : ");
for(i=0;i<5;i++)
printf("\n%d. %s",i+1,name[i]);
printf("\n Enter the no. :");
scanf("%d",&n);
*list=*fun(name,n); // I am little confused as to how should I wrote this ?
for(i=0;i<n;i++)
printf("\n%d. %s",i+1,list[i]);
getch();
}
Suppose I gave the Input as :
1.the
2.there
3.this
4.that
5.therefore
Enter the No.: 3
Output:
1.this
2.<Some special characters>
3.<Some special characters>
I would more interested in the method which uses the pointer approach .
PS: I am Using Turbo C/C++ IDE as I am in a Learning phase of C .
As H2CO3 pointed out, define the fun as fun(list, name, n); where list is your output list of string. Pass the list from main(), fill it up inside fun().
You can not define array of pointers of char locally(which will allocate it on stack. scope of it is inside that function only) and use it globally.
inside fun() you can use
char f = (char)malloc(sizeof(char*[5])); (allocate memory on heap which you can use it globally)
instead of
char *f[5];
code should be:
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include <malloc.h>
char** fun(char *s[5],int no)
{
char **f = (char**)malloc(sizeof(char*[5]));
int i,j=0;
for(i=5-no;i<5;i++)
{
f[j]=(char*)malloc(strlen(s[i])+1);
strcpy(f[j],s[i]);
j++;
}
/*for(j=0;j<no;j++) //I did it just to check whether 'f' stores the last 'n' names.
printf("\n%d. %s",j+1,f[j]);*/
return f;
}
void main()
{
char *name[5],*str,**list;
int i,n;
printf("Enther the Names of the list : " );
for(i=0;i<5;i++)
{
printf("%d. ",i+1);
str=(char*)malloc(30);
gets(str);
name[i]=(char*)malloc(strlen(str)+1);
strcpy(name[i],str);
free(str);
}
printf("\nEntered Names are : ");
for(i=0;i<5;i++)
printf("\n%d. %s",i+1,name[i]);
printf("\n Enter the no. :");
scanf("%d",&n);
list=fun(name,n); // I am little confused as to how should I wrote this ?
for(i=0;i<n;i++)
printf("\n%d. %s",i+1,list[i]);
getch();
}

Two Dimensional Array of Characters in C

Help me to get out of this problem. I'm using GCC on ubuntu12.04. While I write this program to get 5 strings from keyboard n then print these strings on screen. Program is compiled but during execution it takes strings from keyboard but print only last string. The program which I have written is below:
void main()
{
char names[10];
int i,j;
for(i=0;i<5;i++)
{
printf(" Enter a name which you want to register\n");
scanf("%s",names);
}
for(i=0;i<5;i++)
printf(" the names you enter are %s\n", names);
}
1) you can use 2D char array in this way
char names[5][100];
each line in the 2D array is an array of char with size = 100
for(i=0;i<5;i++)
{
printf(" Enter a name which you want to register\n");
scanf("%99s",names[i]);
}
2) You can use array of pointers in this way
char *names[5];
each element in the array is a pointer to a string (char array). you have to assign each pointer in the array to a memory space before you call scanf()
for(i=0;i<5;i++)
{
names[i]=malloc(100);
printf(" Enter a name which you want to register\n");
scanf("%99s",names[i]);
}
3) if you compile with gcc version >2.7 then your scanf() can allocate memory by using "%ms" instead of "%s"
char *names[5];
for(i=0;i<5;i++)
{
printf(" Enter a name which you want to register\n");
scanf("%ms",&names[i]);
}
There is a simple example about reading and keeping string in the char array.
#include <stdio.h>
const int MACRO = 6;
int main() {
printf("Hello Admin Please Enter the Items:\n");
char items[MACRO][20];
for (int i = 0; i < MACRO; ++i) {
scanf("%19s", items[i]);
}
for (int i = 0; i < MACRO; ++i) {
printf("%s ", items[i]);
}
return 0;
}
In your program the mistake is that you have not putted '&'address of operator int the first for loop . names in your case is an array if you store %s string in names and not &names[0] or &names[1] or so on then as array itself acts as a pointer therefore the array "names" is pointing to the address of its first elements i.e. names[0] . so if you are writing scanf("%s",names); that is similar to scanf("%s",&names[0]); so as you are storing the names in one element only and that too for 5 iterations for only the last string you have entered will be stored and previous strings will be gone . so onlye last string is printed in your program .
in your code, you only declare char data type to be one dimensional and thus it will always overwrite the previous input,that's why the result is the last input printed 5 times.
char names[10];
the above declaration means that you declare a char type variable only with 10 character size without an extra array,it means you only declare a single variable for 5 input.
to make a two dimensional char, you will need to declare it like this :
char names[5][10];
in the code above, it means that you declare a char type variable with 10 character size in an array of 5.
Here is the code I wrote using pointer.
#include <stdio.h>
void main()
{
char *string[100];
int ln;
printf("Enter numbar of lines: ");
scanf("%d",&ln);
printf("\n");
for(int x=0;x<ln;x++)
{
printf("Enter line no - %d ",(x+1));
scanf("%ms",&string[x]); // I am using gcc to compile file, that's why using %ms to allocate memory.
}
printf("\n\n");
for(int x=0;x<ln;x++)
{
printf("Line No %d - %s \n",(x+1),string[x]);
}
}
Another code using two dimensional Array
#include <stdio.h>
void main()
{
int ln;
printf("Enter numbar of lines: ");
scanf("%d",&ln);
printf("\n");
char string[ln][10];
for(int x=0;x<ln;x++){
printf("Enter line no - %d ",(x+1));
scanf("%s",&string[x][0]);
}
for(int x=0;x<ln;x++)
{
printf("Line No %d - %s \n",(x+1),string[x]);
}
}

Strings taken from user in C are being scrambled

I have written the following C code to get in a list of strings from the user. But the stored strings are giving out weird values.
#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING_LENGTH 50
void readInStrings(char* arr[],int n)
{
int i=0;
char line[MAX_STRING_LENGTH];
for(i=0;i<n;i++){
arr[i]=malloc(MAX_STRING_LENGTH);
printf("Enter another string : ");
scanf("%s",&arr[i]);
//fgets(&arr[i],MAX_STRING_LENGTH,stdin);
}
printf("Strings read in correctly.... \n");
printf("Displaying out all the strings: \n");
for(i=0;i<n;i++){
printf("%s\n",&arr[i]);
}
}
void testStringInputs()
{
printf("Enter the number of entries : ");
int n;
scanf("%d",&n);
char* strings[n];
readInStrings(strings,n);
}
Input Sample:
Enter the number of entries : 3
Enter another string : Alladin
Enter another string : Barack Obama
Enter another string : Strings read in correctly....
Displaying out all the strings:
AllaBaraObama
BaraObama
Obama
Problems:
1) Why is one string not taken in as input at all?
2) Why are the displayed strings scrambled like that?
The problem is the same if I use gets() or fgets() in place of scanf().
arr[i] is already a pointer, you don't need the &
Removing the & (as the first answerer noted) in scanf("%s",&arr[i]); and in printf("%s\n",&arr[i]); did the trick for me. Also, note if you compiled with warnings at their highest, your compiler would have told you right away that the & was misplaced.
Its better to use an array of arrays(two dimensional) instead of array of pointers.
I had a tough time correcting your code. So I changed the code to this
#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING_LENGTH 50
void readInStrings(char (*arr)[MAX_STRING_LENGTH],int n)
{
int i;
for(i = 0 ; i< n+1; ++i)
fgets(*(arr+i),MAX_STRING_LENGTH,stdin);
printf("Strings read in correctly.... \n");
printf("Displaying out all the strings: \n");
for(i=0;i< n+1;i++){
printf("%s",arr[i]);
}
}
int main()
{
printf("Enter the number of entries : ");
int n;
scanf("%d",&n);
char strings[n][MAX_STRING_LENGTH];
readInStrings(strings,n);
return 0;
}

Resources