GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 07-Jul-2006, 02:46
aijazbaig1's Avatar
aijazbaig1 aijazbaig1 is offline
Member
 
Join Date: May 2006
Location: India
Posts: 156
aijazbaig1 has a spectacular aura aboutaijazbaig1 has a spectacular aura about
Question

getting string size at run time


Huy.
I am trying to write a simple program to get the size of two strings at run time. I mean I let the user enter the strings and then I wanna use the sizeof operator to compare the sizes of the two strings.

Heres my code:

CPP / C++ / C Code:
#include <stdio.h>

int main()
{
	char string1[],string2[];
	size_t size1,size2;
	printf("enter string1\n");
	gets(string1);
	printf("enter string2\n");
	gets(string2);
	size1 = sizeof(string1);
	size2 = sizeof(string2);
	printf("the size of string1 is %d\n",size1);
	printf("the size of string2 is %d\n",size2);
	return 0;
}

and it gives me the following errors:

Compiling...
strng_copy.c
D:\VC++\chap7_pointers\str_copy\strng_copy.c(5) : error C2133: 'string1' : unknown size
D:\VC++\chap7_pointers\str_copy\strng_copy.c(5) : error C2133: 'string2' : unknown size
D:\VC++\chap7_pointers\str_copy\strng_copy.c(11) : warning C4034: sizeof returns 0
D:\VC++\chap7_pointers\str_copy\strng_copy.c(12) : warning C4034: sizeof returns 0
Error executing cl.exe.

strng_copy.obj - 2 error(s), 2 warning(s)

How does one go about telling the compiler that the size(s) would be known only at run time and not at compile time?

Is there any other way to go about it?

Hoping to hear from you guys

Best Regards,
Aijaz Baig.
Last edited by cable_guy_67 : 07-Jul-2006 at 02:58. Reason: Please surround your C code with [c] ... [/c] codetags
  #2  
Old 07-Jul-2006, 04:11
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,373
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all

Re: getting string size at run time


Quote:
Originally Posted by aijazbaig1
Huy.
I am trying to write a simple program to get the size of two strings at run time. I mean I let the user enter the strings and then I wanna use the sizeof operator to compare the sizes of the two strings.
You can't use sizeof() to get the length of a string. You need strlen()

You may want to read this, too.

As someone brand new to the forum, maybe you can help us. We have a post with RED background and YELLOW text that new people seem to not see or understand. Is there something we can change that would indicate to someone new that the information should be read before posting a question?

The reason I ask is that the moderators have requested 4 times that to use code tags, and the Guidelines explain how. You obviously haven't read them yet...
__________________

The 3 Laws of the Procrastination Society:
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
  #3  
Old 07-Jul-2006, 09:22
aijazbaig1's Avatar
aijazbaig1 aijazbaig1 is offline
Member
 
Join Date: May 2006
Location: India
Posts: 156
aijazbaig1 has a spectacular aura aboutaijazbaig1 has a spectacular aura about
Question

Re: getting string size at run time


Hi.
Thnks for showing me the link that proved to be immensely helpful. Additionally I clearly don't understand what you wrote after that. I mean how does that pertain to my post? Are u asking me for my opinion on that ?

Or is it that you want me to format the way I enter my messages so as to make them more readable for others.

By the way where is the post with the red background and yellow text? Kindly elaborate as I am currently very confused about what u meant

Best Regards,
Aijaz Baig.
  #4  
Old 07-Jul-2006, 12:13
fhj52 fhj52 is offline
New Member
 
Join Date: Jul 2006
Posts: 13
fhj52 is on a distinguished road

Re: getting string size at run time


@aijazbaig1
YELLOW text w/ RED background is the post title @ top of the list:
http://www.gidforums.com/f-41.html

@WaltP
Since you asked, as one also a new member here, I suggest adding "BEFORE POSTING," in front of the "Read This" .

The "Read This >>> Guidelines for posting requests for help -"
could be:
"BEFORE POSTING, Please Read This Post! "

The additional info "Guidelines ...blah.", as helpful as it might be to some, will actually cause others NOT to read it. Some people think they already know the rules so will ignore it.
(ithink the red&yellow colors & bold are good but I cannot repo that here...)

Also, in the Guidelines text body, perhaps a short example(shorter than this!) of what the tagindicator is and why it is might help.
E.g.
one with the tagindicator:
[postStart]
What's the error in this code:
Code:
CPP / C++ / C Code:
/*
 * private-queue-hello-world.c  - a "hello world" example in which a single
 *                                process creates a message queue and sends
 *                                itself a "hello world" message via this queue.
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

int main(int argc, char* argv[])
{
    /* create a private message queue, with access only to the owner. */
    int queue_id = msgget(IPC_PRIVATE, 0600);
    struct msgbuf* msg;
    struct msgbuf* recv_msg;
    int rc;

    if (queue_id == -1) {
	perror("main: msgget");
	exit(1);
    }
    printf("message queue created, queue id '%d'.\n", queue_id);
    msg = (struct msgbuf*)malloc(sizeof(struct msgbuf)+strlen("hello world"));
    msg->mtype = 1;
    strcpy(msg->mtext, "hello world");
    rc = msgsnd(queue_id, msg, strlen(msg->mtext)+1, 0);
    if (rc == -1) {
	perror("main: msgsnd");
	exit(1);
    }
    free(msg);
    printf("message placed on the queue successfully.\n");
    recv_msg = (struct msgbuf*)malloc(sizeof(struct msgbuf)+strlen("hello world"));
    rc = msgrcv(queue_id, recv_msg, strlen("hello world")+1, 0, 0);
    if (rc == -1) {
	perror("main: msgrcv");
	exit(1);
    }

    printf("msgrcv: received message: mtype '%d'; mtext '%s'\n",
	   recv_msg->mtype, recv_msg->mtext);
    
    return 0;
}
[postEND]
versus one without the tagindicator
[postStart]
What's the error in this code:
Code:
/* * private-queue-hello-world.c - a "hello world" example in which a single * process creates a message queue and sends * itself a "hello world" message via this queue. */ #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> int main(int argc, char* argv[]) { /* create a private message queue, with access only to the owner. */ int queue_id = msgget(IPC_PRIVATE, 0600); struct msgbuf* msg; struct msgbuf* recv_msg; int rc; if (queue_id == -1) { perror("main: msgget"); exit(1); } printf("message queue created, queue id '%d'.\n", queue_id); msg = (struct msgbuf*)malloc(sizeof(struct msgbuf)+strlen("hello world")); msg->mtype = 1; strcpy(msg->mtext, "hello world"); rc = msgsnd(queue_id, msg, strlen(msg->mtext)+1, 0); if (rc == -1) { perror("main: msgsnd"); exit(1); } free(msg); printf("message placed on the queue successfully.\n"); recv_msg = (struct msgbuf*)malloc(sizeof(struct msgbuf)+strlen("hello world")); rc = msgrcv(queue_id, recv_msg, strlen("hello world")+1, 0, 0); if (rc == -1) { perror("main: msgrcv"); exit(1); } printf("msgrcv: received message: mtype '%d'; mtext '%s'\n", recv_msg->mtype, recv_msg->mtext); return 0; }
[postEND]

versus one with only the tagindicator
[postStart]
What's the error in this code:
CPP / C++ / C Code:
/*
 * private-queue-hello-world.c  - a "hello world" example in which a single
 *                                process creates a message queue and sends
 *                                itself a "hello world" message via this queue.
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

int main(int argc, char* argv[])
{
    /* create a private message queue, with access only to the owner. */
    int queue_id = msgget(IPC_PRIVATE, 0600);
    struct msgbuf* msg;
    struct msgbuf* recv_msg;
    int rc;

    if (queue_id == -1) {
	perror("main: msgget");
	exit(1);
    }
    printf("message queue created, queue id '%d'.\n", queue_id);
    msg = (struct msgbuf*)malloc(sizeof(struct msgbuf)+strlen("hello world"));
    msg->mtype = 1;
    strcpy(msg->mtext, "hello world");
    rc = msgsnd(queue_id, msg, strlen(msg->mtext)+1, 0);
    if (rc == -1) {
	perror("main: msgsnd");
	exit(1);
    }
    free(msg);
    printf("message placed on the queue successfully.\n");
    recv_msg = (struct msgbuf*)malloc(sizeof(struct msgbuf)+strlen("hello world"));
    rc = msgrcv(queue_id, recv_msg, strlen("hello world")+1, 0, 0);
    if (rc == -1) {
	perror("main: msgrcv");
	exit(1);
    }

    printf("msgrcv: received message: mtype '%d'; mtext '%s'\n",
	   recv_msg->mtype, recv_msg->mtext);
    
    return 0;
}
[postEND]

OF COURSE you will want to use a shorter example. That just happened to be some that I was looking at recently...

The KEY part seems to be that you need to state:
"REPLACE the "CODE" word in the code block tag with the appropriate language tag: C/C++/CPP, JAVA, CSS, etc... "
Because that is what you really want, correct?

Part " 1.A.d. " lists the code types but apparently c, c++, and cpp are all the same so the statement " using c, c++ or cpp are all the same " might be worthwhile.
Also, that seems to be missing XML and related... Is there no parser for XML and associated types? What about PERL or other languages(BASH, etc...)?
IOW, the list of language types should mention those that are not supported and what the poster should do when posting one of those other types of code.

And, PHP and HTML already have code tags to be used so that info, in part 1.A.d., is not needed, right? That makes it confusing: ' does one do what Walt needs or use the built-in tags? ' If you do want people to use the built-in tags, then say such; if not then state that too.

As you might know, people tend to take the shortest route possible which means putting an extra, non-clickable tag requires effort and forethought. Some might forget the tagindicator too since preoccupation with the problem is quite likely.
So, perhaps modify the bar to add that to the "tagindicator" code block as part/one of the clickable elements. The HTML and PHP widgets are there so C, C++, XML, etc... could be there too. A drop-down selection box would be nice...

I'm sure part of the problem is that people figure '' I am posting in the "X" subforum so the code is, of course, "X" '' and they also generally mention that in the text description so they might feel it is redundant info and not understand that it is required to be able to use this forum.

In general, instructions have to be very, very simple and to the point. When learning something new, most everyone is just like a young child.

I don't have a problem with using apropos tags ... just hope I don't forget.

c-ya


PS: There really is an error in that code according to the ch interpreter...
  #5  
Old 08-Jul-2006, 21:54
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,373
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all

Re: getting string size at run time


Quote:
Originally Posted by fhj52
@WaltP
Since you asked, as one also a new member here, I suggest adding "BEFORE POSTING," in front of the "Read This" .

Response has been moved to Misc Programming. Thanks, fhj52
__________________

The 3 Laws of the Procrastination Society:
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
  #6  
Old 09-Jul-2006, 03:47
aijazbaig1's Avatar
aijazbaig1 aijazbaig1 is offline
Member
 
Join Date: May 2006
Location: India
Posts: 156
aijazbaig1 has a spectacular aura aboutaijazbaig1 has a spectacular aura about
Exclamation

Re: getting string size at run time


Hello..
I have come up with the following code which uses a char pointer to allocate memory at run time on the heap.
It then uses these allocated memory locations to store the characters sequentially.

CPP / C++ / C Code:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

int main()
{
	char *string1;
	int chr_cntr=0,crrnt_chr;
	printf("enter string1\n");
	string1 = (char *) malloc (500);
	do
	{
		*(string1+chr_cntr) = getchar();
		chr_cntr++;
	}
	while (string1[chr_cntr-1] != '\r'&& string1[chr_cntr-1] != '\n');
	string1[chr_cntr] = '\0';
	printf("\nstring1 has %d characters\n",chr_cntr-1);
	printf("string  = %s\n",string1);
	return 0;
}

Is there an even more efficient way in which we can allocate memory for each single character each time before reading a character at that location?

And even if we manage to do that..won't it make the program more slower as we have to call the malloc function every time for each single character?
What do you people think would be a clever thing to do..allocate space for 500 characters at once or allocate space for 1 char at a time but use as many calls to malloc as there are characters to be stored??
And I hope this time I have used the proper tag indicators
Best regards,
Aijaz.
  #7  
Old 09-Jul-2006, 04:21
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,373
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all

Re: getting string size at run time


Why are you making this so complicated?

Define a char* buffer of 500
Input using fgets() as described in the link I posted.
And you never free()ed the buffer you malloc()ed -- a no-no.
__________________

The 3 Laws of the Procrastination Society:
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
  #8  
Old 09-Jul-2006, 09:34
aijazbaig1's Avatar
aijazbaig1 aijazbaig1 is offline
Member
 
Join Date: May 2006
Location: India
Posts: 156
aijazbaig1 has a spectacular aura aboutaijazbaig1 has a spectacular aura about

Re: getting string size at run time


Hi.

Well, as said by walt, i tried the following code which uses fgets and it did work. And by defining a char * buffer of 500, did u mean allocate space for 500 characters using malloc?

Nevertheless, heres my code and it does work

CPP / C++ / C Code:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
	char *string1;
	printf("enter string1\n");
	string1 = (char *) malloc (500);
	fgets(string1,500,stdin);
	if (string1[strlen(string1)-1] == '\n') string1[strlen(string1)-1] = '\0';
	printf("\nstring1 has %d characters\n",strlen(string1));
	printf("string  = %s\n",string1);
	free(string1);
	return 0;
}

I hope I got it correct on everything..however if you think it could be further improvised, then let me know..my ears are always open to advices on making further improvisations
  #9  
Old 09-Jul-2006, 12:36
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,373
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all

Re: getting string size at run time


Quote:
Originally Posted by aijazbaig1
Hi.

Well, as said by walt, i tried the following code which uses fgets and it did work. And by defining a char * buffer of 500, did u mean allocate space for 500 characters using malloc?
No.
Define a buffer: char buf[500];
not
Allocate a buffer: malloc (500);
There is no reason to allocate anything. People use allocation way too much -- simply because they can is not a good reason.

Quote:
Originally Posted by aijazbaig1
Nevertheless, heres my code and it does work
CPP / C++ / C Code:
snipped
I hope I got it correct on everything..however if you think it could be further improvised, then let me know..my ears are always open to advices on making further improvisations
Looks better, except the malloc() line is in fact incorrect, but C is forgiving. When you take that out, it'll be almost perfect...

And to be nit-picky -- improved is the word, not improvised -- coding should rarely, if ever, be improvised... ;-)
__________________

The 3 Laws of the Procrastination Society:
1) Never do today that which can be put off until tomorrow
2) Tomorrow never comes
  #10  
Old 11-Jul-2006, 09:19
aijazbaig1's Avatar
aijazbaig1 aijazbaig1 is offline
Member
 
Join Date: May 2006
Location: India
Posts: 156
aijazbaig1 has a spectacular aura aboutaijazbaig1 has a spectacular aura about
Cool

Re: getting string size at run time


Hello.

@waltP

Quote:
Looks better, except the malloc() line is in fact incorrect, but C is forgiving. When you take that out, it'll be almost perfect...

What did u mean by the sentence above. Did u mean my usage of malloc was inappropriate as in my syntax wasn't exactly what malloc expects? Or did u mean I should remove the malloc and instead define a buffer explicitly?

I hope that u meant the latter...

and yeah, my english won't ever be like yours ..doesn't this explain my existence here in the old world when I should have crossed the atlantic way back..

Best Regards,
Aijaz Baig.
 
 

Recent GIDBlogInstall Adobe Flash - Without Administrator Rights by LocalTech

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
String pad. pjpav Java Forum 6 13-Nov-2005 12:10
Help wit my source code compiler errors Krandygrl00 C++ Forum 1 06-Jun-2005 08:14
runtime, compile time... kai85 C Programming Language 2 19-May-2005 22:05
Having a problem Chuckles Computer Hardware Forum 19 13-Sep-2004 12:17
Display Size and maybe download time BobbyDouglas MySQL / PHP Forum 5 08-Nov-2003 00:18

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 09:41.


vBulletin, Copyright © 2000 - 2010, Jelsoft Enterprises Ltd.