Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I receive 10 bytes (010830FFFFFFFFFF0304) in hexa on terminal, and I need to write only a part of this array (This 5 bytes FFFFFFFFFF) in another char array.
HereĀ“s the code:
#include <stdio.h>
void main(){
char buffer[]; // buffer size in bytes
int i; // counter
while(true){
for(i=0; i<buffer; i++){
buffer[i] = getc();
}
}
}
How to extract this part of array?
General fixup:
I declared an actual size for buffer (10), where you did not have a size.
I declared an array for your answer (middle), where you did not have such a space.
I loop 10 times, instead of the non-sense comparison i<buffer
I removed the outer while(true), which would never terminate.
I memcpy from the input buffer to the answer, for 5 characters.
Your question is very unclear and imprecise, so I can only guess at what you intended.
void main()
{
char buffer[10]; // buffer size in bytes
char middle[5];
int i; // counter
for(i=0; i<10; ++i){
buffer[i] = getc();
}
memcpy(middle, &buffer[3], 5*sizeof(char));
for(i=0; i<5; ++i)
{
printf("%x",middle[i]);
}
printf("\n");
}
as it seems you have a while(true) loop and all you need to do is just create another char array and put the needed chars in it:
#include <stdio.h>
void main()
{
char buffer[10]; // buffer size in bytes
char smallBuf[5]; // buffer size in bytes
int i; // counter
for(i=0; i<10; i++)
{
buffer[i] = getc();
}
for(i=0; i<5; i++)
{
smallBuf[i] = buffer[i + 3];
}
}
#include <stdio.h>
void main(){
char buffer[64]; // buffer size in bytes
char result[10];
int i; // counter
while(1){
for(i=0; i<10; i++){
buffer[i] = getc(stdin);
}
for(i=0; i<5; i++){
result[i] = buffer[i+3];
}
result[i] = 0; // end string
printf("%s\n",result);
}
}
Related
This question already has answers here:
Function to reverse string in C
(4 answers)
Closed 6 years ago.
Beginner programmer here. I'm trying to take an input from user, reverse it and show the result. For some reason, it's printing blanks instead of the reversed string. I know that array[i] has the right information because if I use this loop on line for (int i=0; i<count; i++), it's printing the right characters. It's just not printing in reverse. What am I not getting here?
#include <stdio.h>
#include <cs50.h>
#include <string.h>
int main(void)
{
printf("Please enter a word: ");
char *word = get_string();
int count = strlen(word);
char array[count];
for (int i=0; i< count; i++)
{
array[i] = word[i];
}
for (int i=count-1; i==0; i--)
{
printf("%c ", array[i]);
}
printf("\n");
}
for (int i=0; i< count; i++)
{
array[i] = word[i];
}
You go over the string and copy it, you do not reverse it.
There is also a subtle bug in-waiting in your declaration of array, since you do not leave space for the '\0' character terminator. Passing your buffer to printf as a C-string, as opposed to character by character will have undefined behavior.
So to fix those two particular errors:
char array[count + 1];
array[count] = '\0';
for (int i = 0; i< count; i++)
{
array[i] = word[count - i];
}
As a side note, it may not mean much to use a VLA for this small exercise, but for larger inputs it could very well overflow the call stack. Beware.
// the header where strlen is
#include <string.h>
/**
* \brief reverse the string pointed by str
**/
void reverseString(char* str) {
int len = strlen(str);
// the pointer for the left and right character
char* pl = str;
char* pr = str+len-1;
// iterate to the middle of the string from left and right (len>>1 == len/2)
for(int i = len>>1; i; --i, ++pl, --pr) {
// swap the left and right character
char l = *pl;
*pl = *pr;
*pr = l;
};
};
And just call the function:
int main(void) {
printf("Please enter a word: ");
char *word = get_string();
// Just call the function. Note: the memory is changed, if you want to have the original and the reversed just use a buffer and copy it with srcpy before the call
reverseString(word)
printf("%s\n", word);
};
And just change
char array[count];
for (int i=0; i< count; i++)
{
array[i] = word[i];
}
to
// add an other byte for the null-terminating character!!!
char array[count+1];
strcpy(array, word);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
How do you split a string:
char *mystring = "12345"
into an integer array which looks like this:
[1, 2, 3, 4, 5]
I have tried something like the code below, but I'm not entirely sure if it's reliable, and I think it will be easy to break. This is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(void) {
char *mystring = "12345";
int string_size, i, length;
string_size = strlen(mystring);
int values[string_size];
for (i = 0; mystring[i] != '\0'; i++) {
values[i] = mystring[i] - 48;
}
length = sizeof(values)/sizeof(*values);
for (i = 0; i < length; i++) {
printf("%d ", values[i]);
}
return 0;
}
Which outputs:
1 2 3 4 5
Is there a more C like way I can do this?
The odd thing I see, which isn't itself a problem, is that you calculate the length of the string/array three different ways:
string_size = strlen(mystring);
for (i = 0; mystring[i] != '\0'; i++) {
length = sizeof(values)/sizeof(*values);
where just one method is sufficient:
#include <stdio.h>
#include <string.h>
int main(void) {
char *mystring = "12345";
size_t length = strlen(mystring);
int values[length];
for (int i = 0; i < length; i++) {
values[i] = mystring[i] - '0';
}
for (int i = 0; i < length; i++) {
printf("%d ", values[i]);
}
printf("\n");
return 0;
}
You can replace 48 with '0' for readability.
You can change all loops to loop until string_size like the first one, no need to change the method for each loop.
And finally if you're going to return that array anywhere outside of local function, you should probably malloc() it rather than use a local/stack variable.
But otherwise, it's pretty simple and it works.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Shouldn't st be a array of pointers to char rather than a pointer to char? I do not understand how the latter for loop prints the value?
int main(void)
{
char temp[256];
char *st;
for (int i = 0; i < 3; i++)
{
scanf("%s", temp);
st= strdup(temp);
}
for(int i=0;i<3;i++)
{
printf("%s",st);
}
}
You probably want this:
#include <stdio.h>
#include <string.h>
int main(void)
{
char temp[256];
char *st[3]; // array of three pointers to char
for (int i = 0; i < 3; i++)
{
scanf("%255s", temp); // prevents potential buffer overflow
st[i] = strdup(temp);
}
for(int i = 0; i < 3; i++)
{
printf("%s\n", st[i]);
free(st[i]); // free strduped memory
}
}
This program displays:
./a.out
11
22
33
11
22
33
Whereas your program displays
./a.out
11
22
33
33
33
33
this is because:
char *st; // in your prog. you only declare one pointer
for (int i = 0; i < 3; i++)
{
scanf("%s", temp);
st= strdup(temp); // here you overwrite the st pointer loosing
// the string strduped in the previous run of the loop
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
This is the text of my example:
Loading number N then N words from standard input. The word is not longer than 100 characters. Dynamically allocate array of loaded words as a series of pointers to character strings (dynamic array needs to have a type char **). Provide a set of words printed in a single line with spaces between the words.
Can someone tell me how to set the character limits?
Should I do this:
scanf("%100s", str[i])
or something else?
BTW, how can I allocate the memory for a type like this (char **,int **,etc)?
This is my code that I've done, so what have I done wrong?
int main()
{
int i,n;
printf("How much words? "), scanf("%d", &n);
char *str= (char *)malloc(n*sizeof(char *));
for(i = 0; i < n; i++)
{
str[i] = malloc(100 * sizeof(char *));
printf("%d. word: ", i + 1),scanf("%s", str[i]);
}
for (i = 0; i < n; i++)
{
printf("%s ", str[i]);
}
getch();
Wrong type for array of pointers
// char *str
char **str
Code clean-up with comments.
// add void
int main(void) {
int i,n;
// Easier to understand if on 2 lines-of code
printf("How much words? ");
// test scanf() results
if (scanf("%d", &n) != 1) return -1;
// Consider different style to allocate memory, as well as type change
// char *str= (char *)malloc(n*sizeof(char *));
char **str= malloc(sizeof *str * n);
// check allocation
assert(str == NULL);
for(i = 0; i < n; i++) {
str[i] = malloc(sizeof *str[i] * 100);
// check allocation
assert(str[i] == NULL);
printf("%d. word: ", i + 1);
fflush(stdout);
// limit input width to 99
// test scanf() results
if (scanf("%99s", str[i]) != 1) return -1;
}
for (i = 0; i < n; i++) {
// Add () to clearly show beginning/end of string
printf("(%s) ", str[i]);
}
getch();
}
My text file is formated like that:
my.txt
Red
Green
Blue
Yellow
I'm tring to get words like that:
typedef char * string;
main(){
int i;
string array[4];
FILE *my;
my = fopen("my.txt","r");
for(i = 0; i < 4; i++)
fscanf(data, "%s", &array[i]);
fclose(my);
}
When I try to print the array there is an error. What's wrong with my code and how can I fix it?
You'll need to allocate memory for your null-terminated strings.
At the moment you are only allocating memory for 4 char *, but these pointers are uninitialized and therefor will result in UB (undefined behavior) when you try to write data to the memory pointed to by them.
Working example snippet
The use of "%127s" in the below snippet is to prevent us writing outside the bounds of the allocated memory. With the format-string in question we will at the most read/write 127 bytes + the null-terminator.
Please remember that further error checks should be implemented if this is to be used in "real life".
Check to see that file_handle is indeed valid after attempt to open the file
Check to see that malloc did indeed allocate requested memory
Check to see that fscanf read the desired input
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int
main (int argc, char *argv[])
{
int i;
char * lines[4];
FILE *file_handle = fopen ("my.txt", "r");
for (i =0; i < 4; ++i) {
lines[i] = malloc (128); /* allocate a memory slot of 128 chars */
fscanf (file_handle, "%127s", lines[i]);
}
for (i =0; i < 4; ++i)
printf ("%d: %s\n", i, lines[i]);
for (i =0; i < 4; ++i)
free (lines[i]); /* remember to deallocated the memory allocated */
return 0;
}
output
0: Red
1: Green
2: Blue
3: Yellow
You try to read some data, but you don't have anywhere to put it. All you have is 4 pointers, pointing to god knows where and you are trying to write into it!
There are many ways to do this:
You know the bound to the size of the data:
#include <stdio.h>
#define MAX_CHARS 20
typedef char string[MAX_CHARS+1]; // leave one space for '\0'
main(){
int i;
string array[4];
FILE *my;
my = fopen("my.txt","r");
for(i = 0; i < 4; i++)
fscanf(data, "%s", array[i]); // no need for & with %s
fclose(my);
}
Assume a bound to the size of the data, and ignore the rest of the strings (if it was too big):
#include <stdio.h>
#define MAX_CHARS 20
#define MAX_CHARS_STR "20" // there are better ways to get this
typedef char string[MAX_CHARS+1];
main(){
int i;
string array[4];
FILE *my;
my = fopen("my.txt","r");
for(i = 0; i < 4; i++){
fscanf(data, "%"MAX_CHARS_STR"s", &array[i]); // read at most 20 chars for the string
ungetc('x', data); // append one character to make sure we don't hit space
fscanf(data, "%*s"); // ignore whatever is left of string
}
fclose(my);
}
Read the file twice, first time find out the sizes of each string (or the maximum size, for simplicity), then allocate memory for the strings (using malloc). Then read the file again and this time actually store the strings:
#include <stdio.h>
typedef char *string;
main(){
int i;
string array[4];
int cur_size = 0;
FILE *my;
my = fopen("my.txt","r");
for(i = 0; i < 4; i++){
fscanf(data, "%*s%n", &cur_size);
array[i] = malloc((cur_size+1)*sizeof(*array[i]));
}
fclose(my);
my = fopen("my.txt","r");
for(i = 0; i < 4; i++){
fscanf(data, "%s", array[i]);
}
fclose(my);
// and when done:
for(i = 0; i < 4; i++){
free(array[i]);
}
}
Read from the input chunk by chunk. For each string, if input string was not finished yet resize the memory allocated for the string (increase its size), read another chunk and check again. Method 3 is faster though and I recommend it, but just so you know, this is basically what happens in C++'s string.
Since all the other answers told you what you did wrong but not how to fix it. Here
typedef char * string;
#define LEN 100 //long enough for your line
main(){
int i;
string array[4];
for(i = 0; i < 4; i++) {
if((array[i] = (char *)(malloc(sizeof(char) * LEN))) == NULL) {
printf("malloc failed");
return 1;
}
}
FILE *my;
my = fopen("my.txt","r");
for(i = 0; i < 4; i++)
fscanf(data, "%s", &array[i]);
fclose(my);
}
And like they said you made space for the pointers but not for what the pointers point to.