-1

I'm trying to create a function that get a string, taking char by char:

char * GetString (int dim) // dim is the size of the string
{
    char c, *S;
    int i = 0;

    S = (char*)malloc(dim*(sizeof(char));

    while ((c=getchar() != '\n') && (i < dim) && (c != EOF))
    {
        S[i] = c;
        i++;
    }

    S[i] = '/0';

    return S;
}

The problem is when i try to use a "printf" in this function, trying to see if the input was taken correctly, it shows me strange characters, not the ones i inserted. I don't know what i'm missing.

Thanks very much.

Mauri
  • 41
  • 7

4 Answers4

6

This should be a backslash:

S[i] = '\0';

Make sure your compiler warnings are turned on and you're paying attention to them. '/0' is a non-standard multi-character integer literal.

Backslash zero '\0' is the C string NUL-terminator you're after.

Also, in the case where your input is larger than dim, you are overrunning your buffer, writing one byte more than you allocated. I would suggest allocating dim+1 bytes.

Finally, there's no point in multiplying by sizeof(char) - it is 1 by definition.

P.S. Now is an excellent time to learn how to use a debugger. If you're using GNU tools: gcc -Wall -Werror main.c then gdb a.out, and type r to run.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
3

This '/0' is a character constant which value is implementation defined. So you have to replace it with escape character '\0'.

Also you have to allocate dim + 1 bytes if you want to append exactly dim characters with the terminating zero.

The function can look like

char * GetString( int dim )
{
    char *s;
    int i;

    s = ( char* )malloc( ( dim + 1 ) *( sizeof( char ) );

    i = 0;
    while ( i < dim && ( ( c = getchar() ) != '\n') && ( c != EOF ) )
    {
        s[i++] = c;
    }

    s[i] = '\0';

    return s;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
2

Thanks to Vlads from Moscow for the right snippets. The problem was here:

while (c = getchar() != '\n')

It's wrong, the right way:

while ((c=getchar()) != '\n')
Mauri
  • 41
  • 7
1

The code had an amazingly simple problem: you missed parentheses around c=getchar(). Try ((c=getchar()) != '\n') instead of (c=getchar() != '\n') The code has other problems also, like using /0 instead of \0

Here is the rectified code:

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

char * GetString (int dim) // dim is the size of the string
{
    char c, *S;
    int i = 0;

    S = (char*)malloc(dim*(sizeof(char)));

    while (((c=getchar()) != '\n') && (i < dim) && (c != EOF))
    {
        S[i] = c;
        i++;
    }

    S[i] = '\0';

    return S;
}

int main()
{
    char *s;

    s = GetString(10);
    printf("%s\n", s);
    free(s);

    return 0;
}
Nandakumar Edamana
  • 770
  • 1
  • 4
  • 10