Question

I wanted to allocate a string array dynamically , the program is supposed to ask the user for characters and collect them in the first string in the array till letter 'q' is entered then the program starts adding the characters to the second line and so on.

When I print the characters memory location it seems like each character takes two memory cells instead of one though I increment it only once.

Here is the source code to my program

#include <stdio.h>

void main()
{

    char** txt;
    char* baseAddress;

    txt = (char **)malloc(5*sizeof(char*));
    *txt = (char *)malloc(20*sizeof(char));

    baseAddress = *txt;


    while (*(*txt) != 'q')
    {
       (*txt)++;
       scanf("%c", (*txt));
       printf("%p\r\n", (*txt));
    } 

    *txt = '\0';

    printf("%p", baseAddress);

    free(baseAddress);
    free(txt);
}

the output is like this

>j
>0x9e12021
>0x9e12022
>s
>0x9e12023
>0x9e12024
>

I think there may be something wrong with the pointers. How do I go about accomplishing this? and sorry for the bad english

Was it helpful?

Solution

What exacty you code do :

+----------------------------------------------+
|     +--------------------------------------+ |  
|  txt|*txt  |*txt+1 |*txt+2 |*txt+3 |*txt+4 | |
|     +--------------------------------------+ |
|       ^        ^    no memory alloc   ^      |
|       |        |_______not used_______|      |
|     +----+                                   |
|*txt |____|    <------------------------------+---you never give a value here,                            
| +1  |____|    <--j                           |
| +2  |____|    <-- '\n'                       |
| +3  |____|    <--s                           |
| +4  |____|    <-- '\n'                       |
|  .    .                                      |
|  .    .                                      |
|  .   ____                                    |
| +19 |____|                                   |
+----------------------------------------------+

So you need :

  1. re-write you while loop and deal with the '\n'
  2. when user type q , alloc new string memory and collect user input .

Suggust:

In you fisrt string

Use txt[0] instead of *txt , use txt[0][i] and i++ instead of **txt and (*txt)++ .

Hope can help. :-)

OTHER TIPS

You are forgetting about the newline character.

For instance, you are probably imagining your input to be "js". However, since you are hitting the enter key, it is actually "j\ns\n".

So, you are entering two characters at a time, and it is reading two characters at a time. Your code is behaving just as it should.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top