|
|
|
#1 (permalink) |
|
New to Overclock.net
|
I have the following code and I am not sure that its working right. I am using C. The final result is that the program is suppose to give me the length of each string that is entered that is the second for loop. I do not think this part is working right. I have gone from having no code to what is below on my own I just need a little help making sure that this is correct. Any assistance would be greatly appreciated.
Below are the instructions that I am having problems with. Each time the name is read I then have to measure the length and allocate a dynamical string large enough to hold a copy of it. You will then copy the contents of buffer into this newly allocated string and add its address to the array names. Once you are done filling the array names, each of its element should contain the address of a dynamically allocated copy of each word entered by the user. You will iterate over names and display these strings with a message.Once done, you will deallocate the memory you allocated I am getting closer. The code now gives me a value of 2 for any input I put in it doesn't matter the length of word. Code:
#include <stdio.h>
#include <string.h>
int str_length(char* names);
void copy(char *buffer, const char *names);
int main(void)
{
int n = 0;
char names[n];
int i = 0;
char buffer[256];
printf("How many names to store: ");
scanf("%d", &n);
for( i = 0; i < n; i++)
{
printf("names[%d] = ", i);
scanf("%s", buffer);
copy(buffer, names);
}
for( i = 0; i < n; i++)
{
printf("buffer[%d] = %s %d\n", i, buffer, str_length);
}
system("PAUSE");
return 0;
}
int str_length(char* names)
{
char* start = names;
while ( *names++);
return names-start;
}
void copy(char *buffer, const char *names)
{
for ( ; ( *buffer = *names ) != '\0'; buffer++, names++ ) ;
}
Last edited by loonyt7 : 2 Weeks Ago at 09:36 PM |
|
|
|
|
|
#2 (permalink) |
|
New to Overclock.net
|
I made a minor change to this code. I know I am getting closer I wish someone could help me with this.
|
|
|
|
|
|
#3 (permalink) |
|
Case Modder
![]() |
For starters, what is your "source" and "destination" parameters of your copy() method? And are you sure you're passing the correct variables for the source and destination to the copy() method?
__________________
Rich Custom Wooden Case Builder
|
|
|
|
|
|
#4 (permalink) |
|
New to Overclock.net
|
I was able to get the code to work finally thanks though
|
|
|
|
|
|
#5 (permalink) | ||||||||||||||
|
Security Sleuth
![]() |
What the eff is that mess?
Just use strlen(), and if you wish to write your own function then just loop on the input buff until a null is found. while(buff[i]) { i++ }; for example.
__________________
Quote:
Proud Member of the Linux Gaming CommunityI am your friend.
|
||||||||||||||
|
|
|
![]() |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
|
|