473,662 Members | 2,595 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to access higher char array element?

Hi!,
im trying to copy the middle part of a dinamycally created char* string
with memcopy but all i get is rubbish...
I understand, that malloc can allocate memory wherever it wants and it
does not have to be in one piece... but how do i access higher parts of
the allocated memory?

lets say source contains "helloworld " and i only want to have "llowo"
in destination... what do i do?

char* destination=mal loc(5);
char* source=malloc(8 );
[.....]

memcpy(destinat ion, source +3 ,5);

this line copies whatever.... and writing source[3] does not work
either... a hint would be nice... :D
thanks for any help!

Sep 12 '06 #1
5 2347
mw****@freenet. de said:
Hi!,
im trying to copy the middle part of a dinamycally created char* string
with memcopy but all i get is rubbish...
I'm not familiar with memcopy. Do you mean memcpy?
I understand, that malloc can allocate memory wherever it wants and it
does not have to be in one piece...
You understand wrongly. Each call to the malloc function yields either a
null pointer (in the case of failure) or a pointer to a contiguous region
of memory of at least the size requested.
lets say source contains "helloworld " and i only want to have "llowo"
in destination... what do i do?

char* destination=mal loc(5);
char* source=malloc(8 );
The region pointed to by source does not have sufficient storage to store
the string "helloworld ". It would require 11 bytes, not 8.
[.....]

memcpy(destinat ion, source +3 ,5);

this line copies whatever.... and writing source[3] does not work
either... a hint would be nice... :D
It is probable that you are forgetting about the importance of a null
terminator, but we can't tell from what you've shown so far. Post the
smallest *complete* C program that demonstrates the difficulty you are
having, and I have little doubt that we will be able to point out the
problem.
--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Sep 12 '06 #2

mwe...@freenet. de wrote:
Hi!,
im trying to copy the middle part of a dinamycally created char* string
with memcopy but all i get is rubbish...
I understand, that malloc can allocate memory wherever it wants and it
does not have to be in one piece... but how do i access higher parts of
the allocated memory?

lets say source contains "helloworld " and i only want to have "llowo"
in destination... what do i do?

char* destination=mal loc(5);
char* source=malloc(8 );
[.....]

memcpy(destinat ion, source +3 ,5);

this line copies whatever.... and writing source[3] does not work
either... a hint would be nice... :D
thanks for any help!
Perhaps I am misunderstandin g your intentions here, but why something
like:

char *destination = (char *)malloc(6), *source =
strdup("hellowo rld");
memcpy(destinat ion, source + 2, 5);
destination[5] = '\0';

won't work for you?
Perhaps you need to consider the following:
o you need to allocate length + 1, because the string is null
terminated
o offsets base is 0, not 1. Thus you should memcpy() from source + 2
o you need to set the '\0' on the destination ( null character
terminator ).

Mark Papadakis

Sep 12 '06 #3
mw****@freenet. de wrote:
Hi!,
im trying to copy the middle part of a dinamycally created char* string
with memcopy but all i get is rubbish...
I understand, that malloc can allocate memory wherever it wants and it
does not have to be in one piece... but how do i access higher parts of
the allocated memory?

lets say source contains "helloworld " and i only want to have "llowo"
in destination... what do i do?

char* destination=mal loc(5);
Obviously wrong. There are 6 chars in "llowo".
char* source=malloc(8 );
Obviously wrong. There are 11 chars in "helloworld ".
[.....]

memcpy(destinat ion, source +3 ,5);
Obviously wrong. The chars {'l','l','o','w ','o'} begin at source+2.
>
this line copies whatever.... and writing source[3] does not work
either... a hint would be nice... :D
"Does not work" doesn't work as a description. Below you will see a
demonstration that everything you claim "does not work" does work when
done correctly.
Are you perhaps trying to use the non-string array
{'l','l','o','w ','o'} as if it were a string?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
char source[] = "helloworld ";
char *dest;
size_t i;

printf("Copying the 5 chars from \"%s\"[2]\n", source);
if (!(dest = malloc(5))) {
printf("malloc failed.\n");
exit(EXIT_FAILU RE);
}
memcpy(dest, source + 2, 5);
for (i = 0; i < 5; i++)
printf("%u %#3o %c\n", (unsigned) i, (unsigned) dest[i],
dest[i]);
putchar('\n');
free(dest);

printf("Creatin g a string using the 5 chars from \"%s\"[2]\n",
source);
if (!(dest = malloc(6))) {
printf("malloc failed.\n");
exit(EXIT_FAILU RE);
}
memcpy(dest, source + 2, 5);
dest[5] = 0;
for (i = 0; i < 6; i++) {
if (dest[i])
printf("%u %#3o %c\n", (unsigned) i, (unsigned) dest[i],
dest[i]);
else
printf("%u %#3o %s\n", (unsigned) i, (unsigned) dest[i],
"(zero byte)");
}
printf("The created string: \"%s\"\n", dest);
free(dest);

return 0;
}
Copying the 5 chars from "helloworld "[2]
0 0154 l
1 0154 l
2 0157 o
3 0167 w
4 0157 o

Creating a string using the 5 chars from "helloworld "[2]
0 0154 l
1 0154 l
2 0157 o
3 0167 w
4 0157 o
5 0 (zero byte)
The created string: "llowo"
Sep 12 '06 #4
markpapadakis wrote:
Perhaps I am misunderstandin g your intentions here, but why something
like:

char *destination = (char *)malloc(6), *source =
strdup("hellowo rld");
If his intention is to write standard C, then there is a good reason not
to use the above: strdup does not exist in C and if it ever does there
is no guarantee that the standard strdup will behave like yours.
Sep 12 '06 #5

Martin Ambuhl schrieb:
[a nice example]
Thanks to all who answered...
indeed the error came from me missallocating the space and trying to
read from non allocated memory! i also didnt take into account the last
0...

indeed im writing in c in windows.
I actually do c++ and had to do this one thing for compatibiltys sake
with a programm im using.

thanks again to all!!

Sep 12 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

35
20940
by: Ying Yang | last post by:
Hi, whats the difference between: char* a = new char; char* b = new char; char c ;
21
18857
by: Bret | last post by:
I'm curious why char** argv is acceptable in the main() declaration. In the comp.lang.c FAQ (question 6.18) it says that pointers to pointers and pointers to an array are not interchangable. However the declaration: int main(int argc, char** argv) is common.
5
3962
by: jab3 | last post by:
(again :)) Hello everyone. I'll ask this even at risk of being accused of not researching adequately. My question (before longer reasoning) is: How does declaring (or defining, whatever) a variable **var make it an array of pointers? I realize that 'char **var' is a pointer to a pointer of type char (I hope). And I realize that with var, var is actually a memory address (or at
2
2042
by: Amrit Kohli | last post by:
Hello. I have the following code, to do a simple operation by copying the elements of a vector of strings into an array of char pointers. However, when I run this code, the first element in the char array strarr holds garbage characters. For some reason, every time the strcpy function is called to copy the string in temp to the array, it fills the 0th element in the strarr array with garbage characters. Can someone try to compile this...
9
2190
by: gk245 | last post by:
I have something like this: struct block { int x; int y; float z; }
2
7653
by: Michael | last post by:
Hi, How to understand the difference between the following three. My understanding is the number in bracket minus one is the max number of chars to store in the char array , right? Thanks in advance.
4
7064
by: =?Utf-8?B?cm9nZXJfMjc=?= | last post by:
hey, I have a method that takes a char array of 10. I have a char array of 30. how do I make it send the first 10, then the next 10, then the final 10 ? I need help with my looping skills. thanks. I have this, but I get the index was out of bounds.... char char1 =
21
2741
by: arnuld | last post by:
int main() { const char* arr = {"bjarne", "stroustrup", "c++"}; char* parr = &arr; } this gives an error: $ g++ test.cpp test.cpp: In function 'int main()': test.cpp:4: error: cannot convert 'const char* (*)' to 'char*' in
10
1760
by: =?Utf-8?B?R2Vvcmdl?= | last post by:
Hello everyone, There is error message when executing my program, Unhandled exception at 0x00411a49 in test_entern.exe: 0xC0000005: Access violation reading location 0x00000002. It is very simple, does anyone know what is wrong with the program?
0
8432
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8344
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8857
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8764
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6186
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5654
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4180
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4347
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2762
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.