Two Dimensional Array of Characters in C - 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]);
}
}

Related

How to Print an array with names

I wrote this code to input names to array (eg:Jon,raj...) and the input part is ok but how to print exact name that i input to this array a[5] why this code is not working
#include <stdlib.h>
#include<stdio.h>
int main(){
int i;
char a[5];
for(i=0;i<5;i++){
printf("Enter ");
scanf("%s",&a[i]);
}
for(i=0;i<5;i++){
printf("%s \n",a[i]);
}
}
Your array a is an array of chars. This means that in each position you will have only one char.
You can do this any one of these two ways:
Pre-allocated (array of arrays of chars)
#include <stdio.h>
int main(){
const int NAME_MAXIMUM_SIZE = 50;
const int NUMBER_OF_NAMES = 5;
int index;
char names [NUMBER_OF_NAMES][NAME_MAXIMUM_SIZE];
for(index=0; index<NUMBER_OF_NAMES; index++){
printf("Enter ");
scanf("%49s",names[index]);
}
for(index=0; index<NUMBER_OF_NAMES; index++){
printf("%s \n",names[index]);
}
}
Malloc + free (array of pointers)
#include <stdio.h>
#include <stdlib.h>
int main(){
const int NAME_MAXIMUM_SIZE = 50;
const int NUMBER_OF_NAMES = 5;
int index;
char *names [NUMBER_OF_NAMES];
for(index=0; index<NUMBER_OF_NAMES; index++){
names[index] = (char*)malloc(NAME_MAXIMUM_SIZE);
printf("Enter ");
scanf("%49s",names[index]);
}
for(index=0; index<NUMBER_OF_NAMES; index++){
printf("%s \n",names[index]);
free(names[index]);
}
}
You can make use of 2 dimensional array. Here your variable a which is a character array stores only one character at each index.
#include <stdlib.h>
#include<stdio.h>
int main(){
int i;
char a[5];
for(i=0;i<5;i++){
printf("Enter ");
scanf("%s",&a[i]);
}
for(i=0;i<5;i++){
printf("%s \n",a[i]);
}
}
"...wrote this code to input names to array..."
char a[5] does not create 5 C strings. It is simply an array of 5 char. It provides room for only 1, 4 character C string (leaving room for the \0 terminator). If you need an array of names, of typical size the code will need an array of arrays each with space sufficient for typical names. For example:
char a[5][80] = {{0}}; //provides an array capable of containing 5 names
Also, in the read statement: scanf("%s",&a[i]);, the format code %s is expecting to process an array of char. But is provided with &a[i] which is only a single character. If you are going to use scanf, then call it like this: scanf("%s",a); Same issue with the print statement.
Make the following edits to address these basic issues:
int main(void)
{
int i = 0;
char a[5][80] = {{0}};//space for 5 names, each with up to 79 characters
//arrays are initialized to zeros
for(i=0;i<sizeof(a)/sizeof(a[0]);i++)//sizeof(a)/sizeof(a[0]) is flexible way to
//loop only through number of names.
//If array size changes, expression will still work
{
printf("Enter name %d:\n ", i+1);
scanf("%79s",a[i]);//limit input to prevent overflow
// ^^
}
for(i=0;i<sizeof(a[0])/sizeof(a[0][0]);i++)
{
printf("%s \n",a[i]);
}
return 0;
}

Why the output file isn't the same as the input of the variable?

I create it a program that asks for raw and columns after that asks you to put numbers to the dimensional array. This arrays inputs to a file. When i open the file i can't see the array.
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
int main () {
FILE *fp;
int n,m;
int i,j;
float b;
char filename[100];
int getfloat(float *);
printf("Number of rows\n");
scanf("%d",&n);
printf("Number of colums\n");
scanf("%d",&m);
float s[n][m];
for (i=1;i<=n;i++)
{
for (j=1;j<=m;++j)
{
printf("Insert number %d",i);
printf(",%d\n", j);
scanf("%f",&b);
s[i][j]=b;
}
}
printf("Enter file name \n");
scanf("%s", filename);
// ****print file****
fp=fopen(filename,"w+");
if(fp!=NULL)
{
fputs(s,fp);
fprintf("%c",s);
}
fclose(fp);
return 0;
the only thing i see is this
If you want a list of numbers, probably in some kind of grid in the file, then at the minimum you want a loop such as the following:
for (int i=0; i<n; ++i)
{
for (int j=0; j<m; ++j)
{
fprintf(fp, "%f ", s[i][j]);
}
fprintf(fp, "\n");
}
See fprintf for documentation on the format specifiers; you'll probably want to tweak that to get better-looking values.
Also, again, note that arrays start from 0. Your initial read loop skips the very first element, and writes past the end of the actual array.
fprintf("%c", s); and fputs does not print out the contents of the array, it prints out the location stored in the array's pointer and tries to interpret it as a char. What you would need to print out the proper values is to loop through each value and use fprintf with each float value, using s[i][j] similar to how you initialized it.
The way you initialized the array is also off, as arrays begin at 0, not 1. Currently your for loop does not ever access s[0][0] or s[1][0] and so on. Your for loops should have i initialized to 0, and have the condition be i < n instead of i<=n.

Why my program is showing wrong output in C

I want a program in which the user will give three names and they will be printed in result.
I declared a string "name" and also declared that 'name' variable as an array(or I wanted to)
But when I run the program,The output I get is weird
It only accepted one name,I thought It had something to do with array declaration,so I changed 'char name[3][20];' to 'char name[20][3];' but nothing changed..
Please help me..
Program:
#include<stdio.h>
#include<conio.h>
struct variable
{
char name[3][20];
}v;
void main()
{
int i=0,j=0;
clrscr();
printf("Enter Three names \n");
for(i=0;i<3;i++)
{
scanf("%c",&v.name[i]);
}
for(j=0;j<3;j++)
{
printf("%c\t",v.name[i]);
}
getch();
}
Output Image :-> here
%c is the format string for a char data type
for printing a string you will want to use the %s format string
# include <stdio.h>
int main(){
char name [3][20];
printf("Enter 3 names\n");
for(int i = 0; i < 3; i++){
scanf("%s", name[i]);
}
for(int i = 0; i < 3; i++){
printf("%s\n", name[i]);
}
return 0;
}
You have to use %s instead of %c, (first one works with strings, second one with single chars).
change printf("%c\t",v.name[i]); to printf("%c\t",v.name[j]); because otherwise your loop wouldn't pass through all the names thus, print them out.

error while using array of pointers instead of 2 dimensional array

the following code crashes if i give array of pointer here is there any other way to accept value through array of pointers or did i do somethong wrong here
the run this program after compiling you should type
objectname -numberoflines
//program to print first n lines of string using command line arguement
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
int less(int x,int y);`enter code here`
int main(int argc,char* argv[])
{
int i,j,n,num;
char *lines[100];/*if I use two dimensional array here the code compiles
char nu[6];
// the whole for loop is for checking error in n
for(i=1,n=strlen(argv[1]);i<n;i++)
{
if(argv[1][i]=='.')
{
printf("your input was not correct \n");
return 0;
}
if(argv[1][i]=='-')
{
printf("your input was not correct \n");
return 0;
}
if(isalpha(argv[1][i])!=0)
{
printf("your input was not correct indeed");
return 0;
}
}
printf("\t\t application to print number of last n lines \n\n\n");
printf("enter the number of lines\n");
scanf("%d",&n);
printf("enter your lines \n");
for(j=0;(n<100)&&(j<=n);j++)
{
gets(lines[j]);
}
strcpy(nu,argv[1]);
nu[0]=' ';
num=atoi(nu);
num=(less(num,n));
for(i=0;i<=num;i++)
{
printf("%s",lines[i]);
}
return 0;
}
int less(int x,int y)
{
int z;
return (z=(x>y?y,printf("your input lines are less\n"):x));
}
The main problem is that when you write
char *lines[100];
You create an array of 100 char* pointers. These pointers have no memory allocated for them and they point to a random location. Writing to that location(using gets in your program) invokes Undefined Behavior.
To fix it, allocate memory for each pointer using
for(i=0 ; i<100 ; i++)
lines[i]=malloc(AMOUNT_OF_BYTES_TO_ALLOCATE);
And later, after the use is over, free the allocated memory using
for(i=0 ; i<100 ; i++)
free(lines[i]);
The reason that it worked when you used a two dimensional array is that you create an array of array of char for which memory is automatically allocated in the stack.

Using an Array to print out a number of asterisks, dependent on number inputted from user in C

So this program should print out the number of asterisks dependending on the number you enter, so if you enter 5, the 5 asterisks will print out.
I don't know where I am going wrong? Also if anyone can recommend a good book for C, I read through my school text and C for dummies, I am just not getting it.
void barplot(int num1, char array[]);
int main()
{
int n1;
printf("Enter a number: ");
scanf("%d",&n1);
printf("You have entered: %d\n",n1);
char astrk[n1];
strcpy(astrk, "*");
barplot(n1, astrk);
return(0);
}
void barplot(int num1, char array[])
{
printf("num1=%d\n",num1);
int i=0;
for(i=0; i<num1; i++)
{
printf("%c",array[i]);
}
}
Edit: An array is needed per the assignment
Given that you're stuck using an array, you can fill the astrk array with '*' characters using memset:
char astrk[n1];
memset(astrk, '*', n1);
barplot(n1, astrk);
return 0;
memset fills the array (the first argument) with copies of the character (the second argument), up to the length in the third argument. Note that this doesn't null-terminate the array, so you can't directly printf it.
If you do want to be able to printf it, then you should allocate enough space for the null terminator, like so:
char astrk[n1+1];
memset(astrk, '*', n1);
astrk[n1] = '\0'
printf("%s", astrk);
return 0;
Then you don't need the barplot function at all.
You don't really need a whole char array just to store one character. Let's just replace the char[] with a single char:
void barplot(int num1, char array);
int main()
{
int n1;
printf("Enter a number: ");
scanf("%d", &n1);
printf("You have entered: %d\n", n1);
barplot(n1, '*');
return 0;
}
void barplot(int num1, char ch)
{
printf("num1=%d\n",num1);
int i;
for(i=0; i<num1; i++)
{
putchar(ch);
}
}
You did not filled your astrk array with asterisks. You just copied over a string literal that has only one asterisk.
If you need only to print these asterisks, why do you need an array at all?
try this:
void barplot(int num1)
{
printf("num1=%d\n",num1);
for(i=0; i<num1; i++)
{
printf("*");
}
printf("\n");
}
void barplot(int num1)
{
char s[BUFSIZ];
memset(s,'*',BUFSIZ);
printf("%.*s",num1%BUFSIZ,s);
}
I wonder why it has not been mentioned that standard c does not allow variable length arrays. You can do variable length arrays in C99 (ISO/IEC 9899:1999) but they are not part of C++ or standard C. It might be supported by some compilers but there is always a risk.
Besides i am certain that above question being an assignment, was given with the intention that size determined at run time should be handled using dynamic allocation such as malloc.
char arr[SIZE]; // size has to be a constant value or a variable with const modifier
Size cannot be determined at run time for the above syntax.
You should use malloc as a standard practice
char *arr = malloc(n1);
This needs to be freed latter too
free(arr);

Resources