944,118 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Unsolved
  • Views: 846
  • C RSS
You are currently viewing page 1 of this multi-page discussion thread
Oct 26th, 2009
0

Array of pointers to char...messed up!

Expand Post »
I want to finaly learn what's up with pointers and arrays, so i made up this program:

#include <stdio.h>

int main()
{
    int cantidad_frases = 0;
    printf("Cuantas frases quieres escribir?: ");
    scanf("%d", &cantidad_frases);
    char *frases[cantidad_frases];
    for(unsigned i = 0; i < cantidad_frases; i++)
    {
        for(; *frases[i]; frases[i]++)
        {
            *frases[i] = getchar();
        }
    }
    printf("\nReproduciendo las frases:\n\n");
    for(unsigned i = 0; i < cantidad_frases; i++)
    {
        printf("Frase %d:", i + 1);
        for(; *frases[i]; frases[i]++)
        {
            printf("%c", *frases[i]);
        }
        printf("\n");
    }
    return 0;
}

I had no errors nor warnings at all. But program crashes after entering the cantidad_frases value and hitting enter. The problem is in the 11th line.

I really didn't know how to "refer" each letter of the words/string stored in frases[i].
I hope i made my question clear enough so you can help me. Any advise or (please) any specific place where they explain the whole thing about pointers and arrays is more than welcome!
Reputation Points: 12
Solved Threads: 2
Junior Poster in Training
neithan is offline Offline
75 posts
since Oct 2009
Oct 26th, 2009
0
Re: Array of pointers to char...messed up!
This line should probably be:

char *frases[cantidad_frases];

  1. char *frases = (char*)malloc(cantidad_frases);

So that you have allocated the memory...
Last edited by gerard4143; Oct 26th, 2009 at 8:34 pm.
Reputation Points: 499
Solved Threads: 367
Postaholic
gerard4143 is offline Offline
2,198 posts
since Jan 2008
Oct 27th, 2009
0
Re: Array of pointers to char...messed up!
  1. for(unsigned i = 0; i < cantidad_frases; i++)
  2. {
  3. for(; *frases[i]; frases[i]++)
  4. {
  5. *frases[i] = getchar();
  6. }
  7. }
U have not assigned memory to frases[i].

Do
  1. #define MAX_STR 40 // whatever u want
  2. frases[i] = malloc(MAX_STR);
U are alos doing another mistake:
  1. for(; *frases[i]; frases[i]++)
here frases[i] is getting incremented. Hence the pointer advances and when later u want the inputed string u wont have it because the pointer has advanced to the end hence it contain nothing. U should do this with some temp pointer as
  1.  
  2. for(unsigned i = 0; i < cantidad_frases; i++)
  3. {
  4. frases[i] = malloc(MAX_STR);
  5. char *tmp = frases[i];
  6. for(; *tmp; tmp++)//AGAIN HERE U SHOULD MODIFY YOUR LOGIC BECAUSE frases[i] initially contains nothing. I am leaving it to you.
  7. {
  8. *tmp = getchar();
  9. }
  10. }
Last edited by dkalita; Oct 27th, 2009 at 3:15 am.
Reputation Points: 121
Solved Threads: 61
Posting Pro in Training
dkalita is offline Offline
402 posts
since Sep 2009
Oct 27th, 2009
0
Re: Array of pointers to char...messed up!
And in C for(unsigned i = 0; i < cantidad_frases; i++) is illegal.
i must be defined before it is used, not in the for statement.
Moderator
Reputation Points: 3281
Solved Threads: 895
Posting Sage
WaltP is online now Online
7,746 posts
since May 2006
Oct 27th, 2009
0
Re: Array of pointers to char...messed up!
Click to Expand / Collapse  Quote originally posted by gerard4143 ...
This line should probably be:

char *frases[cantidad_frases];

  1. char *frases = (char*)malloc(cantidad_frases);

So that you have allocated the memory...
Click to Expand / Collapse  Quote originally posted by dkalita ...
  1.  
  2. for(unsigned i = 0; i < cantidad_frases; i++)
  3. {
  4. frases[i] = malloc(MAX_STR);
  5. char *tmp = frases[i];
  6. for(; *tmp; tmp++)//AGAIN HERE U SHOULD MODIFY YOUR LOGIC BECAUSE frases[i] initially contains nothing. I am leaving it to you.
  7. {
  8. *tmp = getchar();
  9. }
  10. }
char *tmp = frases[i]; <--- i'm confused here. Where does tmp point at?
Click to Expand / Collapse  Quote originally posted by WaltP ...
And in C for(unsigned i = 0; i < cantidad_frases; i++) is illegal.
i must be defined before it is used, not in the for statement.
I'm told in C99 is perfectly accepted?


OK so i see my fault was all about memory allocation, so im going to learn about that cause i know nothing.
However, if you had this *frases[].. let's say it cointains:
*frases[0] -> "tutorials"
*frases[1] -> "dani web"
*frases[2] -> "it discussion"

How would you refer to the w in web at frases[1]?

Thank you
Reputation Points: 12
Solved Threads: 2
Junior Poster in Training
neithan is offline Offline
75 posts
since Oct 2009
Oct 27th, 2009
0
Re: Array of pointers to char...messed up!
Quote ...
How would you refer to the w in web at frases[1]?
  1. frases[1][5];
or if you want to complicate it
  1. *(*(frases + 1)+ 5)
Last edited by Aia; Oct 27th, 2009 at 7:48 pm.
Aia
Reputation Points: 2224
Solved Threads: 218
Nearly a Posting Maven
Aia is offline Offline
2,304 posts
since Dec 2006
Oct 28th, 2009
0
Re: Array of pointers to char...messed up!
Click to Expand / Collapse  Quote originally posted by Aia ...
  1. frases[1][5];
or if you want to complicate it
  1. *(*(frases + 1)+ 5)
Awesome. The complicated version...heheh yes.
frases is pointing at 0, so +1 makes it look at the second phrase. And then the * dereference symbol, would return what? The first word in the first phrase? --> *( ? ) + 5 <---- ? should be a memory adress so it can be added with 5 and then dereference returning the "w" letter. But how come just doing *(frases + 1) returns not the value but a memory address?

Instead of mallocation before user's input, isn't the way to allocate at the same time user inputs so you reserve the exact memory needed? Like in run time.

Thank you for your time, i'm learning a lot. I'm gonna focus learning memory, malloc and pointers stuff more.
Reputation Points: 12
Solved Threads: 2
Junior Poster in Training
neithan is offline Offline
75 posts
since Oct 2009
Oct 29th, 2009
0
Re: Array of pointers to char...messed up!
I made it! It works perfectly thanks to your advices and further studying hehe. Any comments / corrections?

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. int main()
  5. {
  6. int cantidad_frases = 0;
  7. printf("Cuantas frases quieres escribir?: ");
  8. scanf("%d", &cantidad_frases);
  9. getchar();
  10. char *frases[cantidad_frases];
  11. for(unsigned i = 0; i < cantidad_frases; i++)
  12. {
  13. frases[i] = (char *) malloc(sizeof(char[20]));
  14. char *tmp = frases[i];
  15. printf("Escribe la frase %d: ", i+1);
  16. while((*tmp = getchar()))
  17. {
  18. if(*tmp == 10)
  19. {
  20. *tmp = '\0';
  21. break;
  22. }
  23. tmp++;
  24. }
  25. }
  26. for (unsigned i = 0; i < cantidad_frases; i++)
  27. {
  28. puts(frases[i]);
  29. }
  30.  
  31. return 0;
  32. }

I was turning mad when i saw phrase one was skipped. I realized there was a remanent \n in the buffer (by the line feed in the cantidad_frases selection). So i added the getchar() after the scanf to clean that up. Is there any elegant way to do it? EDIT: other than using another input function.
Last edited by neithan; Oct 29th, 2009 at 8:46 pm.
Reputation Points: 12
Solved Threads: 2
Junior Poster in Training
neithan is offline Offline
75 posts
since Oct 2009
Oct 30th, 2009
1
Re: Array of pointers to char...messed up!
Quote ...
Any comments / corrections?
In the C89 standard, an array must be set with a constant. Which would not allowed what you just did.
  1. int cantidad_frases = 0;
  2. printf("Cuantas frases quieres escribir?: ");
  3. scanf("%d", &cantidad_frases);
  4. getchar();
  5. char *frases[cantidad_frases]; /* This is not allowed in C89 */
Furthermore, there can not be mixing of variable declarations and code. All variable must be declared first in the block. Making char *frases[cantid_frases]; incorrect as well.
If you want dynamically allocated multidimensional arrays you may take a look at pointer to pointer. Example

C89 doesn't accept declaration of variable in the for loop construct.
for(unsigned i = 0; i < cantidad_frases; i++)
Variable i must be declared outside the ().

When you ask for user input, the control of the program is handled to the user. They can enter an integer (in which case an enter key has been added to the stream), they can enter a float, a char or any combination and length of those. Moreover they might just press enter or be generous with blank sequence.
Can scanf() handle that kind of conditions? The answer is no. The elegant option then is to think how would you deal with the input and design your program to accommodate for those possibilities. There's not "silver-bullet function" that will do that for you.
Aia
Reputation Points: 2224
Solved Threads: 218
Nearly a Posting Maven
Aia is offline Offline
2,304 posts
since Dec 2006
Oct 30th, 2009
0
Re: Array of pointers to char...messed up!
Click to Expand / Collapse  Quote originally posted by Aia ...
In the C89 standard, an array must be set with a constant. Which would not allowed what you just did.
Furthermore, there can not be mixing of variable declarations and code. All variable must be declared first in the block. Making char *frases[cantid_frases]; incorrect as well.
Ok but, i'm sorry if this sound ignorant which probably will, isn't C89 too old? I look it up and this C99 thing works with those issues, right? Why still thinking of C89? (remember i'm a beginner)


Click to Expand / Collapse  Quote originally posted by Aia ...
If you want dynamically allocated multidimensional arrays you may take a look at pointer to pointer. Example
I'm going to check that url and see what i can learn.

Click to Expand / Collapse  Quote originally posted by Aia ...
When you ask for user input, the control of the program is handled to the user. They can enter an integer (in which case an enter key has been added to the stream), they can enter a float, a char or any combination and length of those. Moreover they might just press enter or be generous with blank sequence.
Can scanf() handle that kind of conditions? The answer is no. The elegant option then is to think how would you deal with the input and design your program to accommodate for those possibilities. There's not "silver-bullet function" that will do that for you.
That is true...i'll see if i can improve that.

Thank you.
Reputation Points: 12
Solved Threads: 2
Junior Poster in Training
neithan is offline Offline
75 posts
since Oct 2009

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: C program for 2D arrays
Next Thread in C Forum Timeline: File modification time as an int





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC