As i know, i can create an array with item inside such as:
char *test1[3]= {"arrtest","ao", "123"};
but how can i store my input into array like code above because i only can code it as
input[10];
scanf("%s",&input) or gets(input);
and it store each char into each space.
How can i store the input "HELLO" such that it stores into input[0] but now
H to input[0],E to input[1], and so on.
You need a 2 dimensional character array to have an array of strings:
#include <stdio.h>
int main()
{
char strings[3][256];
scanf("%s %s %s", strings[0], strings[1], strings[2]);
printf("%s\n%s\n%s\n", strings[0], strings[1], strings[2]);
}
Use a 2-dimensional array char input[3][10];
or
an array of char pointers (like char *input[3];) which should be allocated memory dynamically before any value is saved at those locations.
First Case, take input values as scanf("%s", input[0]);, similarly for input[1] and input[2]. Remember you can store a string of max size 10 (including '\0' character) in each input[i].
In second case, get input the same way as above, but allocate memory to each pointer input[i] using malloc before. Here you have flexibility of size for each string.
Did not really understand what you need. But here is what I guessed.
char *a[5];//array of five pointers
for(i=0;i<5;i++)// iterate the number of pointer times in the array
{
char input[10];// a local array variable
a[i]=malloc(10*sizeof(char)); //allocate memory for each pointer in the array here
scanf("%s",input);//take the input from stdin
strcpy(a[i],input);//store the value in one of the pointer in the pointer array
}
try below code:
char *input[10];
input[0]=(char*)malloc(25);//mention the size you need..
scanf("%s",input[0]);
printf("%s",input[0]);
int main()
{
int n,j;
cin>>n;
char a[100][100];
for(int i=1;i<=n;i++){
j=1;
while(a[i][j]!=EOF){
a[i][j]=getchar();
j++;
}
}
This code inspired me on how to get my user input strings into an array. I'm new to C and to this board, my apologies if I'm not following some rules on how to post a comment. I'm trying to figure things out.
#include <stdio.h>
int main()
{
char strings[3][256];
scanf("%s %s %s", strings[0], strings[1], strings[2]);
printf("%s\n%s\n%s\n", strings[0], strings[1], strings[2]);
}
Related
I have created Date struct to store date format as date, month, year which is inputed by the user as a single line string seperated by space.
I want to split the input and store it accordingly. I have used simple C sscanf() to split and store my input in struct Date. But when I try to print my data it's showing some garbage value, I don't know what is missing.
Help me to clear this issue.
My code:
Input: 24 Jan 1980
output: 24 ? -978635323
here is my C code.
struct Date
{
int date;
char* month;
int year;
};
int main()
{
struct Date date[1];
char* string;
scanf("%s",string);
sscanf(string,"%d %s %d",&date[0].date,date[0].month,&date[0].year);
printf("%d %s %d",date[0].date,date[0].month,date[0].year);
return 0;
}
Thanks in advance.
it works for me. You can check it.
struct Date
{
int dat;
char month[20];
int year;
};
int main()
{
struct Date date[1];
char str[20];
scanf("%[^\n]%*c", str);
sscanf(str,"%d %s %d",&date[0].dat,&date[0].month,&date[0].year);
printf("%d %s %d",date[0].dat,date[0].month,date[0].year);
return 0;
}
EXPLANATION
In your code, you have declared two char * pointers char *month and char *string, and trying to store string values in them. You have to understand that these two are mere pointers. All they can store are memory addresses to char arrays. It is true that an array variable is interchangeable with a pointer in C. But an array declaration also involves a size attribute.
When you declare a character array as:
char str[10];
It actually reserves a block of size 10 in memory, implicitly creates char *str, and stores the base address of the newly created block in str. But when you just declare char *str, all it does is create a pointer. This doesn't have any associated memory block for the array.
That's why you have to declare a character array of some size before storing strings in it with scanf(). Or you have to dynamically allocate memory with calloc or malloc after declaring the char * pointer. Only then can you store a string input in it.
I have modified your code to work properly. It produces the desired output now. Hope this helps.
WORKING CODE
#include <stdio.h>
#include <stdlib.h>
struct Date
{
int date;
char month[10];
int year;
};
int main()
{
struct Date date[1];
char string[20];
scanf("%[^\n]s",string);
sscanf(string,"%d %s %d",&date[0].date,date[0].month,&date[0].year);
printf("%d %s %d",date[0].date,date[0].month,date[0].year);
return 0;
}
EDIT
They themselves are integers actually (as are all pointers).
As mentioned by anastaciu, pointers are not equivalent to integers per se. You can follow the links given in his comments for more knowledge. I had mentioned that statement to assert the difference between pointers and array declarations.
char* string is an uninitialized pointer, it cannot hold a string, you need to allocate memory, initialize it as an array of chars or point it to a variable with memory already allocated or to an existing array of chars.
Your structure member month suffers from the same problem.
A -Wall flag in your compiler should give you a warning:
'string is used uninitialized in this function [-Wuninitialized]'
Another problem is that %s only gets a string, when it finds a blank space, it stops reading, so it can only read 24 in your case.
Though "%[^\n]s" can work, a better solution would be to use fgets, it's a safer function since you can limit the size of the input to the size of receiving container, unlike scanf.
#include <stdio.h>
#define SIZE 100
struct Date
{
int date;
char month[SIZE];
int year;
};
int main()
{
struct Date date[1];
char string[SIZE];
fgets(string, sizeof(string), stdin);
sscanf(string,"%d %s %d",&date[0].date, date[0].month, &date[0].year);
}
I'm new to C and i'm trying to store some strings inside a 2D array of chars.Here's what i have:
char strArray[100][100];
char input[100];
scanf("%s",&input);
strArray[i] = input; //this is where i get the incompatible types assignment error
As shown in the comment i get an incompatible types in assignment error.Do i need to use an array of char *strArray[100][100] ? Aren't strArray and input both of the same type (char [])? The one's 1D and the other is 2D obviously but i just didn't specify the 2nd dimension in the assignment since each string is stored in a new line. What am i doing wrong?
You'd have to use strcpy():
#include <stdio.h>
#include <string.h>
int main(void)
{
char strArray[100][100];
char input[100];
scanf("%s", input);
strcpy(strArray[0], input);
}
But never, really: never! use scanf() with "%s" without limiting the number of characters to read (field width):
scanf("%99s", input);
You can use strcpy() to copy each char in input to strArray[i]. In this case you would use
strcpy(strArray[i], input);
In C, you cannot assign arrays in the sense of char input1[100], input2[100]; input1 = input2. You can just copy the contents using, for example, strcpy for strings or memcpy for arbitrary memory chunks.
So you'd have to write strcpy(strArray[i],input), provided that i is an integral value between 0 and 99 in your case.
Further, you'll have to omit the & in scanf("%s",&input) (i.e. write scanf("%s",input)), because input already decays to a pointer to char.
#include <stdio.h>
#include <string.h>
int main(void) {
int number_of_members;
char family[number_of_members][20][number_of_members][20];
char member_name[20];
char birth_state[20];
char family_last_name[20];
printf("What is the last name of the family?\n");
scanf("%s", &family_last_name);
printf("How many members do you want to create?\n");
scanf("%d", &number_of_members);
int const FAMILY_SIZE = number_of_members;
number_of_members = number_of_members -1;
printf("Enter the family member name: \n");
for(number_of_members;number_of_members>-1;number_of_members--)
{
scanf("%s", &member_name);
strcpy(family[number_of_members], member_name);
printf(" %d %s %s\n",number_of_members, member_name, family_last_name);
}
printf("%s, %s ", family[0], family[1]);
return 0;
}
Here is the output:(from Ideone.com)
Ideone.com with code
The input to this code is: Layne , 2 , tim , jim.
When run, it shows the correct index with the name in the array however, once out it will show the last entered name, jim, as family1 and family[0]. Am I not understanding how strcpy() works? or is it a logic error?Some assistance soon would be appreciated!
This is very very wrong
int number_of_members;
char family[number_of_members][20][number_of_members][20];
Because you haven't initialized number_of_members.
Because it doesn't make sense whatsoever, it's not possible that you really need this kind of array.
And yes, if you enable compiler warnings it will hit you in your nose with a stick, because
strcpy(family[number_of_members], member_name);
shouldn't even compile and is undefined behavior since the type of family[number_of_members], is an array of arrays of arrays of char.
strcpy can take an array of char's because it will be automatically converted to a char poitner, and provided that the contents of the array comply with what a c string is, then strcpy() will work correctly, in your case the behavior is undefined because almost surely the '\0' will never be found in the destination pointer.
instead of
int num_of_members;
char family[number_of_members][20][number_of_members][20];
which is not C code, do this
#define MAX_MEMBERS 20
char family[MAX_MEMBERS][20];
which creates a rectangular array of arrays each of 20 bytes long
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLINES 25
int get_lines(char *studentinfo[]);
int main()
{
int onswitch=0;
char *studentinfo[100];
char *fname[100];
char *lname[100];
char *score[100];
int counter;
int x,y;
char temp,temp2,temp3;
counter=get_lines(studentinfo);
for (y=0; y<counter; y++)
{
temp=strtok(studentinfo, " ");
fname[y]=malloc(strlen(temp));
strcpy(fname[y],temp);
temp2=strtok(NULL, " ");
lname[y]=malloc(strlen(temp2));
strcpy(lname[y],temp2);
temp3=strtok(NULL," ");
score[y]=malloc(strlen(temp3));
strcpy(score[y],temp3);
int get_lines(char *studentinfo[])
{
int n=0;
char buffer[80];
puts("Enter one line at a time; enter a blank when done.");
while ((n<MAXLINES) && (gets(buffer) !=0) && (buffer[0] != '\0'))
{
if ((studentinfo[n]=(char*)malloc(strlen(buffer)+1))==NULL)
return -1;
strcpy(studentinfo[n++],buffer);
}
return n;
}
Alright guys I am trying to make program that takes in student information for sorting later. I have taking the input down with the function on the bottom. I am trying to break down to the student information into three different pointers for sorting. The problem I am having is trying to allocate enough memory to store then information. Then actually storing the memory in that pointer location.
A simple input is
John Smith 80
^fname ^lname ^score
I thought the for loop I had would work in theory but it didnt (error: Unhandled exception at 0x0F3CFA50 (msvcr110d.dll) in ConsoleApplication3.exe: 0xC0000005: Access violation reading location 0xFFFFFF8) can anybody point me in the right direction (not just give me a loop that works) ?
With your implementation, you get an access violation. You are trying to touch a dirty region of memory. Here is the solution with an explanation below
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLINES 25
int get_lines(char *studentinfo[]);
int main()
{
int onswitch=0;
char *studentinfo[100];
char *fname[100];
char *lname[100];
char *score[100];
int counter;
int x,y;
char *temp,*temp2,*temp3;
counter=get_lines(studentinfo);
for (y=0; y<counter; y++)
{
temp=strtok(studentinfo[y], " ");
fname[y]=malloc(strlen(temp));
strcpy(fname[y],temp);
temp2=strtok(NULL, " ");
lname[y]=malloc(strlen(temp2));
strcpy(lname[y],temp2);
temp3=strtok(NULL," ");
score[y]=malloc(strlen(temp3));
strcpy(score[y],temp3);
printf("%s %s %s", fname[y], lname[y], score[y]);
}
}
int get_lines(char *studentinfo[])
{
int n=0;
char buffer[80];
puts("Enter one line at a time; enter a blank when done.");
while ((n<MAXLINES) && (gets(buffer) !=0) && (buffer[0] != '\0'))
{
if ((studentinfo[n]=(char*)malloc(strlen(buffer)+1))==NULL)
return -1;
strcpy(studentinfo[n++],buffer);
}
return n;
}
First off, you are missing an ending bracket } for your for loop as well as your main function. So add those.
Your getlines function is all good.
Your for loop is screwed up. In particular, you confused the data types you are passing. Remember, you have declared an array of POINTERS.
temp=strtok(studentinfo, " ");
This is saying, hey, let's tokenize my array pointer. You don't want this. You want to tokenize the yth element in that array! So element 0 in your array is a pointer to the string "JOHN SMITH 80". This is what we want to tokenize. Otherwise what you had was trying to tokenize somthing along the lines of 0xabcdabcd or whatever the memory address of the allocated array was.
temp=strtok(studentinfo[y], " ");
This is the correct way. It says tokenize the first element, which is a pointer to our string.
Your next problem is your temp variables. You are calling strlen(temp). strlen expects a pointer to a string. You are passing the data of the char itself. Actually, you are passing the return pointer (likely null) of the strtok function that was stored in your char byte.
char temp,temp2,temp3;
You declared three bytes for the type char. What you wanted was three char * to hold pointers to your string tokens.
char *temp,*temp2,*temp3;
With this, strlen takes in these pointers, mallocs some space for your fname elements, and then you proceed to copy into this element using strcpy.
Note: strcpy also takes two pointers, one for destination, one for source, so again your temp variables needed to be pointers to your strings.
Hope this helps let me know if you are confused with my explanation at all.
strcpy takes characters until it reaches a \0 character. You want to check out the strncpy or memcpy functions, and then manually add the null terminator.
I have an assignment I've been working on for a few hours now, and I can't seem to get it quite right. The assignment is to take a random number of names (from stdin), sort them, and then output them in alphabetical order. I can't find any sites online that handle this kind of sorting specifically, and have had no luck trying to implement qsort() into my code.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int stringcmp(const void *a, const void *b)
{
const char **ia = (const char **)a;
const char **ib = (const char **)b;
return strcmp(*ia, *ib);
}
void main(int argc, char *argv[])
{
char *input[] = {" "};
char temp[20][20];
int i = 0;
int num = 0;
int place = 0;
int stringlen = sizeof(temp) / sizeof(char);
printf("How many names would you like to enter? ");
scanf("%d", &num);
while (place < num)
{
printf("Please input a name(first only): ");
scanf("%s", input[place]);
printf("The name you entered is: ");
printf("%s\n", input[place]);
place++;
}
//qsort(temp, stringlen, sizeof(char *), stringcmp); <-- just an idea I was messing with
qsort(input, stringlen, sizeof(char *), stringcmp);
printf("Names:\n");
for(i=0; i<place; i++)
printf("%s\n", input[i]);
system("PAUSE");
return(EXIT_SUCCESS);
}
The main problem is, when I go to output my code, I cannot use the char *input variable because of how its declared. The temp[] will display, but will not be sorted by qsort because it is not declared as a pointer. Any ideas?
You can't declare your input array like that. Since you know how many the user requires, you can dynamically allocate the array:
char **input = malloc(num * sizeof(char*));
Likewise, when you read your strings in, they need somewhere to go. Simply passing an uninitialized pointer to scanf is not okay. I suggest you define the maximum length of a name and have a temporary buffer for reading it:
const size_t MAX_NAME = 50;
char name[MAX_NAME];
...
for( i = 0; i < num; i++ )
{
printf("Please input a name(first only): ");
scanf("%s", name);
input[i] = strdup(name);
}
[Note this does not prevent the user from overflowing the 'name' buffer. I used scanf for illustrative purposes only]
You seem to be passing the wrong array length to qsort. Try this:
qsort(input, num, sizeof(char *), stringcmp);
When you are finished, you need to release memory for all the names and the array.
for( i = 0; i < num; i++ ) free(input[i]);
free(input);
could you explain
the ** declarations throughout the code? I'm not sure what they're
used for, although I know the function for stringcmp is a widely used
algorithm, I have no idea how it works; I'm thrown off by the double
de-reference markers.
Yep, in the case where I used it, I am telling C that to get a single character, I have to dereference a pointer twice. When you index a pointer, it's dereferencing. So I allocated an array by requesting a block of memory containing num * sizeof(char*) bytes. Because I assigned that pointer to a char**, the compiler knows that I am pointing to a chunk of memory that contains char* values.
If I ask for input[0] (this is the same as *input) it should look at the very start of that memory and pull out enough bytes to form a char*. When I ask for input[1], it skips past those bytes and pulls out the next bunch of bytes that form a char*. Etc... Likewise, when I index a char*, I am pulling out single characters.
In your stringcmp function, you have the following situation. You passed a void* pointer to qsort so it doesn't actually know the size of the data values stored in your array. That's why you have to pass both the array length AND the size of a single element. So qsort just blindly rips through this arbitrary-length array of arbitrary-sized values and fires off memory addresses that ought to contain your data for comparison. Because qsort doesn't know anything else about your array elements except where they are located, it just uses void*.
But YOU know that those pointers are going to be the memory addresses of two of your array elements, and that your array elements are char*. So you need the address of a char* (hence you cast the pointers to char**). Now you need to dereference these pointers when you call strcmp() because that function requires a char* (ie a value that points directly to the memory containing your string characters). That is why you use the * in strcmp(*ia, *ib).
One quick way to fix your program is to declare input as an array of pointers, like this:
char *input[20];
When you read names in, use tmp[place] for your buffer, and store the pointer into input, like this:
scanf("%19s", tmp[place]);
input[place] = tmp[place];
Now sorting the input should work fine.
This has a limitation of being limited to 20 lines of 20 characters max. If you learned about malloc in the class, you should be able to fix that by allocating your strings and the string array dynamically.