• 0

[c] reading a string on second letter


Question

Hi. I wanted to know how I could start off a string from the second letter. An example would be better:

eg.

char mybuf[100];

mybuf = "Hi.";

I want it so it is:

mybuf = "i."

So basically I am starting off at the 2nd spot. Thanks!

Also i want to add that i know how to do it when it is

char * mybuf;

but is it possible to do it with

char mybuf[100]?

Link to comment
https://www.neowin.net/forum/topic/229717-c-reading-a-string-on-second-letter/
Share on other sites

6 answers to this question

Recommended Posts

  • 0

Do it the exact same way you would with a char*: use "myBuf+1".

A char[] is the exact same thing a char*, except that with a char* u need to allocate and de-allocate memory yourself; both are pointers...

btw kjordan2001: no need to use a strncpy... a strcpy would work just fine since it would copy until the eos char (\0)...

strcpy(dest,myBuf+1);

strcpy(dest,&mybuf[1]);

  • 0
  Mouton said:
no need to use a strncpy... a strcpy would work just fine since it would copy until the eos char (\0)...

strcpy(dest,myBuf+1);

strcpy(dest,&mybuf[1]);

584723600[/snapback]

But that might be a buffer overflow. You don't know if the string fits into the buffer. If it is filled to the last byte, your strcpy would overflow the buffer by one. If you think that doesn't matter - remember how every other critical security hole involves unchecked buffers?

At the same time...

  kjordan2001 said:
strncpy(dest,&mybuf[1],strlen(mybuf)-2);

or

strncpy(dest,mybuf+1,strlen(mybuf)-2);

584723180[/snapback]

Those are subtly broken as well, with at least two bugs. They are probably just oversights: Using strlen(myBuf)-2 here doesn't make sense. Consider what happens if there are 99 non-null characters plus the '\0' at the end in myBuf. strlen() returns 99. You pass 97 as the buffer size to strncpy. It will thus truncate the string.

And it will reveal the second bug: strncpy is not guaranteed to zero-terminate the buffer. If there is not enough room for the original string in the destination buffer, the last character in the destination buffer will be the last from the source buffer that could be copied, rather than '\0'. Thus people usually do the following as a workaround:

strncpy(target, source, sizeof(target));
target[sizeof(target)-1] = '\0';

You can imagine how easy it is to forget that of course... Thus some people instead ensure that the buffer is filled with zeros to begin with....

char target[100] = { 0 };

...and then use

strncpy(target, source, sizeof(target)-1);

So strncpy never touches the very last (zero) byte. That's most likely what you had in mind.

You probably meant to use sizeof() instead of strlen() as well. Hence my gut feel that it's just an oversight.

I'm not sure if strncpy's behavior is defined if source and target overlap anyway. Though I've seen and used this so many times that it apparently works at least with popular compilers/library implementations.

  • 0
  ilmcuts said:
But that might be a buffer overflow. You don't know if the string fits into the buffer. If it is filled to the last byte, your strcpy would overflow the buffer by one. If you think that doesn't matter - remember how every other critical security hole involves unchecked buffers?

I know it won't overflow because I defined the char arrays myself with the appropriate sizes.

No way u can buffer overflow if dest and myBuf are of the same size. And I wouldn't see why you would not make them the same size. Especially since he's using char arrays, and not pointers + mem allocation...

I think choosing the size of your arrays correctly is much easier to deal with than using strncpy then having to think/check for the \0...

  • 0
  Quote
So strncpy never touches the very last (zero) byte. That's most likely what you had in mind.

You probably meant to use sizeof() instead of strlen() as well. Hence my gut feel that it's just an oversight.

Yeah, I meant sizeof. However, I was right on the -2 part, since he's excluding the first letter.
  Quote
btw kjordan2001: no need to use a strncpy... a strcpy would work just fine since it would copy until the eos char (\0)...

Yeah, that would work too, guess I always go the long hard way :wacko:

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Google Sheets gets exciting Gemini feature that is still missing in Excel by Usama Jawad We recently learned that Copilot in Microsoft Excel got a big upgrade in the form of context awareness, which is in addition to the formula generation capabilities that were made available earlier. However, no firm has really won the AI race yet, and Google has now edged ahead in at least one domain today, by adding Gemini text generation capabilities in Google Sheets. In a blog post, Google has announced that while you can already leverage Gemini in Sheets to generate charts and insights, you can now generate text using its new AI function too. This function can utilize a natural language prompt and an optional context window to summarize and generate text, categorize information, and perform sentiment analysis. The syntax for the AI function is fairly straightforward: AI("prompt",[optional range]) So you can invoke the Gemini function as follows: =AI("Perform sentiment analysis on the emails sent by the customers to the barbershop.", C2) Or: =AI("Create an email to the reviewer addressing specific items in their reviews.", A2:G2) It is very interesting to note that a similar capability is not offered by Copilot in Excel yet. In my testing, I did get Copilot to generate charts, formulas, and do some text formatting, it simply doesn't seem to have the ability to actually generate textual data directly in a workbook just yet. While an input range isn't mandatory, Google recommends using it for the best results. Just like any cell using a formula, you can refresh the AI cell, and get an indicator about its sync state. That said, a limitation that is present with regards to the AI function is that it only works for the first 200 selected cells in your range. Once that generation completes, you can select more cells and repeat the process, which is a slightly cumbersome experience. The rollout for this capability has begun across Business, Enterprise, Education, Education Premium, AI Pro, and Ultra plans, so it should be available to everyone sooner rather than later. In the meantime, you can view details about the AI function here.
    • Space Marine 2 gains a horde mode and DLSS 4 with new Siege update by Pulasthi Ariyasinghe Warhammer 40,000: Space Marine 2 just received its next major update. Dubbed the Siege update, it is finally bringing the long-promised horde mode for the third-person action game, as well as new tech for PC gamers. The Siege mode takes place on a fortified Imperial stronghold on Kadaku that is enduring endless attacks by Tyranids and Thousand Sons. There are three sections in total that players will defend in order before circling back to the original position, fighting away thousands of enemies in five waves before swapping locations. To give players a small break, there's a one-minute gap between each wave to resupply and purchase perks from the points they collect while in battle. Players can call in AI-controlled specialized soldiers, Space Marines, or even a Dreadnought to help out if the waves get a little too tough. To cap it all off, every fifth wave a boss encounter kicks off. There are 15 waves to go through in a single session, but parties can also kick off an endless mode at the end of these to see how far they can get. "Siege Mode expands on our PVE operations, emphasizing endless enemy waves that challenge even the strongest teams," says Focus Entertainment, describing the new mode. "When overwhelmed, players may call reinforcements for assistance. Engage in intense battles across three distinctive sectors, each requiring strategic adaptation. Side objectives emerge during combat, providing essential resources used to summon elite Space Marines or a formidable Dreadnought, drastically shifting battlefield dynamics. Over on PC, the studio has added two new options. One is RTAO (Ray-Traced Ambient Occlusion), though this is currently listed as an experimental feature. Next, Nvidia 5000 series graphics card owners can now enable DLSS 4 for better upscaling tech as well as multi-frame generation. The complete patch notes for Patch 8, which includes details on the balance changes, can be found here. The Warhammer 40,000: Space Marine 2 Siege update is now available on PC, Xbox Series X|S, and PlayStation 5.
    • Microsoft updates Media Creation Tool with a newer Windows 11 release by Taras Buria If you want to download a Windows 11 image or create an install media, the Media Creation Tool app is one of the best options—simple, fast, and, more importantly, official. While there are other useful alternatives, such as Rufus, Media Creation Tool remains the default choice for those who simply want a clean Windows 11 installation on a supported computer. Thanks to the latest MCT update, you will have to deal with fewer updates after installing Windows 11. Microsoft has quietly updated the Media Creation Tool app so that it downloads the latest Windows 11 release, version 24H2, with build number 26100.4349. This is the most recent public Windows 11 update (June 2025 Patch Tuesday), which eliminates the need to download large updates for your PC after installing the operating system. You can download Media Creation Tool from the official Windows 11 website. If you are familiar with it, this simple app can generate a Windows 11 image with the language you need or create a bootable USB media. Note that it only works on Windows, so Linux or macOS users have to download Windows images directly from the official website and then use apps that are available on their platforms. Another thing worth noting is Media Creation Tool is not the right choice if you want to install Windows 11 on an unsupported PC. In such a case, you can use MCT to download an ISO and then create a modified install media with apps like Rufus or Ventoy as described in our dedicated guide. If you want a more exotic Windows 11 Edition, try the Oofhours Media Tool, which allows you to select Windows 10 or 11, architecture (x64, x86, or ARM64), language, and edition. In addition to standard Home and Pro, the application can download non-mainstream SKUs, such as Enterprise, Education, or Professional for Workstations. Via: Deskmodder
    • Putting premium on your higher end laptops really makes it feel like your lower end laptops are worse.
  • Recent Achievements

    • Conversation Starter
      Kavin25 earned a badge
      Conversation Starter
    • One Month Later
      Leonard grant earned a badge
      One Month Later
    • Week One Done
      pcdoctorsnet earned a badge
      Week One Done
    • Rising Star
      Phillip0web went up a rank
      Rising Star
    • One Month Later
      Epaminombas earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      541
    2. 2
      ATLien_0
      207
    3. 3
      +FloatingFatMan
      175
    4. 4
      Michael Scrip
      148
    5. 5
      snowy owl
      119
  • Tell a friend

    Love Neowin? Tell a friend!