I'm new at C and I'm trying to do an exercise which asks to insert some strings and then store them. First it requests a multidimensional array where we have for every row of the array a string, and then as an array of pointers. Here's the code for the first part. I don't know how to store into an array some strings that are not already written.
For the second one I have no idea since I've never done exercises with pointers before.
#include <stdio.h>
int main(){
int n; //number of strings
int x; //number of characters per string
printf("How many strings do you want to insert?");
scanf("%d", &n);
if ((n >= 1) && (n <= 20)){
printf("How many characters per string?");
scanf("%d", &x);
char str[x];
if (x <= 10){
for(int i = 0; i < n; i++){
printf("Insert a string:");
scanf("%s", str);
for(int j = 0; j < x; j++){
char arr[j];
arr[j] = str[x];
printf("%s", arr);
}
}
}
else {
printf("Error:the number of characters must be < 10");
}
}
else {
printf("Error: the number must be < 20");
}
return 0;
}
... requests a multidimensional array where we have for every row of the array a string, and then as an array of pointers.
After getting the qualified number of strings, allocate an array of pointers to char
.
if ((n >= 1) && (n <= 20)){
char **string_list = calloc(n, sizeof *string_list);
assert(string_list); // or other error checking
(Notice no type in = calloc(n, sizeof *string_list);
. Easier to code right, review and maintain.)
Read the strings in a working temp buffer. As "How many characters per string?" likely means the number of characters not including the null character , our str[]
needs a +1 in size.
// char str[x]; // too small
char str[x+1];
Yet we know x <= 10
and can use a fixed buffer size and limit input length
for(int i = 0; i < n; i++){
char str[10+1];
printf("Insert a string:");
scanf("%10s", str); // Notice the 10 - a width limit
// TBD check if scanf() returned 1 and if str is longer than x
Now allocate a copy of the str
string_list[j] = strdup(str);
assert(string_list[j]); // or other error checking
}
Later, when done with string_list[]
, clean-up and free allocations.
for (int i=0; i<n; i++) {
free(string_list[i]);
}
free(string_list);
What is weak about this:
It uses scanf()
rather than fgets()
and then parses, has minimal error checking, does not take in strings with spaces, does not handle over-long input, strdup()
is not standard -yet , etc.
So the above is a baby step. Better code would handle the weak issues.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.