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;
}
Related
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?
I am trying to make a two dimensional array in a struct using pointer since I am new to c and get quite confuse in the topic of pointer. Help please!
struct course
{
char *coursecode;
char *coursesession[5];
};
int main()
{
int n = 0;
int numSession = 0;
struct course *main = malloc(sizeof(struct course));
printf("Enter the course code and the session in this order:");
scanf("%s", main->coursecode);
printf("Enter the number of session required:");
scanf("%d", &numSession);
for (int i = 0; i < numSession; ++i)
{
printf("Enter the session code (M1...):");
scanf("%s", main->coursesession[i]);
}
++n;
}
You've declared coursecode to be a pointer to char, but you need to allocate space for it, which you can do with malloc.
And you've declared coursesession to be an array of 5 pointers to char. You need to allocate space for all 5 pointers, again with malloc.
Alternatively, you could declare both of them as arrays, e.g.
struct course
{
char coursecode[100];
char coursesession[5][100];
};
This declares coursecode to be an array of 100 char, and coursesession to be an array of 5 arrays of 100 char. Obviously you could adjust the 100 to whatever you need, but the storage size would be fixed regardless.
You can modify code like this
#include <stdio.h>
#include<stdlib.h>
struct course
{
char *coursecode;
char *coursesession[5];
};
int main()
{
int n,i = 0;
int numSession = 0;
struct course main;
main.coursecode = (char *)malloc(100*sizeof(char));
printf("Enter the course code and the session in this order:");
scanf("%s", main.coursecode);
printf("Enter the number of session required:");
scanf("%d", &numSession);
for (i = 0; i < numSession; ++i)
{
printf("Enter the session code (M1...):");
main.coursesession[i] = (char *)malloc(100*sizeof(char));
scanf("%s", main.coursesession[i]);
}
++n;
free(main.coursecode);
for (i = 0; i < numSession; ++i){
free(main.coursesession[i]);
}
}
If N is a positive number, extend given string S, for N places, using character C. Complete it using a function and in the main function check if the function works. Any value of N gives me "it doesn't work".
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cat(char*,char,int);
int main()
{
char S[20],C;
int N;
puts("Enter N: ");
scanf("%d",&N);
puts("Enter string: ");
gets(S);
if (N<1)
printf("it's unknown whether it works");
else if(cat(S,C,N)==strlen(S)+N)
printf("it works.");
else
printf("it doesn't work.");
}
int cat(char*S,char C,int N){
int i;
char T[20];
for(i=0;i<N;i++)
T[i]=C;
return strlen(strcat(S,T));
}
You need to initialize the C character variable:
char C = 'C';
The strcat function concatenates the 2 string parameters & returns a string whose length is equal to the sum of the 2 strings' length. So you need to declare a new array whose size is string1 + string2's length in the cat function that will hold the concatenation result. Then return its length.
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.
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]);
}
}