Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hello,
Does anybody like to help me in the following problems ? How to declare a variable of string using pointer, instead of array.
eg. char *s++;
this will declare a variable of type pointer to char. But how to declare a pointer to string, so that I can use *str++In pascal (and delphi i think) I can write:
var str : string;
str = "C String - confusing";
But how to do this in C. The string is not entered from kb, and the following doesn't work:
char str[100];
str ="C String - confusing";Any help would be thanksful

C does not have strings, only arrays of characters.
There are a number of library functions to manipulate, compare, etc... these arrays.
They are prototyped in .
For example the following willl work:
char str[100];
strcpy(str,"A dumb string");If you need more familiar string processing capabilities, then try C++, Java, or almost anything but C.
Regards, Guy

You can also you the C standard library functions malloc and free likechar *d_ptr;
char *s_str = "This is just an arbitrary string";d_ptr = malloc(strlen(s_str));
strcpy(d_ptr, s_str);
puts(d_ptr);
/* Should write out familiar contents */
free(d_ptr); /* to free memory and lose string reference though d_ptr */malloc and free are part of the C standard library. The strcpy procedure is in string.h, and should be included the way you would stdlib.h and stdio.h.
If you machine uses other than 1-byte chars (IBM PCs _DO_ use byte-sized chars), you'll have to weight the argument to malloc, or use calloc instead to specify the width of the character you want. Read about these functions in your compiler documentation. If it didn't come with printed docs (many compilers nowadays won't) check any book on C or online help. If you plan on doing any string manipulation with programs written in C, get to know these functions.

My fault. Third line in last reply should've been written: d_ptr = malloc(strlen(s_str) + 1);
,ensuring that extra space is granted for the ASCII null byte for end-of-string signal.

The Response 2 is idiot.It doesnt use malloc().At eesponses 3,4 is missing (char*) before malloc. str=(char *)malloc() because malloc returns void *

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |