Thread: string pointers

  1. #1
    Registered User
    Join Date
    May 2004

    string pointers

    I have the following code
    #include <stdio.h>
    #include <conio.h>
    int main(void)
    	char *ptrchar1;
    	char first_line[10];
    	printf("What is the keyword?");
    	while( scanf("%c",ptrchar1)==1) 
    		printf("\n\nThe first word is %s",&first_line);
    	return 0;
    is there a way i can get away without allocating 10 chars in the statement
    char first_line[10];

    i mean what if i had a keyword of 12 chars which i would want to fit in, then what?

  2. #2
    Registered User penney's Avatar
    Join Date
    Jan 2003
    1st off I don't believe you are doing what you intend to be doing with your code. An array' name by itself is a pointer to the first location of the array. Therfore just do this:

    ptrchar1 = first_line;

    also change your printf to:
    printf("\n\nThe first word is %s",first_line);

    Your statements was performing an address of an address which you did not allocate.

    Now to answer your question: Yes you can just allocate the exact number of characters that you want instead of pre-allocating a set amount. To do this you use the malloc command to dynamically allocate memory as the program is running. Therefore, while the program runs you must know what size to allocate on the fly. Hope this helps.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. char Handling, probably typical newbie stuff
    By Neolyth in forum C Programming
    Replies: 16
    Last Post: 06-21-2009, 04:05 AM
  2. String Pointers
    By mbuster in forum C Programming
    Replies: 3
    Last Post: 05-28-2008, 09:39 AM
  3. Compile Error that i dont understand
    By bobthebullet990 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 09:19 AM
  4. problems with overloaded '+' again
    By Brain Cell in forum C++ Programming
    Replies: 9
    Last Post: 04-14-2005, 05:13 PM
  5. string pointers
    By David Korb in forum C++ Programming
    Replies: 3
    Last Post: 12-15-2001, 01:07 AM