jonathan
jonathan

Reputation: 5

C how to store words in a char pointer from the user input

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    char *read[100];
    char *ch, *back;
    int i;

    ch = read;

    printf("Enter a sentence and get it reversed: ");
    while (getchar() != '\n') {
        *ch = getchar();
        ch++;
    }

    for (back = ch; back != read; back--) {
        printf("%s",*back);
    }

    return 0;
}

Here's my code. Does is it possible to store Strings in a Array or a pointer. This language is old. For exampel if the user wrote void and null the output should be null and void. And i tries this with a pointer to char array and want to just print the word backwords and it dosen't do anything. Whats wrong with my code?

Upvotes: 0

Views: 3153

Answers (3)

Spikatrix
Spikatrix

Reputation: 20244

Three problems:

  1. char *read[100]; isn't array of chars. It is an array of pointers to char. Change that to char read[100]; to get an array of chars of size 100.
  2. printf("%s",*back); is wrong as *back is a char but ℅s expects a char*. Change it to printf("%c",*back);.
  3. This for (back = ch; back != read; back--) { should be for (back = ch - 1; back >= read; back--) {. Otherwise, you'll be reading an uninitialized memory location in the first iteration of the loop.

Now that your code is vulnerable to a buffer overflow, i.e, when more than 100 characters are inputted, anything could be the result as your program will read and write from invalid memory locations invoking undefined behavior.

Upvotes: 4

You should use getline(3) if your system (e.g. a POSIX one) has it. Otherwise, declare a large enough line buffer (e.g. char linebuf[200];) and use fgets(3)

Then, you might parse the string (that is, your line buffer). You could use functions from <ctype.h> like isalpha(3), or perhaps use sscanf(3) (with e.g. a control string containing %70[A-Za-z]...)

Things would become more complex if you want to parse UTF-8 strings (since non-latin letters -like the Russian yery e.g. Ы- have multi-byte encoding). Then use some Unicode library like libunistring

Upvotes: 2

Laurens Ruijtenberg
Laurens Ruijtenberg

Reputation: 472

Strings in C don't have all the fancy stuff that Strings in Java or C#/.Net have. C strings are basically array's of char which are ended by a '\0' character. So when a function is doing operations on C string it starts reading characters at the memory location as specified by your char* pointer and goes on reading until it finds a '\0' character in the string. If it doesn't find a '\0' character it will go on reading characters until it hits an error because it's trying to read memory in a non assigned/allocated memory address. ps. You cannot assign void as value as it is a type.

Upvotes: 2

Related Questions